Skip to content

Commit

Permalink
jwt_done
Browse files Browse the repository at this point in the history
  • Loading branch information
ChabVlad committed Sep 23, 2024
1 parent 8de7342 commit 1720c7a
Show file tree
Hide file tree
Showing 6 changed files with 33 additions and 68 deletions.
23 changes: 11 additions & 12 deletions src/main/java/project/bookstore/config/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -20,7 +22,7 @@
@EnableMethodSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final UserDetailsService userDetailsService;
private final UserDetailsService service;
private final JwtAuthenticationFilter jwtAuthenticationFilter;

@Bean
Expand All @@ -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();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,43 +21,27 @@
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(
HttpServletRequest request,
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;
}
}
20 changes: 6 additions & 14 deletions src/main/java/project/bookstore/security/JwtUtil.java
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -18,29 +17,23 @@ 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();
}

public boolean isValidToken(String token) {
try {
Jws<Claims> 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);
}
}

Expand All @@ -50,11 +43,10 @@ public String getUserName(String token) {

private <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claims = Jwts.parser()
.verifyWith(secret)
.verifyWith((SecretKey) secret)
.build()
.parseSignedClaims(token)
.getPayload();

return claimsResolver.apply(claims);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,10 @@ databaseChangeLog:
nullable: false
- column:
name: shipping_address
type: varchar(255)
type: varchar(255)
- column:
name: is_deleted
type: tinyint
defaultValueBoolean: false
constraints:
nullable: false

This file was deleted.

2 changes: 0 additions & 2 deletions src/main/resources/db/changelog/db.changelog-master.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 1720c7a

Please sign in to comment.