对于oauth / token

时间:2017-06-20 10:07:26

标签: java angularjs spring spring-boot oauth-2.0

我在spring boot中为CORS实现了Filter。代码如下: -

@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

我已经找到了堆栈溢出中类似问题的解决方案,但没有一个解决了我的问题。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:3)

以下一段代码解决了我的问题

@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

答案 1 :(得分:0)

请详细了解Preflight requests

如果服务器支持跨源请求,他们只是建议浏览器。对此类OPTIONS请求的响应应该是好的(即<400)。

我认为语句filterChain.doFilter(servletRequest, servletResponse);正在进一步传递请求,而不是返回响应。

您可以在此处阅读有关使用Spring in Java启用CORS的更多信息Enable CORS for OPTIONS request using Spring Framework