From 1720c7a1e26d2cd7c8b2e22bbcbc94aa75041db2 Mon Sep 17 00:00:00 2001 From: ChabVlad Date: Mon, 23 Sep 2024 16:07:14 +0400 Subject: [PATCH] jwt_done --- .../bookstore/config/SecurityConfig.java | 23 ++++++------- .../security/JwtAuthenticationFilter.java | 34 +++++-------------- .../project/bookstore/security/JwtUtil.java | 20 ++++------- .../changes/02-create-users-table.yaml | 8 ++++- .../changes/06-add-isDeleted-to-users.yaml | 14 -------- .../db/changelog/db.changelog-master.yaml | 2 -- 6 files changed, 33 insertions(+), 68 deletions(-) delete mode 100644 src/main/resources/db/changelog/changes/06-add-isDeleted-to-users.yaml diff --git a/src/main/java/project/bookstore/config/SecurityConfig.java b/src/main/java/project/bookstore/config/SecurityConfig.java index c451686..a36b31e 100644 --- a/src/main/java/project/bookstore/config/SecurityConfig.java +++ b/src/main/java/project/bookstore/config/SecurityConfig.java @@ -1,5 +1,7 @@ package project.bookstore.config; +import static org.springframework.security.web.util.matcher.AntPathRequestMatcher.antMatcher; + import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -20,7 +22,7 @@ @EnableMethodSecurity @RequiredArgsConstructor public class SecurityConfig { - private final UserDetailsService userDetailsService; + private final UserDetailsService service; private final JwtAuthenticationFilter jwtAuthenticationFilter; @Bean @@ -29,28 +31,25 @@ public PasswordEncoder passwordEncoder() { } @Bean - public SecurityFilterChain getSecurityFilterChain(HttpSecurity http) throws Exception { + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { return http .cors(AbstractHttpConfigurer::disable) .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests( auth -> auth .requestMatchers( - "/api/auth/**", - "/api/swagger-ui/**", - "/api/v3/api-docs/**" - ) + antMatcher("/auth/**"), + antMatcher("/swagger-ui/**"), + antMatcher("/v3/api-docs/**")) .permitAll() .anyRequest() .authenticated() ) - .addFilterBefore( - jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class - ) .sessionManagement( - session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS - )) - .userDetailsService(userDetailsService) + s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .addFilterBefore(jwtAuthenticationFilter, + UsernamePasswordAuthenticationFilter.class) + .userDetailsService(service) .build(); } diff --git a/src/main/java/project/bookstore/security/JwtAuthenticationFilter.java b/src/main/java/project/bookstore/security/JwtAuthenticationFilter.java index 2666c6b..1a1bdc3 100644 --- a/src/main/java/project/bookstore/security/JwtAuthenticationFilter.java +++ b/src/main/java/project/bookstore/security/JwtAuthenticationFilter.java @@ -21,7 +21,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter { private static final String TOKEN_HEADER = "Bearer "; private final JwtUtil jwtUtil; - private final UserDetailsService userDetailsService; + private final UserDetailsService service; @Override protected void doFilterInternal( @@ -29,35 +29,19 @@ protected void doFilterInternal( HttpServletResponse response, FilterChain filterChain ) throws ServletException, IOException { - /*String path = request.getRequestURI(); - if ( - path.startsWith("/api/auth") - || path.startsWith("/api/swagger-ui") - || path.startsWith("/api/v3/api-docs")) { - filterChain.doFilter(request, response); - return; - } - - */ - String token = getToken(request); - boolean isTokenValid = jwtUtil.isValidToken(token); - if (token != null && isTokenValid) { - String userName = jwtUtil.getUserName(token); - UserDetails userDetails = userDetailsService.loadUserByUsername(userName); - Authentication auth = new UsernamePasswordAuthenticationToken( - userDetails, null, userDetails.getAuthorities() - ); - SecurityContextHolder.getContext().setAuthentication(auth); + if (token != null && jwtUtil.isValidToken(token)) { + UserDetails userDetails = service.loadUserByUsername(jwtUtil.getUserName(token)); + Authentication authentication = new UsernamePasswordAuthenticationToken( + userDetails, null, userDetails.getAuthorities()); + SecurityContextHolder.getContext().setAuthentication(authentication); } filterChain.doFilter(request, response); } private String getToken(HttpServletRequest request) { - String bearerToken = request.getHeader(HttpHeaders.AUTHORIZATION); - if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(TOKEN_HEADER)) { - return bearerToken.substring(TOKEN_HEADER.length()); - } - return null; + String token = request.getHeader(HttpHeaders.AUTHORIZATION); + return (StringUtils.hasText(token) && token.startsWith(TOKEN_HEADER)) + ? token.substring(TOKEN_HEADER.length()) : null; } } diff --git a/src/main/java/project/bookstore/security/JwtUtil.java b/src/main/java/project/bookstore/security/JwtUtil.java index 518f8ff..b571dd8 100644 --- a/src/main/java/project/bookstore/security/JwtUtil.java +++ b/src/main/java/project/bookstore/security/JwtUtil.java @@ -1,7 +1,6 @@ package project.bookstore.security; import io.jsonwebtoken.Claims; -import io.jsonwebtoken.Jws; import io.jsonwebtoken.JwtException; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.security.Keys; @@ -18,14 +17,13 @@ public class JwtUtil { private long expiration; private final SecretKey secret; - private JwtUtil(@Value("${jwt.secret}") String secretString) { + public JwtUtil(@Value(value = "${jwt.secret}") String secretString) { secret = Keys.hmacShaKeyFor(secretString.getBytes(StandardCharsets.UTF_8)); } - public String generateToken(String name) { + public String generateToken(String username) { return Jwts.builder() - .subject(name) - .issuedAt(new Date(System.currentTimeMillis())) + .subject(username) .expiration(new Date(System.currentTimeMillis() + expiration)) .signWith(secret) .compact(); @@ -33,14 +31,9 @@ public String generateToken(String name) { public boolean isValidToken(String token) { try { - Jws claimsJws = Jwts.parser() - .verifyWith(secret) - .build() - .parseSignedClaims(token); - - return !claimsJws.getPayload().getExpiration().before(new Date()); + return !getClaimFromToken(token, Claims::getExpiration).before(new Date()); } catch (JwtException | IllegalArgumentException e) { - throw new JwtException("Expired or invalid Jwt token", e); + throw new JwtException("Expired or invalid JWT token", e); } } @@ -50,11 +43,10 @@ public String getUserName(String token) { private T getClaimFromToken(String token, Function claimsResolver) { final Claims claims = Jwts.parser() - .verifyWith(secret) + .verifyWith((SecretKey) secret) .build() .parseSignedClaims(token) .getPayload(); - return claimsResolver.apply(claims); } } diff --git a/src/main/resources/db/changelog/changes/02-create-users-table.yaml b/src/main/resources/db/changelog/changes/02-create-users-table.yaml index 00b0b96..3b45732 100644 --- a/src/main/resources/db/changelog/changes/02-create-users-table.yaml +++ b/src/main/resources/db/changelog/changes/02-create-users-table.yaml @@ -36,4 +36,10 @@ databaseChangeLog: nullable: false - column: name: shipping_address - type: varchar(255) \ No newline at end of file + type: varchar(255) + - column: + name: is_deleted + type: tinyint + defaultValueBoolean: false + constraints: + nullable: false diff --git a/src/main/resources/db/changelog/changes/06-add-isDeleted-to-users.yaml b/src/main/resources/db/changelog/changes/06-add-isDeleted-to-users.yaml deleted file mode 100644 index dcab0c6..0000000 --- a/src/main/resources/db/changelog/changes/06-add-isDeleted-to-users.yaml +++ /dev/null @@ -1,14 +0,0 @@ -databaseChangeLog: - - changeSet: - id: add-isDeleted-to-users - author: vlad - changes: - - addColumn: - tableName: users - columns: - - column: - name: is_deleted - type: tinyint - defaultValueBoolean: false - constraints: - nullable: false diff --git a/src/main/resources/db/changelog/db.changelog-master.yaml b/src/main/resources/db/changelog/db.changelog-master.yaml index 19df5dd..ec80400 100644 --- a/src/main/resources/db/changelog/db.changelog-master.yaml +++ b/src/main/resources/db/changelog/db.changelog-master.yaml @@ -9,5 +9,3 @@ databaseChangeLog: file: db/changelog/changes/04-create-users-roles-table.yaml - include: file: db/changelog/changes/05-insert-users-to-db.yaml - - include: - file: db/changelog/changes/06-add-isDeleted-to-users.yaml