1

REST API を保護するために Spring-Boot と Spring-OAuth2 を使用しています。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() {
    }

}
4

1 に答える 1