Allow OPTIONS HTTP Method for oauth/token request

前端 未结 5 1376
不思量自难忘°
不思量自难忘° 2020-12-04 19:17

I\'m trying to enable oauth2 token fetching for my angular application. My configuration is working fine (authentication is working correctly for all requests, token fetchin

5条回答
  •  遥遥无期
    2020-12-04 20:10

    The following works for Spring Boot 2. It does not pick up other CORS configurations otherwise.

    @Configuration
    @EnableAuthorizationServer
    public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    
        // this is a Spring ConfigurationProperty use any way to get the CORS values
        @Autowired
        private CorsProperties corsProperties;
    
        // other things
        //...
    
        @Override
        public void configure(
                AuthorizationServerEndpointsConfigurer endpoints) {
            endpoints
                    .tokenStore(tokenStore())
                    .authenticationManager(authenticationManager);
            if (corsProperties.getAllowedOrigins() != null) {
                Map corsConfigMap = new HashMap<>();
                Arrays.asList(corsProperties.getAllowedOrigins().split(",")).stream()
                        .filter(StringUtils::isNotBlank).forEach(s -> {
                    CorsConfiguration config = new CorsConfiguration();
                    config.setAllowCredentials(true);
                    config.addAllowedOrigin(s.trim());
                    if (corsProperties.getAllowedMethods() != null) {
                        config.setAllowedMethods(Arrays.asList(corsProperties.getAllowedMethods().split(",")));
                    }
                    if (corsProperties.getAllowedHeaders() != null) {
                        config.setAllowedHeaders(Arrays.asList(corsProperties.getAllowedHeaders().split(",")));
                    }
                    // here the /oauth/token is used
                    corsConfigMap.put("/oauth/token", config);
                });
                endpoints.getFrameworkEndpointHandlerMapping()
                        .setCorsConfigurations(corsConfigMap);
            }
        }
    
    
    }
    

    And in addition the already mentioned allowance of the OPTIONS request:

    @Order(-1)
    @Configuration
    public class MyWebSecurity extends WebSecurityConfigurerAdapter {
       @Override
       protected void configure(HttpSecurity http) throws Exception {
           http
              authorizeRequests()
                .antMatchers("/**/oauth/token").permitAll()
                .and().httpBasic().realmName(securityRealm)
                // would throw a 403 otherwise
                .and().csrf().disable()
                // optional, but with a token a sesion is not needed anymore
    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
       }
    }
    

提交回复
热议问题