springboot配置401未授权

Springboot configuration 401 Unauthorized

我有这个配置方法,我想让用户能够注册,但我得到 401 Unathorized。这是由 .apply(**) 引起的,我无法做到。

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .httpBasic().disable()
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/auth/register").permitAll()
                .antMatchers("/auth/signin").permitAll()
                .anyRequest().authenticated()
                .and()
                .apply(new JwtConfigurer(jwtTokenProvider, securityUtils));
    } 

JwtConfigurer.class

 public class JwtConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    private final JwtTokenProvider jwtTokenProvider;
    private final SecurityUtils securityUtils;

    public JwtConfigurer(JwtTokenProvider jwtTokenProvider, SecurityUtils securityUtils) {
        this.jwtTokenProvider = jwtTokenProvider;
        this.securityUtils = securityUtils;
    }

    @Override
    public void configure(HttpSecurity http) {
        JwtTokenFilter customFilter = new JwtTokenFilter(jwtTokenProvider, securityUtils);
        http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class);
    }
} 

所以当请求发送到 /auth/register 时,我不想添加 .apply(**)。请问您有什么建议吗?

在扩展 WebSecurityConfigurerAdapter 的 class 中,您的 http configure() 方法与 .apply() 被写入,您可以使用以下内容告诉 Spring Boot如果遇到用于用户注册的 uri,则绕过或忽略过滤器。

@Override
public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(
                "/auth/register");
}

编辑:由于您遇到异常:

Cross-origin Request Blocked (Reason: CORS header ‘Access-Control-Allow-Origin’ missing and Reason: CORS request did not succeed)

这意味着您的 OPTIONS 请求(预检请求)失败。您是否使用不同的项目作为应用程序的前端?如果是,您将需要在 spring 引导配置中指定允许来源并允许来自该特定来源的指定方法。

请参考此official documentation to learn how to do that. You can enable Cors at Controller level or at global level. This ,如果您无法继续执行,也应该有助于实施。