Skip to content

Commit

Permalink
Merge pull request #20 from tofiksa/19-upgrade-jsonwebtokens
Browse files Browse the repository at this point in the history
19 upgrade jsonwebtokens
  • Loading branch information
tofiksa authored Jul 23, 2024
2 parents 89679d9 + 5ea0578 commit 9ede0ed
Show file tree
Hide file tree
Showing 21 changed files with 452 additions and 471 deletions.
14 changes: 12 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,18 @@
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
Expand Down
48 changes: 48 additions & 0 deletions src/main/java/no/josefushighscore/configure/AuthConfiguration.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package no.josefushighscore.configure;

import no.josefushighscore.register.UserRegister;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
public class AuthConfiguration {

private final UserRegister userRepository;

public AuthConfiguration(UserRegister userRepository) {
this.userRepository = userRepository;
}

@Bean
UserDetailsService userDetailsService() {
return username -> userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
}

@Bean
BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
return config.getAuthenticationManager();
}

@Bean
AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();

authProvider.setUserDetailsService(userDetailsService());
authProvider.setPasswordEncoder(passwordEncoder());

return authProvider;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package no.josefushighscore.configure;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import no.josefushighscore.service.JwtService;
import org.springframework.lang.NonNull;
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.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import java.io.IOException;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

private final HandlerExceptionResolver handlerExceptionResolver;

private final JwtService jwtService;
private final UserDetailsService userDetailsService;

public JwtAuthenticationFilter(
JwtService jwtService,
UserDetailsService userDetailsService,
HandlerExceptionResolver handlerExceptionResolver
) {
this.jwtService = jwtService;
this.userDetailsService = userDetailsService;
this.handlerExceptionResolver = handlerExceptionResolver;
}

@Override
protected void doFilterInternal(
@NonNull HttpServletRequest request,
@NonNull HttpServletResponse response,
@NonNull FilterChain filterChain
) throws ServletException, IOException {
final String authHeader = request.getHeader("Authorization");

if (authHeader == null || !authHeader.startsWith("Bearer ")) {
filterChain.doFilter(request, response);
return;
}

try {
final String jwt = authHeader.substring(7);
final String userName = jwtService.extractUsername(jwt);

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

if (userName != null && authentication == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(userName);

if (jwtService.isTokenValid(jwt, userDetails)) {
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
userDetails,
null,
userDetails.getAuthorities()
);

authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}

filterChain.doFilter(request, response);
} catch (Exception exception) {
handlerExceptionResolver.resolveException(request, response, null, exception);
}
}
}
45 changes: 0 additions & 45 deletions src/main/java/no/josefushighscore/configure/SecurityConfig.java

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package no.josefushighscore.configure;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.List;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {
private final AuthenticationProvider authenticationProvider;
private final JwtAuthenticationFilter jwtAuthenticationFilter;

public SecurityConfiguration(
JwtAuthenticationFilter jwtAuthenticationFilter,
AuthenticationProvider authenticationProvider
) {
this.authenticationProvider = authenticationProvider;
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeHttpRequests()
.requestMatchers("/auth/**")
.permitAll()
.requestMatchers("/swagger-ui.html", "/swagger-ui/**", "/swagger-resources/**", "/swagger-resources", "/v3/api-docs/*", "/v3/api-docs").hasRole("ANONYMOUS")
.requestMatchers("/register/**").hasRole("ANONYMOUS")
.anyRequest()
.authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

return http.build();
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();

configuration.setAllowedOrigins(List.of("http://localhost:8005"));
configuration.setAllowedMethods(List.of("GET","POST"));
configuration.setAllowedHeaders(List.of("Authorization","Content-Type"));

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

source.registerCorsConfiguration("/**",configuration);

return source;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
import no.josefushighscore.dto.LoginUserDto;
import no.josefushighscore.dto.UserDto;
import no.josefushighscore.exception.BadRequestException;
import no.josefushighscore.model.User;
import no.josefushighscore.service.APIResponse;
import no.josefushighscore.service.UserLoginService;
import no.josefushighscore.service.AuthenticationService;
import no.josefushighscore.service.JwtService;
import no.josefushighscore.util.LoginResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -22,18 +25,32 @@
public class AuthenticationController {

@Autowired
UserLoginService loginService;
JwtService jwtService;

@Autowired
AuthenticationService authenticationService;

Logger LOG = LoggerFactory.getLogger(AuthenticationController.class);

public AuthenticationController(JwtService jwtService, AuthenticationService authenticationService) {
this.jwtService = jwtService;
this.authenticationService = authenticationService;
}

@Secured("ROLE_ANONYMOUS")
@PostMapping("/signin")
public ResponseEntity<LoginUserDto> signin(@RequestBody LoginUserDto data) throws AuthenticationException {
public ResponseEntity<LoginResponse> signin(@RequestBody LoginUserDto data) throws AuthenticationException {

APIResponse apiResponse = new APIResponse();
apiResponse.setData(loginService.login(data));
User authenticatedUser = authenticationService.authenticate(data);

String jwtToken = jwtService.generateToken(authenticatedUser);

LoginResponse loginResponse = new LoginResponse();

loginResponse.setToken(jwtToken);
loginResponse.setExpiresIn(jwtService.getExpirationTime());

return new ResponseEntity<>(loginService.login(data), HttpStatus.OK);
return ResponseEntity.ok(loginResponse);
}

@Secured("ROLE_ANONYMOUS")
Expand All @@ -42,7 +59,7 @@ public ResponseEntity registerNewUserAccount(@RequestBody UserDto accountDto) th

APIResponse apiResponse = new APIResponse();
LOG.info(String.valueOf(accountDto));
loginService.registerNewUserAccount(accountDto);
authenticationService.signup(accountDto);
apiResponse.setStatus(HttpStatus.CREATED);
apiResponse.setMessage("User registered successfully");

Expand Down

This file was deleted.

This file was deleted.

Loading

0 comments on commit 9ede0ed

Please sign in to comment.