Spring-OAuth2上的CORS

时间:2015-12-18 10:46:56

标签: spring-rest spring-oauth2

我使用Spring-Boot和Spring-OAuth2来保护我的Rest API。我已经实现了OAuth2。它被正确执行。我开发了AngularJS并尝试访问它,但我收到了CORS错误。

错误 - > Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.2.45:8080/Jaihind/oauth/token. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

网址 - > curl -X POST -vu clientapp:123456 http://localhost:8080/Jaihind/oauth/token -H "Accept: application/json" -d "password=password&username=gaurav&grant_type=password&scope=read%20write&client_secret=123456&client_id=clientapp"

以下是代码。

OAuth2ServerConfiguration.java

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class OAuth2ServerConfiguration {

    private static final String RESOURCE_ID = "restservice";

    @Configuration
    @EnableResourceServer

    protected static class ResourceServerConfiguration extends
            ResourceServerConfigurerAdapter {

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            // @formatter:off
            resources.resourceId(RESOURCE_ID);
            // @formatter:on
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {

            // @formatter:off
            http.authorizeRequests().antMatchers("/api/greeting").authenticated();
            http.authorizeRequests().antMatchers("/oauth/token").permitAll();
            //http.antMatcher("/oauth/token").p

            // @formatter:on
        }

    }

    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        private TokenStore tokenStore = new InMemoryTokenStore();

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

        @Autowired
        private UserDetailServiceBean userDetailsService;

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            // @formatter:off

            endpoints.addInterceptor(new HandlerInterceptorAdapter() {
                @Override
                public boolean preHandle(HttpServletRequest hsr, HttpServletResponse rs, Object o) throws Exception {
                    rs.setHeader("Access-Control-Allow-Origin", "*");
                    rs.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
                    rs.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
                    return true;
                }
            });
            endpoints.tokenStore(this.tokenStore)
                    .authenticationManager(this.authenticationManager)
                    .userDetailsService(userDetailsService);
            // @formatter:on
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            // @formatter:off
            clients
                    .inMemory()
                    .withClient("clientapp")
                    .authorizedGrantTypes("password", "refresh_token")
                    .authorities("USER")
                    .scopes("read", "write")
                    .resourceIds(RESOURCE_ID)
                    .secret("123456");
            // @formatter:on
        }

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

    }
}

我甚至添加了Filter。

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

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        HttpServletResponse response = (HttpServletResponse) resp;
        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", "Content-Type,x-auth-token,x-requested-with,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
        if (request.getMethod() != "OPTIONS") {
            chain.doFilter(req, resp);
        } else {
        }

        chain.doFilter(req, resp);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {
    }

}

1 个答案:

答案 0 :(得分:0)

您的过滤器始终调用chain.doFilter(req, resp),因此如果下游应用程序未处理CORS请求,那么您将看到类似的错误。