-
Notifications
You must be signed in to change notification settings - Fork 6
Monerh A #5
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
base: main
Are you sure you want to change the base?
Monerh A #5
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| package net.hackyourfuture.security; | ||
|
|
||
| import com.auth0.jwt.JWT; | ||
| import org.springframework.beans.factory.annotation.Value; | ||
| import com.auth0.jwt.algorithms.Algorithm; | ||
| import com.auth0.jwt.interfaces.DecodedJWT; | ||
| import org.springframework.security.core.userdetails.UserDetails; | ||
| import org.springframework.stereotype.Service; | ||
| import java.util.Date; | ||
|
|
||
| @Service | ||
| public class JwtService { | ||
|
|
||
| private final Algorithm algorithm; | ||
|
|
||
| public JwtService(@Value("${JWT_SECRET_KEY}") String secretKey) { | ||
| this.algorithm = Algorithm.HMAC256(secretKey); | ||
| } | ||
|
|
||
|
|
||
| // Generating a new JWT token valid for 24 hours. | ||
| public String generateToken(UserDetails userDetails) { | ||
| return JWT.create() | ||
| .withSubject(userDetails.getUsername()) | ||
| .withIssuedAt(new Date()) | ||
| .withExpiresAt(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000)) | ||
| .sign(algorithm); | ||
| } | ||
|
|
||
| // Extracting the usernme from the token. | ||
| public String extractUsername(String token) { | ||
| DecodedJWT decodedJWT = JWT.require(algorithm) | ||
| .build() | ||
| .verify(token); | ||
| return decodedJWT.getSubject(); | ||
| } | ||
|
|
||
|
|
||
| // Validating if the token belongs to the user and isnt expired. | ||
| public boolean isTokenValid(String token, UserDetails userDetails) { | ||
| String username = extractUsername(token); | ||
| return (username.equals(userDetails.getUsername()) && !isTokenExpired(token)); | ||
| } | ||
|
|
||
| private boolean isTokenExpired(String token) { | ||
| DecodedJWT decodedJWT = JWT.require(algorithm).build().verify(token); | ||
| return decodedJWT.getExpiresAt().before(new Date()); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| package net.hackyourfuture.security; | ||
|
|
||
| import org.springframework.security.core.userdetails.UserDetails; | ||
| import org.springframework.security.core.userdetails.UserDetailsService; | ||
| import org.springframework.security.core.userdetails.UsernameNotFoundException; | ||
| import org.springframework.stereotype.Service; | ||
| import net.hackyourfuture.security.user.User; | ||
| import net.hackyourfuture.security.user.UserRepository; | ||
|
|
||
| @Service | ||
| public class MyUserDetailsService implements UserDetailsService { | ||
|
|
||
| private final UserRepository userRepository; | ||
|
|
||
| public MyUserDetailsService(UserRepository userRepository) { | ||
| this.userRepository = userRepository; | ||
| } | ||
|
|
||
| @Override | ||
| public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { | ||
| User user = userRepository.findByUsername(username); | ||
| if (user == null) { | ||
| throw new UsernameNotFoundException("User not found: " + username); | ||
| } | ||
|
|
||
| // Converting the User into Spring Security's UserDetails | ||
| return org.springframework.security.core.userdetails.User.builder() | ||
| .username(user.getUsername()) | ||
| .password(user.getPassword()) | ||
| .roles("USER") | ||
| .build(); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| package net.hackyourfuture.security.config; | ||
|
|
||
| import jakarta.servlet.FilterChain; | ||
| import jakarta.servlet.ServletException; | ||
| import jakarta.servlet.ServletRequest; | ||
| import jakarta.servlet.ServletResponse; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import lombok.AllArgsConstructor; | ||
| import net.hackyourfuture.security.JwtService; | ||
| import net.hackyourfuture.security.MyUserDetailsService; | ||
| import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
| import org.springframework.security.core.context.SecurityContextHolder; | ||
| import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; | ||
| import java.io.IOException; | ||
|
|
||
| @AllArgsConstructor | ||
| public class MyUserAuthenticationFilter extends UsernamePasswordAuthenticationFilter { | ||
|
|
||
| private final JwtService jwtService; | ||
| private final MyUserDetailsService myUserDetailsService; | ||
|
|
||
| @Override | ||
| public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) | ||
| throws IOException, ServletException { | ||
|
|
||
| HttpServletRequest httpRequest = (HttpServletRequest) request; | ||
| String authHeader = httpRequest.getHeader("Authorization"); | ||
|
|
||
| // Looking for Bearer token in the headers | ||
| if (authHeader != null && authHeader.startsWith("Bearer ")) { | ||
| String token = authHeader.substring(7); | ||
| try { | ||
| // Extracting username | ||
| String username = jwtService.extractUsername(token); | ||
| var userDetails = myUserDetailsService.loadUserByUsername(username); | ||
|
|
||
| // Verifing token validty | ||
| if (jwtService.isTokenValid(token, userDetails)) { | ||
| UsernamePasswordAuthenticationToken authentication = | ||
| new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); | ||
|
|
||
| SecurityContextHolder.getContext().setAuthentication(authentication); | ||
| } | ||
| } catch (Exception e) { | ||
|
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. it would be nice throw exception and/or log it. Currently it is silently failing. |
||
| } | ||
| } | ||
|
|
||
| chain.doFilter(request, response); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,18 +1,56 @@ | ||
| package net.hackyourfuture.security.config; | ||
|
|
||
| import net.hackyourfuture.security.JwtService; | ||
| import net.hackyourfuture.security.MyUserDetailsService; | ||
| 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.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 | ||
| public class SecurityConfig { | ||
| private final JwtService jwtService; | ||
| private final MyUserDetailsService myUserDetailsService; | ||
|
|
||
| public SecurityConfig(JwtService jwtService, MyUserDetailsService myUserDetailsService) { | ||
| this.jwtService = jwtService; | ||
| this.myUserDetailsService = myUserDetailsService; | ||
| } | ||
|
|
||
| @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 | ||
| // public endpoints | ||
| .requestMatchers("/auth/login", "/users/register").permitAll() | ||
| // private endpoints | ||
| .anyRequest().authenticated() | ||
| ) | ||
| .addFilterBefore( | ||
| new MyUserAuthenticationFilter(jwtService, myUserDetailsService), | ||
| UsernamePasswordAuthenticationFilter.class | ||
| ); | ||
| return http.build(); | ||
| } | ||
| // BCrypt for hashing | ||
| @Bean | ||
| public PasswordEncoder passwordEncoder() { | ||
| return new BCryptPasswordEncoder(); | ||
| } | ||
|
|
||
| // to handl the login authentication checks | ||
| @Bean | ||
| public AuthenticationManager authenticationManager(AuthenticationConfiguration config) | ||
| throws Exception { | ||
| return config.getAuthenticationManager(); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,17 +4,28 @@ | |
| 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"); | ||
| String hashedPassword = passwordEncoder.encode(request.password()); | ||
|
|
||
| String userId = UUID.randomUUID().toString(); | ||
| User newUser = new User(userId, request.username(), hashedPassword); | ||
|
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. Right now if someone registers with an existing username, you'll likely get an unhandled database exception. Add a check: |
||
| userRepository.createUser(newUser); | ||
|
|
||
| return new UserResponse(newUser.getId(), newUser.getUsername()); | ||
|
|
||
| } | ||
|
|
||
| public UserResponse getProfile(String username) { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -8,3 +8,7 @@ spring: | |
| sql: | ||
| init: | ||
| mode: always | ||
|
|
||
| jwt: | ||
| secret: | ||
| key: '${JWT_SECRET_KEY}' | ||
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.
authenticationManager.authenticate() throws AuthenticationException if credentials are invalid. Make sure you're handling that somewhere (either here with a try-catch or globally with a @ControllerAdvice) so the user gets a clean 401 response instead of a 500.