Я использую Spring Security 6 со специальным JwtAuthenticationFilter для обработки аутентификации на основе JWT для моего API. Однако, несмотря на использование .permitAll() для конечной точки /api/auth/signin, пользовательский JwtAuthenticationFilter по-прежнему выполняется для этой конечной точки, что неверно, поскольку для процесса входа не требуется JWT. Конфигурация безопасности:
Я использую Spring Security 6 со специальным JwtAuthenticationFilter для обработки аутентификации на основе JWT для моего API. Однако, несмотря на использование .permitAll() для конечной точки /api/auth/signin, пользовательский JwtAuthenticationFilter по-прежнему выполняется для этой конечной точки, что неверно, поскольку для процесса входа не требуется JWT. [b] Конфигурация безопасности:[/b] [code]@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; } } [/code] [b]Пользовательская реализация JwtAuthenticationFilter:[/b] [code]@Component public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtTokenProvider jwtTokenProvider;
public JwtAuthenticationFilter(JwtTokenProvider jwtTokenProvider) { this.jwtTokenProvider = jwtTokenProvider; }