独立Spring OAuth2 JWT授权服务器+ CORS

Mic*_* K. 24 spring-security cors jwt spring-security-oauth2

所以我从Dave Syer的这个例子中得到了以下授权服务器

@SpringBootApplication
public class AuthserverApplication {

    public static void main(String[] args) {
            SpringApplication.run(AuthserverApplication.class, args);
    }

    /* added later
    @Configuration
    @Order(Ordered.HIGHEST_PRECEDENCE)
    protected static class MyWebSecurity extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http //.csrf().disable() 
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/oauth/token").permitAll();
       }
    }*/

    @Configuration
    @EnableAuthorizationServer
    protected static class OAuth2AuthorizationConfig extends
                    AuthorizationServerConfigurerAdapter {

            @Autowired
            private AuthenticationManager authenticationManager;

            @Bean
            public JwtAccessTokenConverter jwtAccessTokenConverter() {
                    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
                    KeyPair keyPair = new KeyStoreKeyFactory(
                                    new ClassPathResource("keystore.jks"), "foobar".toCharArray())
                                    .getKeyPair("test");
                    converter.setKeyPair(keyPair);
                    return converter;
            }

            @Override
            public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
                    clients.inMemory()
                                    .withClient("acme")
                                    //.secret("acmesecret")
                                    .authorizedGrantTypes(//"authorization_code", "refresh_token",
                                                    "password").scopes("openid");
            }

            @Override
            public void configure(AuthorizationServerEndpointsConfigurer endpoints)
                            throws Exception {
                    endpoints.authenticationManager(authenticationManager).accessTokenConverter(
                                    jwtAccessTokenConverter());
            }

            @Override
            public void configure(AuthorizationServerSecurityConfigurer oauthServer)
                            throws Exception {
                    oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess(
                                    "isAuthenticated()");
            }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行它并用卷曲测试它

curl acme@localhost:8110/oauth/token -d grant_type=password -d client_id=acme -d username=user -d password=password
Run Code Online (Sandbox Code Playgroud)

我得到了一个JWT作为响应,但是一旦我尝试从我的前端(Angular JS在不同的端口上)访问AuthServer,我就会收到CORS错误.不是因为缺少Headers,而是因为OPTION请求被拒绝并且缺少凭据.

Request URL:http://localhost:8110/oauth/token
Request Method:OPTIONS
Status Code:401 Unauthorized
WWW-Authenticate:Bearer realm="oauth", error="unauthorized", error_description="Full authentication is required to access this resource"
Run Code Online (Sandbox Code Playgroud)

我已经知道我必须添加一个CorsFilter并另外发现这篇帖子,我在第一个答案中使用了该片段,让OPTIONS请求访问/oauth/token而无需凭据:

@Order(-1)
public class MyWebSecurity extends WebSecurityConfigurerAdapter {
   @Override
   protected void configure(HttpSecurity http) throws Exception {
       http
          .authorizeRequests()
          .antMatchers(HttpMethod.OPTIONS, "/oauth/token").permitAll();
   }
}
Run Code Online (Sandbox Code Playgroud)

之后,我得到了卷曲以下错误:

{"timestamp":1433370068120,"status":403,"error":"Forbidden","message":"Expected CSRF token not found. Has your session expired?","path":"/oauth/token"}
Run Code Online (Sandbox Code Playgroud)

所以为了简化我只是添加http.csrf().disable()configureMyWebSecurity类的方法,它解决了OPTION请求的问题,但因此POST请求不再工作了,我得到了There is no client authentication. Try adding an appropriate authentication filter.(也是curl).

我试图找出是否必须以某种方式连接MyWebSecurity类和AuthServer,但没有任何运气.原始示例(开头的链接)也注入了authenticationManager,但这对我没有任何改变.

Mic*_* K. 90

找到我的问题的原因!

如果CorsFilter处理OPTIONS请求,我只需要结束过滤链并立即返回结果!

SimpleCorsFilter.java

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCorsFilter implements Filter {

    public SimpleCorsFilter() {
    }

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

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }
}
Run Code Online (Sandbox Code Playgroud)

