Spring-OAuth2 上的 CORS

CORS on 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).

URL -> 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;
        }

    }
}

我什至添加了过滤器。

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

}

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