Пропустить пользовательский фильтр JWT для /api/auth/signin при использовании разрешенияAll()JAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Пропустить пользовательский фильтр JWT для /api/auth/signin при использовании разрешенияAll()

Сообщение Anonymous »

Я использую Spring Security 6 со специальным JwtAuthenticationFilter для обработки аутентификации на основе JWT для моего API. Однако, несмотря на использование .permitAll() для конечной точки /api/auth/signin, пользовательский JwtAuthenticationFilter по-прежнему выполняется для этой конечной точки, что неверно, поскольку для процесса входа не требуется JWT.
Конфигурация безопасности:

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

@Configuration
public class SecurityConfig {

private final JwtAuthenticationFilter jwtAuthenticationFilter;

public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter) {
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
// Configure CORS support
http.cors().configurationSource(corsConfigurationSource())
.and()
.authorizeRequests()
.requestMatchers("/api/auth/signin").permitAll()  // Allow signin endpoint
.requestMatchers(HttpMethod.OPTIONS, "/api/auth/signin").permitAll()  // Allow OPTIONS for /api/auth/signin
.anyRequest().authenticated()  // Secure other requests
.and()
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); // Register the custom JWT filter

return http.build();
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
// CORS configuration
CorsConfiguration corsConfig = new CorsConfiguration();
corsConfig.setAllowedOrigins(Arrays.asList("http://localhost:3000"));  // Set your frontend domain here
corsConfig.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));  // Allow these methods
corsConfig.setAllowedHeaders(Arrays.asList("Content-Type", "Authorization"));  // Allow these headers
corsConfig.setAllowCredentials(true);  // Allow credentials like cookies, if needed

// Register the CORS configuration
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfig);
return source;
}
}
Пользовательская реализация JwtAuthenticationFilter:

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

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

private final JwtTokenProvider jwtTokenProvider;

public JwtAuthenticationFilter(JwtTokenProvider jwtTokenProvider) {
this.jwtTokenProvider = jwtTokenProvider;
}

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {

// Extract and validate JWT
String jwt = getJwtFromRequest(request);

if (StringUtils.hasText(jwt) && jwtTokenProvider.validateToken(jwt)) {
String username = jwtTokenProvider.getUsernameFromToken(jwt);

// Set authentication in security context
SecurityContextHolder.getContext().setAuthentication(jwtTokenProvider.getAuthentication(username));
}

// Continue with the filter chain
chain.doFilter(request, response);
}

private String getJwtFromRequest(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7);  // Extract the token without the "Bearer " prefix
}
return null;
}
}
Есть идеи?

Подробнее здесь: https://stackoverflow.com/questions/792 ... -permitall
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

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