Explorar o código

Added Jwt token

wpfat23-5 %!s(int64=2) %!d(string=hai) anos
achega
4e1037a852

+ 38 - 0
.gitignore

@@ -0,0 +1,38 @@
+target/
+!.mvn/wrapper/maven-wrapper.jar
+!**/src/main/**/target/
+!**/src/test/**/target/
+
+### IntelliJ IDEA ###
+.idea/modules.xml
+.idea/jarRepositories.xml
+.idea/compiler.xml
+.idea/libraries/
+*.iws
+*.iml
+*.ipr
+
+### Eclipse ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+
+### NetBeans ###
+/nbproject/private/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
+build/
+!**/src/main/**/build/
+!**/src/test/**/build/
+
+### VS Code ###
+.vscode/
+
+### Mac OS ###
+.DS_Store

+ 92 - 0
pom.xml

@@ -0,0 +1,92 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+
+    <groupId>org.example</groupId>
+    <artifactId>RentABike</artifactId>
+    <version>1.0-SNAPSHOT</version>
+
+    <properties>
+        <maven.compiler.source>11</maven.compiler.source>
+        <maven.compiler.target>11</maven.compiler.target>
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+    </properties>
+
+    <packaging>war</packaging>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-webmvc</artifactId>
+            <version>6.0.5</version>
+        </dependency>
+        <dependency>
+            <groupId>jakarta.servlet</groupId>
+            <artifactId>jakarta.servlet-api</artifactId>
+            <version>5.0.0</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.hibernate.orm</groupId>
+            <artifactId>hibernate-core</artifactId>
+            <version>6.1.7.Final</version>
+        </dependency>
+        <dependency>
+            <groupId>org.postgresql</groupId>
+            <artifactId>postgresql</artifactId>
+            <version>42.5.4</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.data</groupId>
+            <artifactId>spring-data-jpa</artifactId>
+            <version>3.0.3</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-dbcp2</artifactId>
+            <version>2.9.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.security</groupId>
+            <artifactId>spring-security-web</artifactId>
+            <version>6.0.2</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.tomcat.embed</groupId>
+            <artifactId>tomcat-embed-core</artifactId>
+            <version>9.0.73</version>
+        </dependency>
+        <!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt -->
+        <dependency>
+            <groupId>io.jsonwebtoken</groupId>
+            <artifactId>jjwt</artifactId>
+            <version>0.9.1</version>
+        </dependency>
+        <!-- https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt-api -->
+        <dependency>
+            <groupId>io.jsonwebtoken</groupId>
+            <artifactId>jjwt-api</artifactId>
+            <version>0.11.2</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.springframework.security</groupId>
+            <artifactId>spring-security-config</artifactId>
+            <version>5.7.7</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.security</groupId>
+            <artifactId>spring-security-jwt</artifactId>
+            <version>1.1.1.RELEASE</version>
+        </dependency>
+
+        <dependency>
+            <groupId>javax.xml.bind</groupId>
+            <artifactId>jaxb-api</artifactId>
+            <version>2.1</version>
+        </dependency>
+    </dependencies>
+
+</project>

+ 34 - 0
src/main/java/org/example/JwtFilter.java

@@ -0,0 +1,34 @@
+package org.example;
+
+import io.jsonwebtoken.Claims;
+import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.SignatureException;
+import jakarta.servlet.*;
+import jakarta.servlet.http.HttpServletRequest;
+
+
+import java.io.IOException;
+
+public class JwtFilter implements Filter {
+
+    @Override
+    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
+        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
+
+        String header = httpServletRequest.getHeader("authorization");
+
+        if (header == null || !header.startsWith("Bearer ")) {
+            throw new ServletException("Missing or invalid Authorization header");
+        } else {
+            try {
+                String token = header.substring(7);
+                Claims claims = Jwts.parser().setSigningKey("example").parseClaimsJws(token).getBody();
+                servletRequest.setAttribute("claims", claims);
+            } catch (final SignatureException e) {
+                throw new ServletException("Invalid token");
+            }
+        }
+        filterChain.doFilter(servletRequest, servletResponse);
+    }
+
+}

+ 23 - 0
src/main/java/org/example/configuration/AppInitializer.java

@@ -0,0 +1,23 @@
+package org.example.configuration;
+
+import javax.servlet.Filter;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+
+import jakarta.servlet.FilterRegistration;
+import jakarta.servlet.ServletRegistration;
+import org.example.JwtFilter;
+import org.springframework.web.filter.DelegatingFilterProxy;
+import org.springframework.web.WebApplicationInitializer;
+import org.springframework.web.servlet.DispatcherServlet;
+
+public class AppInitializer implements WebApplicationInitializer {
+
+
+    @Override
+    public void onStartup(jakarta.servlet.ServletContext servletContext) {
+        // Register your JwtFilter
+        FilterRegistration.Dynamic jwtFilter = servletContext.addFilter("JwtFilter", JwtFilter.class);
+        jwtFilter.addMappingForUrlPatterns(null, false, "/api/*");
+    }
+}

+ 68 - 0
src/main/java/org/example/configuration/HibernatePersistenceConfiguration.java

