在SecurityConfig中加入:
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
完整的Spring Security配置類:
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final JwtAuthenticationFilter jwtAuthFilter;
private final AuthenticationProvider authenticationProvider;
@Bean
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers(
"/api/hello"
).permitAll()
.anyRequest()
.authenticated()
)
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}
使用 AuthenticationProvider 於登錄時的傳統身份驗證,一旦使用者登錄並獲得有效的 JWT,將該令牌包含在每個後續的 HTTP 請求中, JwtAuthenticationFilter 基於該令牌進行後續的請求認證,使應用程序可以實現無狀態和分散式的身份驗證,提供更高的效能與更靈活且安全的身份驗證機制。