我正在学习 Spring Boot 并尝试使用 JWT 配置安全过滤器链。
我面临一个问题,它总是返回 403 错误。例如,当我访问不存在的 URL 时,它会抛出 403 错误,而在请求正文无效的情况下,它会再次抛出 403 错误。还会出现其他错误。然而,在成功的情况下,它可以正常工作。
谁能告诉我我的错是什么?非常感谢。
我的安全过滤链:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
private final JwtRequestFilter jwtRequestFilter;
@Autowired
public SecurityConfig(JwtRequestFilter jwtRequestFilter) {
this.jwtRequestFilter = jwtRequestFilter;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) {
try {
httpSecurity
.csrf(csrf -> csrf.csrfTokenRepository(cookieCsrfTokenRepository()).disable())
.authorizeHttpRequests(authorize -> authorize.requestMatchers("/api/v1/*/public/**", "/api/v1/auth/login")
.permitAll().anyRequest().authenticated())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
return httpSecurity.build();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Bean
public CsrfTokenRepository cookieCsrfTokenRepository() {
return CookieCsrfTokenRepository.withHttpOnlyFalse();
}
}
JwtRequestFilter:
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
chain.doFilter(request, response);
}
我的依赖项:
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'io.jsonwebtoken:jjwt-api:0.11.2'
感谢 M.Deinum,我了解到:如果出现错误,它会重定向到 /error。我做了一些修改,它起作用了。