@@ -0,0 +1,68 @@
+package org.example.configuration;
+
+import jakarta.persistence.EntityManagerFactory;
+import org.apache.commons.dbcp2.BasicDataSource;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+import org.springframework.orm.jpa.JpaTransactionManager;
+import org.springframework.orm.jpa.JpaVendorAdapter;
+import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
+import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+import javax.sql.DataSource;
+import java.util.Properties;
+
+@Configuration
+@EnableJpaRepositories(basePackages={"org.example"})
+@EnableTransactionManagement
+public class HibernatePersistenceConfiguration {
+
+    // Hibernate configuration
+    @Bean(name = "dataSource")
+    public DataSource getDataSource() {
+        BasicDataSource dataSource = new BasicDataSource();
+        dataSource.setDriverClassName("org.postgresql.Driver");
+        dataSource.setUrl("jdbc:postgresql://localhost:5432/RentABike?characterEncoding=utf-8");
+        dataSource.setUsername("postgres");
+        dataSource.setPassword("postgres");
+        return dataSource;
+    }
+
+    private Properties getHibernateProperties() {
+        Properties properties = new Properties();
+        properties.put("hibernate.show_sql", "true");
+        properties.put("hibernate.hbm2ddl.auto", "update");
+        properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
+        properties.put("hibernate.default_schema", "public");
+        return properties;
+    }
+
+    // JPA
+    @Bean
+    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
+        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
+        em.setDataSource(getDataSource());
+        em.setPackagesToScan(new String[] { "org.example" });
+
+        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
+        em.setJpaVendorAdapter(vendorAdapter);
+        em.setJpaProperties(getHibernateProperties());
+        return em;
+    }
+
+    @Bean
+    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
+        JpaTransactionManager transactionManager = new JpaTransactionManager();
+        transactionManager.setEntityManagerFactory(emf);
+        return transactionManager;
+    }
+
+    @Bean
+    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
+        return new PersistenceExceptionTranslationPostProcessor();
+    }
+
+}

+ 33 - 0
src/main/java/org/example/configuration/SpringInit.java

@@ -0,0 +1,33 @@
+package org.example.configuration;
+
+import jakarta.servlet.Filter;
+import org.example.JwtFilter;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
+
+@Configuration
+@ComponentScan("org.example")
+public class SpringInit extends AbstractAnnotationConfigDispatcherServletInitializer {
+
+    protected Class<?>[] getRootConfigClasses() {
+        return new Class[] {HibernatePersistenceConfiguration.class};
+    }
+
+    protected Class<?>[] getServletConfigClasses() {
+        return new Class[]{SpringInit.class};
+    }
+
+    protected String[] getServletMappings() {
+        return new String[]{"/"};
+    }
+
+/*
+    @Override
+    protected Filter[] getServletFilters() {
+        return new Filter[]{new JwtFilter()};
+    }
+*/
+
+}
+

+ 24 - 0
src/main/java/org/example/controller/HelloController.java

@@ -0,0 +1,24 @@
+package org.example.controller;
+
+import org.example.domain.User;
+import org.example.repository.UserRepository;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController("api")
+public class HelloController {
+
+    @Autowired
+    UserRepository userRepository;
+
+    @RequestMapping ("/hello")
+    public String helloWord() {
+        userRepository.save(new User("login", "pass"));
+
+        return "a";
+    }
+}

+ 28 - 0
src/main/java/org/example/controller/LoginController.java

@@ -0,0 +1,28 @@
+package org.example.controller;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.SignatureAlgorithm;
+import org.example.domain.LoginRequest;
+import org.springframework.http.MediaType;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.util.Date;
+
+@RestController
+public class LoginController {
+    @RequestMapping(value="/login")
+    public String login() {
+        long currentTimeMillis = System.currentTimeMillis();
+        return Jwts.builder()
+                .setSubject("user.getLogin()")
+                .claim("roles","user")
+                .setIssuedAt(new Date(currentTimeMillis))
+                .setExpiration(new Date(currentTimeMillis + 60 * 60 * 1000)) //60min
+                .signWith(SignatureAlgorithm.HS256, "example")
+                .compact();
+    }
+}

+ 22 - 0
src/main/java/org/example/domain/LoginRequest.java

@@ -0,0 +1,22 @@
+package org.example.domain;
+
+public class LoginRequest {
+    private String login;
+    private String password;
+
+    public String getLogin() {
+        return login;
+    }
+
+    public void setLogin(String login) {
+        this.login = login;
+    }
+
+    public String getPassword() {
+        return password;
+    }
+
+    public void setPassword(String password) {
+        this.password = password;
+    }
+}

+ 49 - 0
src/main/java/org/example/domain/User.java

@@ -0,0 +1,49 @@
+package org.example.domain;
+
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+
+@Entity
+public class User {
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    private Long id;
+
+    public String getLogin() {
+        return login;
+    }
+
+    public void setLogin(String login) {
+        this.login = login;
+    }
+
+    public String getPassword() {
+        return password;
+    }
+
+    public void setPassword(String password) {
+        this.password = password;
+    }
+
+    private String login;
+    private String password;
+
+    public User(String login, String password) {
+        this.login = login;
+        this.password = password;
+    }
+
+    public User() {
+
+    }
+
+    public void setId(Long id) {
+        this.id = id;
+    }
+
+    public Long getId() {
+        return id;
+    }
+}

+ 16 - 0
src/main/java/org/example/repository/UserRepository.java

@@ -0,0 +1,16 @@
+package org.example.repository;
+
+import jakarta.transaction.Transactional;
+import org.example.domain.User;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.stereotype.Repository;
+
+import java.util.List;
+
+@Transactional
+@Repository
+public interface UserRepository extends JpaRepository<User, Long> {
+    User findById(long id);
+    User findByLogin(String login);
+    User findByLoginAndPassword(String login, String password);
+}