初始化提交中文测试环境

This commit is contained in:
YuCheng Hu 2022-10-02 08:11:30 -04:00
parent edaf3082e0
commit 1d09caaae7
21 changed files with 185 additions and 161 deletions

130
pom.xml
View File

@ -1,77 +1,79 @@
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.3</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.bezkoder</groupId>
<artifactId>spring-boot-security-jwt</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-security-jwt</name>
<description>Demo project for Spring Boot Security - JWT</description>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.bezkoder</groupId>
<artifactId>spring-boot-security-jwt</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-security-jwt</name>
<description>Demo project for Spring Boot Security - JWT</description>
<properties>
<java.version>1.8</java.version>
</properties>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<!-- DATABASE AND HIBERNATE -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
<version>2.1.214</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,4 +1,4 @@
package com.bezkoder.springjwt;
package com.ossez.spring.security;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

View File

@ -1,4 +1,4 @@
package com.bezkoder.springjwt.controllers;
package com.ossez.spring.security.controllers;
import java.util.HashSet;
import java.util.List;
@ -7,6 +7,14 @@ import java.util.stream.Collectors;
import javax.validation.Valid;
import com.ossez.spring.security.models.ERole;
import com.ossez.spring.security.models.Role;
import com.ossez.spring.security.payload.request.LoginRequest;
import com.ossez.spring.security.payload.request.SignupRequest;
import com.ossez.spring.security.payload.response.JwtResponse;
import com.ossez.spring.security.payload.response.MessageResponse;
import com.ossez.spring.security.security.jwt.JwtUtils;
import com.ossez.spring.security.security.services.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
@ -20,21 +28,13 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bezkoder.springjwt.models.ERole;
import com.bezkoder.springjwt.models.Role;
import com.bezkoder.springjwt.models.User;
import com.bezkoder.springjwt.payload.request.LoginRequest;
import com.bezkoder.springjwt.payload.request.SignupRequest;
import com.bezkoder.springjwt.payload.response.JwtResponse;
import com.bezkoder.springjwt.payload.response.MessageResponse;
import com.bezkoder.springjwt.repository.RoleRepository;
import com.bezkoder.springjwt.repository.UserRepository;
import com.bezkoder.springjwt.security.jwt.JwtUtils;
import com.bezkoder.springjwt.security.services.UserDetailsImpl;
import com.ossez.spring.security.models.User;
import com.ossez.spring.security.repository.RoleRepository;
import com.ossez.spring.security.repository.UserRepository;
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/auth")
@RequestMapping("/custom")
public class AuthController {
@Autowired
AuthenticationManager authenticationManager;
@ -60,19 +60,19 @@ public class AuthController {
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
List<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toList());
return ResponseEntity.ok(new JwtResponse(jwt,
return ResponseEntity.ok(new JwtResponse(jwt,
userDetails.getId(),
userDetails.getUsername(),
userDetails.getEmail(),
roles));
}
@PostMapping("/signup")
@PostMapping("/register")
public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {
if (userRepository.existsByUsername(signUpRequest.getUsername())) {
return ResponseEntity

View File

@ -1,4 +1,4 @@
package com.bezkoder.springjwt.controllers;
package com.ossez.spring.security.controllers;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.CrossOrigin;

View File

@ -1,4 +1,4 @@
package com.bezkoder.springjwt.models;
package com.ossez.spring.security.models;
public enum ERole {
ROLE_USER,

View File

@ -1,4 +1,4 @@
package com.bezkoder.springjwt.models;
package com.ossez.spring.security.models;
import javax.persistence.*;

View File

@ -1,4 +1,4 @@
package com.bezkoder.springjwt.models;
package com.ossez.spring.security.models;
import java.util.HashSet;
import java.util.Set;

View File

@ -1,4 +1,4 @@
package com.bezkoder.springjwt.payload.request;
package com.ossez.spring.security.payload.request;
import javax.validation.constraints.NotBlank;

View File

@ -1,4 +1,4 @@
package com.bezkoder.springjwt.payload.request;
package com.ossez.spring.security.payload.request;
import java.util.Set;

View File

@ -1,4 +1,4 @@
package com.bezkoder.springjwt.payload.response;
package com.ossez.spring.security.payload.response;
import java.util.List;

View File

@ -1,4 +1,4 @@
package com.bezkoder.springjwt.payload.response;
package com.ossez.spring.security.payload.response;
public class MessageResponse {
private String message;

View File

@ -1,13 +1,12 @@
package com.bezkoder.springjwt.repository;
package com.ossez.spring.security.repository;
import java.util.Optional;
import com.ossez.spring.security.models.ERole;
import com.ossez.spring.security.models.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.bezkoder.springjwt.models.ERole;
import com.bezkoder.springjwt.models.Role;
@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
Optional<Role> findByName(ERole name);

View File

@ -1,11 +1,11 @@
package com.bezkoder.springjwt.repository;
package com.ossez.spring.security.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.bezkoder.springjwt.models.User;
import com.ossez.spring.security.models.User;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {

View File

@ -1,4 +1,4 @@
package com.bezkoder.springjwt.security;
package com.ossez.spring.security.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
@ -17,57 +17,57 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.bezkoder.springjwt.security.jwt.AuthEntryPointJwt;
import com.bezkoder.springjwt.security.jwt.AuthTokenFilter;
import com.bezkoder.springjwt.security.services.UserDetailsServiceImpl;
import com.ossez.spring.security.security.jwt.AuthEntryPointJwt;
import com.ossez.spring.security.security.jwt.AuthTokenFilter;
import com.ossez.spring.security.security.services.UserDetailsServiceImpl;
@Configuration
@EnableGlobalMethodSecurity(
// securedEnabled = true,
// jsr250Enabled = true,
prePostEnabled = true)
// securedEnabled = true,
// jsr250Enabled = true,
prePostEnabled = true)
public class WebSecurityConfig { // extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsServiceImpl userDetailsService;
@Autowired
UserDetailsServiceImpl userDetailsService;
@Autowired
private AuthEntryPointJwt unauthorizedHandler;
@Autowired
private AuthEntryPointJwt unauthorizedHandler;
@Bean
public AuthTokenFilter authenticationJwtTokenFilter() {
return new AuthTokenFilter();
}
@Bean
public AuthTokenFilter authenticationJwtTokenFilter() {
return new AuthTokenFilter();
}
// @Override
// public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
// authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
// }
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
// @Bean
// @Override
// public AuthenticationManager authenticationManagerBean() throws Exception {
// return super.authenticationManagerBean();
// }
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
return authConfig.getAuthenticationManager();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
return authConfig.getAuthenticationManager();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
// @Override
// protected void configure(HttpSecurity http) throws Exception {
@ -80,20 +80,21 @@ public class WebSecurityConfig { // extends WebSecurityConfigurerAdapter {
//
// http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
// }
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests().antMatchers("/api/auth/**").permitAll()
.antMatchers("/api/test/**").permitAll()
.anyRequest().authenticated();
http.authenticationProvider(authenticationProvider());
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests().antMatchers("/h2-console/**").permitAll()
.antMatchers("/api/test/**").permitAll()
.anyRequest().authenticated();
http.authenticationProvider(authenticationProvider());
http.headers().frameOptions().sameOrigin();
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}

View File

@ -1,4 +1,4 @@
package com.bezkoder.springjwt.security.jwt;
package com.ossez.spring.security.security.jwt;
import java.io.IOException;
import java.util.HashMap;

View File

@ -1,4 +1,4 @@
package com.bezkoder.springjwt.security.jwt;
package com.ossez.spring.security.security.jwt;
import java.io.IOException;
@ -7,6 +7,7 @@ import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ossez.spring.security.security.services.UserDetailsServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@ -17,8 +18,6 @@ import org.springframework.security.web.authentication.WebAuthenticationDetailsS
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import com.bezkoder.springjwt.security.services.UserDetailsServiceImpl;
public class AuthTokenFilter extends OncePerRequestFilter {
@Autowired
private JwtUtils jwtUtils;

View File

@ -1,4 +1,4 @@
package com.bezkoder.springjwt.security.jwt;
package com.ossez.spring.security.security.jwt;
import java.util.Date;
@ -8,7 +8,7 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.bezkoder.springjwt.security.services.UserDetailsImpl;
import com.ossez.spring.security.security.services.UserDetailsImpl;
import io.jsonwebtoken.*;
@Component

View File

@ -1,4 +1,4 @@
package com.bezkoder.springjwt.security.services;
package com.ossez.spring.security.security.services;
import java.util.Collection;
import java.util.List;
@ -9,7 +9,7 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.bezkoder.springjwt.models.User;
import com.ossez.spring.security.models.User;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class UserDetailsImpl implements UserDetails {

View File

@ -1,4 +1,4 @@
package com.bezkoder.springjwt.security.services;
package com.ossez.spring.security.security.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
@ -7,8 +7,8 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.bezkoder.springjwt.models.User;
import com.bezkoder.springjwt.repository.UserRepository;
import com.ossez.spring.security.models.User;
import com.ossez.spring.security.repository.UserRepository;
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

View File

@ -1,9 +1,32 @@
spring.datasource.url= jdbc:mysql://localhost:3306/testdb?useSSL=false
spring.datasource.username= root
spring.datasource.password= 123456
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
spring.jpa.hibernate.use-new-id-generator-mappings=false
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto= update
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:test;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.sql.init.schema-locations=classpath:db/schema.sql
spring.datasource.hikari.connection-timeout=50000
spring.datasource.hikari.idle-timeout=300000
spring.datasource.hikari.max-lifetime=900000
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.minimum-idle=10
spring.datasource.hikari.pool-name=ConnPool
spring.datasource.hikari.connection-test-query=select 1 from dual
spring.datasource.hikari.data-source-properties.cachePrepStmts=true
spring.datasource.hikari.data-source-properties.prepStmtCacheSize=250
spring.datasource.hikari.data-source-properties.prepStmtCacheSqlLimit=2048
spring.datasource.hikari.data-source-properties.useServerPrepStmts=true
spring.datasource.hikari.data-source-properties.useLocalSessionState=true
spring.datasource.hikari.data-source-properties.rewriteBatchedStatements=true
spring.datasource.hikari.data-source-properties.cacheResultSetMetadata=true
spring.datasource.hikari.data-source-properties.cacheServerConfiguration=true
spring.datasource.hikari.data-source-properties.elideSetAutoCommits=true
spring.datasource.hikari.data-source-properties.maintainTimeStats=false
# App Properties
bezkoder.app.jwtSecret= bezKoderSecretKey

View File

@ -1,4 +1,4 @@
package com.bezkoder.springjwt;
package com.ossez.spring.security;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;