弹簧安全性,启用Oauth2时出现cors错误

时间:2017-06-19 08:20:19

标签: spring spring-mvc cors preflight

我在查询我的oauth / token端点时遇到错误。

我为我的资源启用了配置的cors /还试图允许所有资源但没有任何效果。

  

XMLHttpRequest无法加载http://localhost:8080/oauth/token。响应   预检请求没有通过访问控制检查:否   '访问控制允许来源'标题出现在请求的上   资源。起源' http://localhost:1111'因此是不允许的   访问。响应的HTTP状态代码为401。

vendor.js:1837 ERROR SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at CatchSubscriber.selector (app.js:7000)
    at CatchSubscriber.error (vendor.js:36672)
    at MapSubscriber.Subscriber._error (vendor.js:282)
    at MapSubscriber.Subscriber.error (vendor.js:256)
    at XMLHttpRequest.onError (vendor.js:25571)
    at ZoneDelegate.invokeTask (polyfills.js:15307)
    at Object.onInvokeTask (vendor.js:4893)
    at ZoneDelegate.invokeTask (polyfills.js:15306)
    at Zone.runTask (polyfills.js:15074)
defaultErrorLogger @ vendor.js:1837
ErrorHandler.handleError @ vendor.js:1897
next @ vendor.js:5531
schedulerFn @ vendor.js:4604
SafeSubscriber.__tryOrUnsub @ vendor.js:392
SafeSubscriber.next @ vendor.js:339
Subscriber._next @ vendor.js:279
Subscriber.next @ vendor.js:243
Subject.next @ vendor.js:14989
EventEmitter.emit @ vendor.js:4590
NgZone.triggerError @ vendor.js:4962
onHandleError @ vendor.js:4923
ZoneDelegate.handleError @ polyfills.js:15278
Zone.runTask @ polyfills.js:15077
ZoneTask.invoke @ polyfills.js:15369

随着邮差,一切都很完美。

我的角色安全配置:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowCredentials(true);
    }
}

还尝试在允许的来源中添加http://localhost:1111

邮递员代码:

require 'uri'
require 'net/http'

url = URI("http://localhost:8080/oauth/token")

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Post.new(url)
request["content-type"] = 'application/x-www-form-urlencoded'
request["authorization"] = 'Basic Y2hhdHRpbzpzZWNyZXRzZWNyZXQ='
request["cache-control"] = 'no-cache'
request["postman-token"] = 'daf213da-e231-a074-02dc-795a149a3bb2'
request.body = "grant_type=password&username=yevhen%40gmail.com&password=qwerty"

response = http.request(request)
puts response.read_body

5 个答案:

答案 0 :(得分:7)

经过多次努力之后,我已经超越了 WebSecurityConfigurerAdapter 类的方法 configure(WebSecurity web),因为授权服务器自己配置了这个并且我还没有找到另一个解。你还需要permit所有“/ oauth / token”Http.Options方法。我的方法:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers(HttpMethod.OPTIONS, "/oauth/token");
}

在此之后,我们需要添加cors过滤器以将Http状态设置为OK。我们现在可以使用Http.Options方法。

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter("/*")
public class CorsFilter implements Filter {

    public CorsFilter() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization");
        response.setHeader("Access-Control-Max-Age", "3600");
        if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
    }
}

答案 1 :(得分:2)

我找到了一种在Spring Security 5和Spring Security OAuth 2.3.5上修复401错误的方法,而无需关闭令牌端点上所有OPTIONS请求的安全性。 我意识到您可以通过AuthorizationServerSecurityConfigurer向令牌端点添加安全过滤器。我尝试添加CorsFilter并成功。这种方法的唯一问题是我无法利用Spring MVC的CorsRegistry。如果有人可以弄清楚如何使用CorsRegistry,请告诉我。

我为下面的解决方案复制了一个示例配置:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
@EnableAuthorizationServer
public static class AuthServerConfiguration extends AuthorizationServerConfigurerAdapter {
    //... other config

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        //... other config

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.applyPermitDefaultValues();

        // Maybe there's a way to use config from AuthorizationServerEndpointsConfigurer endpoints?
        source.registerCorsConfiguration("/oauth/token", config);
        CorsFilter filter = new CorsFilter(source);
        security.addTokenEndpointAuthenticationFilter(filter);
    }
}

答案 2 :(得分:0)

您可以扩展AuthorizationServerSecurityConfiguration并重写void configure(HttpSecurity http)方法以实现自定义cors配置,而其余部分保持不变。

这是一个例子:

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerSecurityConfiguration;
import org.springframework.web.cors.CorsConfiguration;

public class MyAuthorizationServerSecurityConfiguration extends AuthorizationServerSecurityConfiguration {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);

        http.cors(httpSecurityCorsConfigurer -> httpSecurityCorsConfigurer.configurationSource(request -> {
            CorsConfiguration configuration = new CorsConfiguration();
            configuration.addAllowedMethod("POST");
            configuration.addAllowedHeader("Content-Type");

            return configuration;
        }));
    }
}

然后,您可以自己导入相关的类,而不用使用默认的注释@EnableAuthorizationServer来引入默认的配置类:

@Import({AuthorizationServerEndpointsConfiguration.class, MyAuthorizationServerSecurityConfiguration.class})

无需更改与OPTIONS方法和/或特定的oauth路径相关的任何安全配置。

答案 3 :(得分:0)

这对我有用

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception 
      {
        security.tokenKeyAccess("permitAll()")
        .checkTokenAccess("isAuthenticated()");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.applyPermitDefaultValues();

        // add allow-origin to the headers
        config.addAllowedHeader("access-control-allow-origin");

        source.registerCorsConfiguration("/oauth/token", config);
        CorsFilter filter = new CorsFilter(source);
        security.addTokenEndpointAuthenticationFilter(filter);

    }

}

答案 4 :(得分:0)

我使用 XMLHttpRequest 发送 POST /logout 请求(Keycloak 和 Spring Cloud OidcClientInitiatedServerLogoutSuccessHandler)时出现 CORS 错误,所以我改用 HTML 表单:

 <form action="/logout" method="post">
    <button>Logout</button>
 </form>

它可以正常工作,并且不需要 CORS 配置。