-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Jwt #11
Merged
Jwt #11
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
31 changes: 25 additions & 6 deletions
31
src/main/java/project/bookstore/config/SecurityConfig.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,44 +1,63 @@ | ||
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; | ||
import org.springframework.security.authentication.AuthenticationManager; | ||
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; | ||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; | ||
import org.springframework.security.config.annotation.web.builders.HttpSecurity; | ||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; | ||
import org.springframework.security.config.http.SessionCreationPolicy; | ||
import org.springframework.security.core.userdetails.UserDetailsService; | ||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; | ||
import org.springframework.security.crypto.password.PasswordEncoder; | ||
import org.springframework.security.web.SecurityFilterChain; | ||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; | ||
import project.bookstore.security.JwtAuthenticationFilter; | ||
|
||
@Configuration | ||
@EnableMethodSecurity | ||
@RequiredArgsConstructor | ||
public class SecurityConfig { | ||
private final UserDetailsService userDetailsService; | ||
private final UserDetailsService service; | ||
private final JwtAuthenticationFilter jwtAuthenticationFilter; | ||
|
||
@Bean | ||
public PasswordEncoder passwordEncoder() { | ||
return new BCryptPasswordEncoder(); | ||
} | ||
|
||
@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( | ||
"/auth/**", | ||
"/swagger-ui/**", | ||
"/v3/api-docs/**" | ||
antMatcher("/auth/**"), | ||
antMatcher("/swagger-ui/**"), | ||
antMatcher("/v3/api-docs/**") | ||
) | ||
.permitAll() | ||
.anyRequest() | ||
.authenticated() | ||
) | ||
.userDetailsService(userDetailsService) | ||
.sessionManagement( | ||
s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) | ||
.addFilterBefore(jwtAuthenticationFilter, | ||
UsernamePasswordAuthenticationFilter.class) | ||
.userDetailsService(service) | ||
.build(); | ||
} | ||
|
||
@Bean | ||
public AuthenticationManager authenticationManager( | ||
AuthenticationConfiguration authenticationConfiguration | ||
) throws Exception { | ||
return authenticationConfiguration.getAuthenticationManager(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
17 changes: 17 additions & 0 deletions
17
src/main/java/project/bookstore/dto/user/UserLoginRequestDto.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
package project.bookstore.dto.user; | ||
|
||
import jakarta.validation.constraints.Email; | ||
import jakarta.validation.constraints.NotBlank; | ||
import jakarta.validation.constraints.Size; | ||
|
||
public record UserLoginRequestDto( | ||
@NotBlank | ||
@Size(min = 6, max = 20) | ||
String email, | ||
@NotBlank | ||
@Size(min = 6, max = 20) | ||
String password | ||
) { | ||
|
||
} |
4 changes: 4 additions & 0 deletions
4
src/main/java/project/bookstore/dto/user/UserLoginResponseDto.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
package project.bookstore.dto.user; | ||
|
||
public record UserLoginResponseDto(String token) { | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
24 changes: 24 additions & 0 deletions
24
src/main/java/project/bookstore/security/AuthenticationService.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
package project.bookstore.security; | ||
|
||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.security.authentication.AuthenticationManager; | ||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
import org.springframework.security.core.Authentication; | ||
import org.springframework.stereotype.Service; | ||
import project.bookstore.dto.user.UserLoginRequestDto; | ||
import project.bookstore.dto.user.UserLoginResponseDto; | ||
|
||
@RequiredArgsConstructor | ||
@Service | ||
public class AuthenticationService { | ||
private final JwtUtil jwtUtil; | ||
private final AuthenticationManager authenticationManager; | ||
|
||
public UserLoginResponseDto authenticate(UserLoginRequestDto requestDto) { | ||
final Authentication authentication = authenticationManager.authenticate( | ||
new UsernamePasswordAuthenticationToken(requestDto.email(), requestDto.password()) | ||
); | ||
String token = jwtUtil.generateToken(authentication.getName()); | ||
return new UserLoginResponseDto(token); | ||
} | ||
} |
47 changes: 47 additions & 0 deletions
47
src/main/java/project/bookstore/security/JwtAuthenticationFilter.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
package project.bookstore.security; | ||
|
||
import jakarta.servlet.FilterChain; | ||
import jakarta.servlet.ServletException; | ||
import jakarta.servlet.http.HttpServletRequest; | ||
import jakarta.servlet.http.HttpServletResponse; | ||
import java.io.IOException; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.http.HttpHeaders; | ||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
import org.springframework.security.core.Authentication; | ||
import org.springframework.security.core.context.SecurityContextHolder; | ||
import org.springframework.security.core.userdetails.UserDetails; | ||
import org.springframework.security.core.userdetails.UserDetailsService; | ||
import org.springframework.stereotype.Component; | ||
import org.springframework.util.StringUtils; | ||
import org.springframework.web.filter.OncePerRequestFilter; | ||
|
||
@RequiredArgsConstructor | ||
@Component | ||
public class JwtAuthenticationFilter extends OncePerRequestFilter { | ||
private static final String TOKEN_HEADER = "Bearer "; | ||
private final JwtUtil jwtUtil; | ||
private final UserDetailsService service; | ||
|
||
@Override | ||
protected void doFilterInternal( | ||
HttpServletRequest request, | ||
HttpServletResponse response, | ||
FilterChain filterChain | ||
) throws ServletException, IOException { | ||
String token = getToken(request); | ||
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 token = request.getHeader(HttpHeaders.AUTHORIZATION); | ||
return (StringUtils.hasText(token) && token.startsWith(TOKEN_HEADER)) | ||
? token.substring(TOKEN_HEADER.length()) : null; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
package project.bookstore.security; | ||
|
||
import io.jsonwebtoken.Claims; | ||
import io.jsonwebtoken.JwtException; | ||
import io.jsonwebtoken.Jwts; | ||
import io.jsonwebtoken.security.Keys; | ||
import java.nio.charset.StandardCharsets; | ||
import java.util.Date; | ||
import java.util.function.Function; | ||
import javax.crypto.SecretKey; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.stereotype.Component; | ||
|
||
@Component | ||
public class JwtUtil { | ||
@Value("${jwt.expiration}") | ||
private long expiration; | ||
private final SecretKey secret; | ||
|
||
public JwtUtil(@Value(value = "${jwt.secret}") String secretString) { | ||
secret = Keys.hmacShaKeyFor(secretString.getBytes(StandardCharsets.UTF_8)); | ||
} | ||
|
||
public String generateToken(String username) { | ||
return Jwts.builder() | ||
.subject(username) | ||
.expiration(new Date(System.currentTimeMillis() + expiration)) | ||
.signWith(secret) | ||
.compact(); | ||
} | ||
|
||
public boolean isValidToken(String token) { | ||
try { | ||
return !getClaimFromToken(token, Claims::getExpiration).before(new Date()); | ||
} catch (JwtException | IllegalArgumentException e) { | ||
throw new JwtException("Expired or invalid JWT token", e); | ||
} | ||
} | ||
|
||
public String getUserName(String token) { | ||
return getClaimFromToken(token, Claims::getSubject); | ||
} | ||
|
||
private <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) { | ||
final Claims claims = Jwts.parser() | ||
.verifyWith((SecretKey) secret) | ||
.build() | ||
.parseSignedClaims(token) | ||
.getPayload(); | ||
return claimsResolver.apply(claims); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
14 changes: 0 additions & 14 deletions
14
src/main/resources/db/changelog/changes/06-add-isDeleted-to-users.yaml
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
add swagger annotation