之后我可以忽略我的AuthServer = D中的OPTIONS预检请求

因此,服务器的工作方式如上所述,您可以在开头忽略带有MyWebSecurity类的块注释.

  • 作为替代方案,您可以使用Spring Framework 4.2+和Spring Boot 1.3+提供的`CorsFilter`,有关详细信息,请参阅我的[这里的答案](http://stackoverflow.com/a/31748398/1092077). (2认同)
  • @SébastienDeleuzeSpring的CorsFilter似乎是出于某种原因在FilterChain之后执行的,仍然导致未经授权的:( (2认同)
  • 您是否尝试按照[此处](http://stackoverflow.com/a/26147788/1092077)所述更改过滤器的顺序? (2认同)
  • @SébastienDeleuze我真的很想使用@CrossOrigin批注,但是可以将Spring CorsFilter用作备份。`@ CrossOrigin`与我的`@ ResoruceService`完美配合,但两个选项均不适用于我的@EnableAuthorizationServer。我总是收到401对Chrome预检OPTIONS请求的响应。此答案中描述的自定义过滤器确实有效。我们如何获得`@ CrossOrigin`注释和/或Spring CorsFilter才能与`@ EnableAuthorizationServer`一起实际使用。我尝试了您在此处和其他地方的回复中的所有建议,但都无济于事。 (2认同)

小智 24

我找到了一个使用解决方案的解决方案.但我有另一种方式来描述解决方案:

@Configuration
public class WebSecurityGlobalConfig extends WebSecurityConfigurerAdapter {
      ....
      @Override
      public void configure(WebSecurity web) throws Exception {
        web.ignoring()
          .antMatchers(HttpMethod.OPTIONS);
      }
      ...
}
Run Code Online (Sandbox Code Playgroud)

  • 你是maaan,就像弹簧靴2的魅力 (6认同)

Raf*_*Raf 11

我使用以下内容遇到了类似的问题

  • 后端 Spring Boot 1.5.8.RELEASE
  • Spring OAuth2 Spring OAuth 2.2.0.RELEASEw
  • Vuejsapp使用axiosajax请求库

随着postman一切正常!当我开始从Vuejs应用程序发出请求时,我得到以下错误

选项http:// localhost:8080/springboot/oauth/token 401()

XMLHttpRequest无法加载http:// localhost:8080/springboot/oauth/token.预检的响应具有无效的HTTP状态代码401

读了一下后,我发现我可以通过覆盖我的实现类来指示我Spring OAuth忽略OPTIONS请求,如下所示configureWebSecurityConfigurerAdapter

@Override
public void configure(WebSecurity web) throws Exception {
   web.ignoring().antMatchers(HttpMethod.OPTIONS);
}
Run Code Online (Sandbox Code Playgroud)

添加上述内容有所帮助,但后来我遇到了CORS具体的错误

选项http:// localhost:8080/springboot/oauth/token 403()

XMLHttpRequest无法加载http:// localhost:8080/springboot/oauth/token.对预检请求的响应未通过访问控制检查:请求的资源上不存在"Access-Control-Allow-Origin"标头.因此不允许来源' http:// localhost:8000 '访问.响应具有HTTP状态代码403.

并在CorsConfig如下所示的帮助下解决了上述问题

@Configuration
public class CorsConfig {
    @Bean
    public FilterRegistrationBean corsFilterRegistrationBean() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.applyPermitDefaultValues();
        config.setAllowCredentials(true);
        config.setAllowedOrigins(Arrays.asList("*"));
        config.setAllowedHeaders(Arrays.asList("*"));
        config.setAllowedMethods(Arrays.asList("*"));
        config.setExposedHeaders(Arrays.asList("content-length"));
        config.setMaxAge(3600L);
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}
Run Code Online (Sandbox Code Playgroud)

添加上述类后,它按预期工作.在我走之前,我prod会研究consequences使用

web.ignoring().antMatchers(HttpMethod.OPTIONS);

以及best practices以上Cors配置.现在*做的工作,但绝对不能安全生产.

西里尔的回答帮助了我partially,然后我CorsConfig在这个Github问题中遇到了这个想法.