首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SpringBoot2 + Spring security CORS选项方法返回401代码

SpringBoot2 + Spring security CORS选项方法返回401代码
EN

Stack Overflow用户
提问于 2019-01-06 23:37:49
回答 1查看 1.6K关注 0票数 3

我使用Angular + Spring Boot2 + Spring Security。我为allow CORS创建了WebMvcConfigurer配置

代码语言:javascript
复制
@Component
@Profile("dev")
class DevWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**").allowedMethods(ALL);
        registry.addMapping("/oauth/token").allowedMethods(ALL);
    }
}

并创建安全配置:

代码语言:javascript
复制
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().authorizeRequests()
                .antMatchers("/login", "/security/**").permitAll()
                .anyRequest().authenticated()
                .and().formLogin().permitAll()
                .and().csrf().disable();
    }
}

但是,当我尝试从angular发出请求时:

代码语言:javascript
复制
Request URL: http://localhost:8080/oauth/token
Request Method: OPTIONS
Status Code: 401 

我得到401错误代码。我该如何解决这个问题呢?我发现的所有示例都可以归结为编写这样的过滤器:

代码语言:javascript
复制
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
        response.setHeader("Access-Control-Max-Age", "3600");
        if (HttpMethod.OPTIONS.name().equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
    }
}

但这是一堆狗屎。我们将所有OPTIONS请求的状态设置为一切正常。那是什么?

仅当配置文件为dev时,才会创建我的DevWebMvcConfigurer。如何向其添加OPTIONS requests权限?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-07 09:04:06

您应该将/oauth/token添加到配置中。

代码语言:javascript
复制
        http.cors().and().authorizeRequests()
                // add the "/oauth/token" permitAll
                .antMatchers("/login", "/security/**","/oauth/token").permitAll()
                .anyRequest().authenticated()
                .and().formLogin().permitAll()
                .and().csrf().disable();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54063102

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档