-
Notifications
You must be signed in to change notification settings - Fork 6
Dagim H. #3
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
Open
Unlock7
wants to merge
5
commits into
HackYourAssignment:main
Choose a base branch
from
Unlock7:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Dagim H. #3
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
fc4ac64
build: add JWT dependencies and application configuration
Unlock7 c5cabaa
feat: configure JWT authentication with Spring Security
Unlock7 59ebb03
feat: implement secure user registration
Unlock7 8a21f39
feat: implement JWT login and logout
Unlock7 f2185a4
chore: finalize security application setup
Unlock7 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 hidden or 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 |
|---|---|---|
|
|
@@ -189,4 +189,6 @@ build/ | |
| !**/src/test/**/build/ | ||
|
|
||
| ### VS Code ### | ||
| .vscode/ | ||
| .vscode/ | ||
|
|
||
| .env | ||
This file contains hidden or 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 hidden or 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 hidden or 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
62 changes: 62 additions & 0 deletions
62
src/main/java/net/hackyourfuture/security/authentication/JwtAuthenticationFilter.java
This file contains hidden or 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,62 @@ | ||
| package net.hackyourfuture.security.authentication; | ||
|
|
||
| import jakarta.servlet.FilterChain; | ||
| import jakarta.servlet.ServletException; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.servlet.http.HttpServletResponse; | ||
| import lombok.AllArgsConstructor; | ||
| import net.hackyourfuture.security.user.User; | ||
| import net.hackyourfuture.security.user.UserRepository; | ||
| import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
| import org.springframework.security.core.context.SecurityContextHolder; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.web.filter.OncePerRequestFilter; | ||
|
|
||
| import java.io.IOException; | ||
| import java.util.List; | ||
|
|
||
| @Component | ||
| @AllArgsConstructor | ||
| public class JwtAuthenticationFilter extends OncePerRequestFilter { | ||
|
|
||
| private final JwtService jwtService; | ||
| private final UserRepository userRepository; | ||
|
|
||
| @Override | ||
| protected void doFilterInternal( | ||
| HttpServletRequest request, | ||
| HttpServletResponse response, | ||
| FilterChain filterChain | ||
| ) throws ServletException, IOException { | ||
|
|
||
| String header = request.getHeader("Authorization"); | ||
|
|
||
| if (header == null || !header.startsWith("Bearer ")) { | ||
| filterChain.doFilter(request, response); | ||
| return; | ||
| } | ||
|
|
||
| String token = header.substring(7); | ||
|
|
||
| if (!jwtService.isTokenValid(token)) { | ||
| filterChain.doFilter(request, response); | ||
| return; | ||
| } | ||
|
|
||
| String username = jwtService.extractUsername(token); | ||
| User user = userRepository.findByUsername(username); | ||
|
|
||
| if (user != null) { | ||
| UsernamePasswordAuthenticationToken authentication = | ||
| new UsernamePasswordAuthenticationToken( | ||
| user.getUsername(), | ||
| null, | ||
| List.of() | ||
| ); | ||
|
|
||
| SecurityContextHolder.getContext().setAuthentication(authentication); | ||
| } | ||
|
|
||
| filterChain.doFilter(request, response); | ||
| } | ||
| } |
48 changes: 48 additions & 0 deletions
48
src/main/java/net/hackyourfuture/security/authentication/JwtService.java
This file contains hidden or 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,48 @@ | ||
| package net.hackyourfuture.security.authentication; | ||
|
|
||
| import io.jsonwebtoken.Jwts; | ||
| import io.jsonwebtoken.security.Keys; | ||
| import org.springframework.beans.factory.annotation.Value; | ||
| import org.springframework.stereotype.Service; | ||
|
|
||
| import javax.crypto.SecretKey; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.util.Date; | ||
|
|
||
| @Service | ||
| public class JwtService { | ||
|
|
||
| @Value("${jwt.secret}") | ||
| private String secret; | ||
|
|
||
| private SecretKey getSigningKey() { | ||
| return Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8)); | ||
| } | ||
|
|
||
| public String generateToken(String username) { | ||
| return Jwts.builder() | ||
| .subject(username) | ||
| .issuedAt(new Date()) | ||
| .expiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60)) | ||
| .signWith(getSigningKey()) | ||
| .compact(); | ||
| } | ||
|
|
||
| public String extractUsername(String token) { | ||
| return Jwts.parser() | ||
| .verifyWith(getSigningKey()) | ||
| .build() | ||
| .parseSignedClaims(token) | ||
| .getPayload() | ||
| .getSubject(); | ||
| } | ||
|
|
||
| public boolean isTokenValid(String token) { | ||
| try { | ||
| extractUsername(token); | ||
| return true; | ||
| } catch (Exception e) { | ||
| return false; | ||
| } | ||
| } | ||
| } |
30 changes: 28 additions & 2 deletions
30
src/main/java/net/hackyourfuture/security/config/SecurityConfig.java
This file contains hidden or 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,18 +1,44 @@ | ||
| package net.hackyourfuture.security.config; | ||
|
|
||
| import lombok.AllArgsConstructor; | ||
| import net.hackyourfuture.security.authentication.JwtAuthenticationFilter; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.security.config.annotation.web.builders.HttpSecurity; | ||
| import org.springframework.security.config.http.SessionCreationPolicy; | ||
| 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; | ||
|
|
||
| @Configuration | ||
| @AllArgsConstructor | ||
| public class SecurityConfig { | ||
|
|
||
| private final JwtAuthenticationFilter jwtAuthenticationFilter; | ||
|
|
||
| @Bean | ||
| public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { | ||
| http | ||
| .csrf(csrf -> csrf.disable()) | ||
| .authorizeHttpRequests(auth -> auth.anyRequest().permitAll()); | ||
| .sessionManagement(session -> | ||
| session.sessionCreationPolicy(SessionCreationPolicy.STATELESS) | ||
| ) | ||
| .authorizeHttpRequests(auth -> auth | ||
| .requestMatchers("/users/register", "/auth/login").permitAll() | ||
| .requestMatchers("/users/profile", "/auth/logout").authenticated() | ||
| .anyRequest().authenticated() | ||
| ) | ||
| .addFilterBefore( | ||
| jwtAuthenticationFilter, | ||
| UsernamePasswordAuthenticationFilter.class | ||
| ); | ||
|
|
||
| return http.build(); | ||
| } | ||
| } | ||
|
|
||
| @Bean | ||
| public PasswordEncoder passwordEncoder() { | ||
| return new BCryptPasswordEncoder(12); | ||
| } | ||
| } |
This file contains hidden or 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 hidden or 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 |
|---|---|---|
|
|
@@ -4,24 +4,44 @@ | |
| import net.hackyourfuture.security.user.dto.UserRequest; | ||
| import net.hackyourfuture.security.user.dto.UserResponse; | ||
| import org.springframework.http.HttpStatus; | ||
| import org.springframework.security.crypto.password.PasswordEncoder; | ||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.web.server.ResponseStatusException; | ||
|
|
||
| import java.util.UUID; | ||
|
|
||
| @Service | ||
| @AllArgsConstructor | ||
| public class UserService { | ||
|
|
||
| private final UserRepository userRepository; | ||
| private final PasswordEncoder passwordEncoder; | ||
|
|
||
| public UserResponse register(UserRequest request) { | ||
| throw new UnsupportedOperationException("TODO: implement registration"); | ||
| User existingUser = userRepository.findByUsername(request.username()); | ||
|
|
||
| if (existingUser != null) { | ||
| throw new ResponseStatusException(HttpStatus.CONFLICT, "Username already exists"); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nice that you are giving informative messages! |
||
| } | ||
|
|
||
| User user = new User( | ||
| UUID.randomUUID().toString(), | ||
| request.username(), | ||
| passwordEncoder.encode(request.password()) | ||
| ); | ||
|
|
||
| userRepository.createUser(user); | ||
|
|
||
| return new UserResponse(user.getId(), user.getUsername()); | ||
| } | ||
|
|
||
| public UserResponse getProfile(String username) { | ||
| User user = userRepository.findByUsername(username); | ||
|
|
||
| if (user == null) { | ||
| throw new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found"); | ||
| } | ||
|
|
||
| return new UserResponse(user.getId(), user.getUsername()); | ||
| } | ||
| } | ||
This file contains hidden or 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
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.
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.
this is the same functionality, but maybe looks cleaner.