响应对OAuth的无效HTTP状态码401 /令牌
问题描述:
我已经实现了筛选春季boot.The代码CORS是如下: -响应对OAuth的无效HTTP状态码401 /令牌
@SpringBootApplication
@Component
public class Application implements Filter {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
为了充分利用的oauth2我创建了下面的access_token从angularjs对象: -
{"url":"http://localhost:8080/oauth/token?grant_type=client_credentials&client_id=clientId&client_secret=clientSecret","headers":{"Authorization":"Basic token_value"},"withCredentials":true,"method":"POST"}
我收到以下错误,当我打的服务器: -
OPTIONS url... 401() Response for preflight has invalid HTTP status code 401
我已经寻找堆栈溢出中类似问题的解决方案,但他们都没有解决我的问题。有人请帮助吗?
答
请阅读更多关于Preflight requests。
他们只是建议浏览器,如果服务器支持一个跨源请求。对这样的OPTIONS
请求的回应应该是好的(即< 400)。
我认为声明filterChain.doFilter(servletRequest, servletResponse);
进一步传递请求,而不是返回响应。
你可以阅读更多有关启用使用Spring CORS在Java中这里Enable CORS for OPTIONS request using Spring Framework
答
下面这段代码解决我的问题
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
的代码示例是从https://github.com/spring-projects/spring-security-oauth/issues/938
采取我也曾尝试解决方案介绍在https://stackoverflow.com/questions/40370022/response-for-preflight-has-invalid-http-status-code-401-spring,但它并没有帮助 –