AuthenticationEntryPoint не обрабатывает некоторые исключенияJAVA

Программисты JAVA общаются здесь
Anonymous
AuthenticationEntryPoint не обрабатывает некоторые исключения

Сообщение Anonymous »

Я создаю шлюз API с помощью Spring Boot, использую токен jwt для проверки сеанса пользователя, и у меня возникла эта проблема с SpringSecurity, поэтому вот мой SecurityFilterChain

Код: Выделить всё

@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Value("${cognito.issuer}")
private String jwkIssuerUri;

@Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.exceptionHandling( exceptions -> exceptions
.authenticationEntryPoint(jwtAuthenticationEntryPoint))
.authorizeRequests(authorizeRequests ->
authorizeRequests
.antMatchers("/auth/callback").permitAll()
.anyRequest().authenticated()
).oauth2ResourceServer(oauth2ResourceServer ->
oauth2ResourceServer.jwt(jwt ->
jwt.decoder(jwtDecoder())
)
);
return http.build();
}

@Bean
public JwtDecoder jwtDecoder() {
return JwtDecoders.fromOidcIssuerLocation(jwkIssuerUri);
}

}
Как видите, я пытаюсь обработать исключение проверки, реализовав AuthenticationEntryPoint, это мой класс:

Код: Выделить всё

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationEntryPoint.class);
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
throws IOException {
logger.debug("Commence method called.  Handling exception.");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
if("ExpiredJwtException".equals(authException.getClass().getSimpleName())) {
logger.debug("Authentication error:\n", authException);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write(String.format("{\"error\": \"%s\", \"message\": \"%s\"}",
HttpServletResponse.SC_UNAUTHORIZED, "Provided authorization token is expired"));
} else if("InsufficientAuthenticationException".equals(authException.getClass().getSimpleName())) {
logger.debug("Athentication error:\n", authException);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write(String.format("{\"error\": \"%s\", \"message\": \"%s\"}",
HttpServletResponse.SC_UNAUTHORIZED, "Authorization token must be provided to reach this endpoint"));
} else {
logger.debug("Authentication error:\n", authException);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write(String.format("{\"error\": \"%s\", \"message\": \"%s\"}",
HttpServletResponse.SC_UNAUTHORIZED, "Cannot validate the token"));
}
}
}
Теперь мне удалось обработать исключение InsufficientAuthenticationException, но другие исключения, такие как ExpiredJwtException, не обрабатываются этим классом, но они обрабатываются Spring Security, здесь логи этого дела:

Код: Выделить всё

2024-05-09 15:12 |DEBUG| org.springframework.security.web.context.HttpSessionSecurityContextRepository.saveContext()
Did not store empty SecurityContext
2024-05-09 15:12 |DEBUG| org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter()
Cleared SecurityContextHolder to complete request
2024-05-09 15:13 |DEBUG| org.springframework.security.web.FilterChainProxy.doFilterInternal()
Securing GET /test
2024-05-09 15:13 |DEBUG| org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter()
Set SecurityContextHolder to empty SecurityContext
2024-05-09 15:13 |DEBUG| org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider.getJwt()
Failed to authenticate since the JWT was invalid
2024-05-09 15:13 |DEBUG| org.springframework.security.web.context.HttpSessionSecurityContextRepository.saveContext()
Did not store empty SecurityContext
2024-05-09 15:13 |DEBUG| org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter()
Cleared SecurityContextHolder to complete request
Я пытался добавить AccessDeniedHandler и даже объединить его с AuthenticationEntryPoint, но это не сработало. Также я попытался настроить собственный фильтр, который выдает исключения при их возникновении, но это тоже не сработало. Я хочу иметь возможность индивидуально обрабатывать эти исключения аутентификации и не позволять весенней загрузке обрабатывать их. Он просто меняет заголовок аутентификации, но это не то, что мне нужно, я хочу получить четкий ответ от API.

Подробнее здесь: https://stackoverflow.com/questions/784 ... exceptions

Вернуться в «JAVA»