在Spring服务器中使用OAuth身份验证的CORS失败

san*_*a4l 6 oauth cors angularjs spring-boot jhipster

当我尝试向我的spring服务器调用"oauth/token"端点进行身份验证时,我遇到了CORS问题.服务器以401响应回答

 XMLHttpRequest cannot load http://localhost:8080/oauth/token.
 Response to preflight request doesn't pass access control check: 
 No 'Access-Control-Allow-Origin' header is present on the requested resource. 
 Origin 'http://localhost:8000' is therefore not allowed access. 
 The response had HTTP status code 401.
Run Code Online (Sandbox Code Playgroud)

这就是我如何调用服务器:

 login: function(credentials) {
        var data = "username=" +  encodeURIComponent(credentials.username) + "&password="
            + encodeURIComponent(credentials.password) + "&grant_type=password&scope=read%20write&" +
            "client_secret=mySecretOAuthSecret&client_id=awhyapp";
        return $http.post('http://localhost:8080/oauth/token', data, {
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                "Accept": "application/json",
                "Access-Control-Allow-Origin": "*",
                "Authorization": "Basic " + Base64.encode("awhyapp" + ':' + "mySecretOAuthSecret")
            }
        }).success(function (response) {
            var expiredAt = new Date();
            expiredAt.setSeconds(expiredAt.getSeconds() + response.expires_in);
            response.expires_at = expiredAt.getTime();
            localStorageService.set('token', response);
            return response;
        });
Run Code Online (Sandbox Code Playgroud)

OauthConfigurations:

 @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/oauth/token").permitAll()
        .and()
            .exceptionHandling()
            .authenticationEntryPoint(authenticationEntryPoint)
        .and()
            .logout()
            .logoutUrl("/api/logout")
            .logoutSuccessHandler(ajaxLogoutSuccessHandler)
        .and()
            .csrf()
            .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
            .disable()
            .headers()
            .frameOptions().disable()
        .and()
            .authorizeRequests()
            .antMatchers("/api/authenticate").permitAll()
            .antMatchers("/api/register").permitAll()
            .antMatchers("...").permitAll()
    }
}
Run Code Online (Sandbox Code Playgroud)

我按照这个问题的答案(将标题添加到oauth/token响应(spring-security))但我的问题是,无论我如何配置我的Filter类,即使我使用@Order设置了最高优先级,也永远不会调用这些函数注解.

bek*_*kce 0

Access-Control-Allow-Origin对请求来说是多余的。那是一个响应头。

在链接的答案中,将部分更改为: response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Authorization, Accept, Content-Type"); 此更改列出了您将发送到服务器的请求中允许的标头值。

我不确定您的 Spring 安全配置,但您基本上应该允许OPTIONS该端点上的请求无需身份验证即可工作。

祝你好运。