我有一个 Spring Boot 应用程序,在一个应用程序中还具有 Oauth 身份验证和资源服务器。我的前端位于单独的服务器上,位于单独的位置。我的前端应用程序似乎没有对后端进行预检操作,后端总是响应 401。我的配置如下所示:
// ... annotations
public class OAuthConfig extends WebSecurityConfigurerAdapter {
// ... authencication providers
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/*.html", "layout/**", "/js/**", "/css/**", "/images/**", "/font/**",
"/signup", "/register",
"/oauth/**")
.permitAll()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/oauth/**").permitAll()
;
// @formatter:on
}
// ... beans
}
请注意,我还必须为静态内容添加异常(exception),因为尽管有任何文档,它似乎也无法以其他方式工作。
// ... annotations
public class MvcConfig extends WebMvcConfigurerAdapter {
// ... resource resolver, view resolver
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
我尝试更明确地指定,但也没有成功:
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**").allowedMethods("GET","POST","OPTIONS","DELETE","UPDATE");
registry.addMapping("/register");
registry.addMapping("/signup");
registry.addMapping("/oauth/**").allowedMethods("GET","POST","OPTIONS");
}
//... annotations
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
// ... resource id config
@Override
public void configure(HttpSecurity http) throws Exception {
//@formatter:off
http
.anonymous().disable()
.requestMatchers()
.antMatchers("/api/**")
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated()
.and()
.exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
//@formatter:on
}
}
此时我无法弄清楚我是否错过了任何重要的配置,以通过身份验证端点(以及 API 端点的其他部分)实现 CORS
最佳答案
如果您收到 HTTP 401 错误,对我来说,这并不意味着 CORS 配置有问题。 401应该意味着未经授权,所以问题可能更多地出在你的安全配置上。如果是跨源问题,您将收到类似“请求的资源上不存在‘Access-Control-Allow-Origin’ header 。”的错误。
事实上,我的一个应用程序在由于跨源问题而失败的请求上获得了 HTTP 200(正常)。
如果您需要帮助,您应该提供有关收到 401 错误代码的请求/响应的详细信息。
<小时/>我知道这不是一个真正的答案,但我还没有评论的声誉,所以我希望这会有所帮助。
关于java - Spring 安全、OAUTH Cors、选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40430476/