我遇到了spring security oauth2的问题。在拥有HTTP基本授权时,除了CORS之外,我的所有工作都按预期工作。加载基本身份验证时,浏览器会向我的端点发送OPTIONS请求。但是,我收到一个错误:
对预检请求的响应未通过访问控制检查:请求的资源上没有“Access-Control-Allow-Origin”标头。
这是我的代码(我使用的是Annotations):
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfiguration.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/*" };
}
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
encodingFilter.setForceEncoding(true);
encodingFilter.setEncoding("UTF-8");
return new Filter[]{encodingFilter,
new DelegatingFilterProxy("springSecurityFilterChain"),
new CORSFilter() };
}
}
// CORS
public class CORSFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
System.out.println("Filtering on...........................................................");
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Authorization, Origin, Accept, Access-Control-Request-Method, Access-Control-Request-Headers");
chain.doFilter(req, res);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
OAuth2ServerConfiguration:
@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {
// other stuff...
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests().antMatchers("/oauth/**", "/kiosks").permitAll().and().httpBasic();
}
}
每个其他基本HTTP请求都有效(基本上我指的是那些不需要预检OPTIONS请求的请求)。任何其他CORS都是允许的。虽然基本的Auth不起作用。
我想提一下,我已经测试了各种类型的解决方案(来自谷歌和StackOverflow),以使这个工作正常,但我还没有接近解决问题。
我在这里缺少什么?