gpt4 book ai didi

angular - SpringBoot2 + Spring security CORS OPTIONS方法返回401代码

转载 作者:行者123 更新时间:2023-12-04 17:42:03 34 4
gpt4 key购买 nike

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

@Component
@Profile("dev")
class DevWebMvcConfigurer implements WebMvcConfigurer {

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

并创建安全配置:

@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 发出请求时:

Request URL: http://localhost:8080/oauth/token
Request Method: OPTIONS
Status Code: 401

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

@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 请求的状态设置为一切正常。这是什么?

我的 DevWebMvcConfigurer 仅在配置文件为 dev 时创建。如何添加 OPTIONS 请求权限?

最佳答案

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

        http.cors().and().authorizeRequests()
// add the "/oauth/token" permitAll
.antMatchers("/login", "/security/**","/oauth/token").permitAll()
.anyRequest().authenticated()
.and().formLogin().permitAll()
.and().csrf().disable();

关于angular - SpringBoot2 + Spring security CORS OPTIONS方法返回401代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54063102/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com