CORS在Spring 4.3上使用OAuth2

时间:2016-08-28 12:32:12

标签: spring spring-security oauth cors spring-security-oauth2

以下是我在使用Angular 1.5应用程序发出请求时在Chrome控制台中获得的内容:

  

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

当我删除OAuth2配置时,错误消失了。

这是我的CORS配置:

class AppWebSpringConfig extends WebMvcConfigurerAdapter implements ServletContextAware {

...

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("X-Requested-With", "X-Auth-Token", "Origin", "Content-Type", "Accept")
                .allowCredentials(false)
                .maxAge(3600);
    }

...
}

我的OAuth2配置类:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {

    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        return new OAuth2MethodSecurityExpressionHandler();
    }

}

@Configuration
class OAuth2ServerConfiguration {

    private static final int ONE_HOUR = 3600;
    private static final int THIRTY_DAYS = 2592000;

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Override
        public void configure(HttpSecurity http) throws Exception {
            // @formatter:off
            http
                    .authorizeRequests()
                    .anyRequest().authenticated();
            // @formatter:on
        }

    }

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;

        @Autowired
        private UserSecurityService userSecurityService;

        @Autowired
        private DataSource dataSource;

        @Autowired
        private Environment env;

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            // @formatter:off
            endpoints
                    .tokenStore(tokenStore())
                    .authenticationManager(authenticationManager)
                    .userDetailsService(userSecurityService);
            // @formatter:on
        }

        @Bean
        public TokenStore tokenStore() {
            return new JdbcTokenStore(dataSource);
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            // @formatter:off
            clients
                    .jdbc(dataSource)
                    .withClient(env.getProperty(CLIENT_ID_WEB))
                    .secret(env.getProperty(CLIENT_SECRET_WEB))
                    .authorizedGrantTypes("password", "refresh_token")
                    .scopes("read", "write")
                    .accessTokenValiditySeconds(ONE_HOUR)
                    .refreshTokenValiditySeconds(THIRTY_DAYS);
            // @formatter:on
        }

        @Bean
        @Primary
        public DefaultTokenServices tokenServices() {
            final DefaultTokenServices tokenServices = new DefaultTokenServices();
            tokenServices.setSupportRefreshToken(true);
            tokenServices.setTokenStore(tokenStore());
            return tokenServices;
        }

    }

}
编辑:我也尝试过以下过滤器实现,但它不起作用。我在doFilter()方法中放了一个断点,但是执行并没有停在那里,就像我的过滤器没有注册一样。但是,当我添加一个默认构造函数来过滤并在那里放置一个断点时 - 它停止了,这意味着已经注册了过滤器。

@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() {
    }
}

我也试过这种方法,但又没有运气:Allow OPTIONS HTTP Method for oauth/token request

我认为OAuth2配置不允许请求甚至通过配置的CORS过滤器。 有人知道这个问题的解决方案吗?

EDIT2: 所以,事实证明有一个类:

public class AppSecurityInitializer extends AbstractSecurityWebApplicationInitializer {

    // nothing here, using defaults

}

一旦我评论它,CORS配置开始工作(可能是由于过滤器通过)但是现在我的OAuth2配置根本不起作用!每个URL都是公开的,没有安全性。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

Hiii我在春季4.3遇到了同样的问题,但这里解决了答案: -

您需要在AuthorizationServerConfiguration类中覆盖AuthorizationServerConfigurerAdapter的以下方法,并使用AuthorizationServerSecurityConfigurer的addTokenEndpointAuthenticationFilter方法在其中添加CORS过滤器,如下所示: -

 @Override
 public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
       security.addTokenEndpointAuthenticationFilter(new CORSFilter());
 }

您的AuthorizationServerConfiguration类将是: -

 @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;

        @Autowired
        private UserSecurityService userSecurityService;

        @Autowired
        private DataSource dataSource;

        @Autowired
        private Environment env;

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            // @formatter:off
            endpoints
                    .tokenStore(tokenStore())
                    .authenticationManager(authenticationManager)
                    .userDetailsService(userSecurityService);
            // @formatter:on
        }

        @Bean
        public TokenStore tokenStore() {
            return new JdbcTokenStore(dataSource);
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            // @formatter:off
            clients
                    .jdbc(dataSource)
                    .withClient(env.getProperty(CLIENT_ID_WEB))
                    .secret(env.getProperty(CLIENT_SECRET_WEB))
                    .authorizedGrantTypes("password", "refresh_token")
                    .scopes("read", "write")
                    .accessTokenValiditySeconds(ONE_HOUR)
                    .refreshTokenValiditySeconds(THIRTY_DAYS);
            // @formatter:on
        }

        @Bean
        @Primary
        public DefaultTokenServices tokenServices() {
            final DefaultTokenServices tokenServices = new DefaultTokenServices();
            tokenServices.setSupportRefreshToken(true);
            tokenServices.setTokenStore(tokenStore());
            return tokenServices;
        }

        // ***** Here I added CORS filter *****
        @Override
        public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
              security.addTokenEndpointAuthenticationFilter(new CORSFilter());
        }  
}