Change response status when token is expired

This commit is contained in:
Dmitrii Cravcenco
2023-10-12 13:26:01 +03:00
parent fe3ad761e7
commit 0b98fe3db4
4 changed files with 12 additions and 28 deletions

View File

@@ -1,19 +0,0 @@
package com.faf223.expensetrackerfaf.config;
import com.faf223.expensetrackerfaf.controller.auth.ErrorResponse;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@ControllerAdvice
public class ExceptionHandlers {
@ExceptionHandler(TokenExpiredException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ResponseBody
public ErrorResponse handleTokenExpiredException(TokenExpiredException ex) {
return new ErrorResponse("Unauthorized", ex.getMessage());
}
}

View File

@@ -1,5 +1,7 @@
package com.faf223.expensetrackerfaf.config;
import com.faf223.expensetrackerfaf.controller.auth.ErrorResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
@@ -55,7 +57,17 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
}
}
} catch (ExpiredJwtException e) {
// Token is expired; return a custom response
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json");
ErrorResponse errorResponse = new ErrorResponse("TokenExpired", "Your session has expired. Please log in again.");
ObjectMapper objectMapper = new ObjectMapper(); // You may need to import ObjectMapper
response.getWriter().write(objectMapper.writeValueAsString(errorResponse));
response.getWriter().flush();
return;
}
filterChain.doFilter(request, response);
}

View File

@@ -19,7 +19,6 @@ public class SecurityConfiguration {
private final JwtAuthenticationFilter jwtAuthFilter;
private final AuthenticationProvider authenticationProvider;
// private final Http401UnauthorizedEntryPoint entryPoint;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
@@ -30,7 +29,6 @@ public class SecurityConfiguration {
.anyRequest().authenticated()
)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// .exceptionHandling((e) -> e.authenticationEntryPoint(entryPoint))
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class); // will be executed before UsernamePasswordAuthenticationFilter

View File

@@ -1,7 +0,0 @@
package com.faf223.expensetrackerfaf.config;
public class TokenExpiredException extends RuntimeException {
public TokenExpiredException(String message) {
super(message);
}
}