我正在从 SpringBoot 2 迁移到 SpringBoot3。我将根据随机生成的令牌来实现身份验证。我已经完成了登录和注册的端点。
我有公共网址列表(如 /login、/register 等),并且有用于身份验证的过滤器。我的问题是,当我调用此公共 url 之一时,请求也会被过滤(但不应该被过滤),并且我会得到 401 状态。对于其余端点,它工作正常。
我的SecurityConfis.class:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
@Autowired
private CustomAuthenticationFilter customAuthenticationFilter;
/**
* No authentication endpoints
*/
public static final RequestMatcher PUBLIC_URLS = new OrRequestMatcher(
new AntPathRequestMatcher("/api/auth/login"),
new AntPathRequestMatcher("/api/auth/register")
);
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
var protectedUrls = new NegatedRequestMatcher(PUBLIC_URLS);
http
.securityMatcher(protectedUrls)
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.csrf(csrf -> csrf.disable())
.sessionManagement(sessionManagement ->
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling(exceptionHandling ->
exceptionHandling.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.FORBIDDEN)))
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/api/data-transfer/**").hasAnyAuthority("ADMIN")
.requestMatchers("/api/discount-code/**").hasAnyAuthority("USER")
.anyRequest().authenticated())
.addFilterAfter(customAuthenticationFilter, BasicAuthenticationFilter.class);
return http.build();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
[...]
}
}
自定义身份验证过滤器.class
@Component
public class CustomAuthenticationFilter extends OncePerRequestFilter {
private static final String BEARER_PREFIX = "Bearer ";
@Autowired
private UserCrudService userCrudService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
[...]
}
}
如何在访问 /api/auth/login 或 /api/auth/register 时不调用 CustomAuthenticationFilter??
我找到了解决方案。这个问题很愚蠢,因为在访问 /api/auth/login 时我添加了“Authentication”标头。 由于身份验证数据不正确,CustomAuthenticationFilter 引发异常,并且我未经授权。 发送没有“授权”标头的请求解决了问题。当然,对于安全端点,此标头是必需的。