Vagner Reis
Vagner Reis

Reputation: 125

CORS policy and Spring Security

I can register, update and delete everything. However, when I will request security, I'm blocked by CORS.

Access to XMLHttpRequest at 'http://localhost:8080/oauth/token' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

My cors config class:

@Configuration
public class WebConfig {

    @Bean
    public WebMvcConfigurer corsConfiguration(){
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        .allowedHeaders("*")
                        .allowedOrigins("http://localhost:4200");
            }
        };
    }

In SecurityConfig.class:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            //resguarda aplicações web dentro do projeto
            .csrf().disable()
            .cors()
        .and()
            .sessionManagement()
            //aplicação não guardará sessões (será pelo token)
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

authService.ts:

tentarLogar(username: string, password: string): Observable<any>{
    const params = new HttpParams()
                        .set('username', username)
                        .set('password', password)
                        .set('grant_type', 'password')
    
    const headers = {
      'Authorization': 'Basic ' + btoa(`${this.clientID}:${this.clientSecret}`),
      'Content-Type': 'application/x-www-form-urlencoded'
    }

    return this.http.post(this.tokenURL, params.toString, {headers})
  }

If needs more some code please tell me. But as I said, with this configuration I can access the API, the real problem is not being able to access localhost:8080/oauth/token to get the JWT token.

EDIT:

new CorsConfiguration.class:

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

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Authorization, Content-Type");

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            filterChain.doFilter(request, response);
        }
    }

}

Upvotes: 2

Views: 547

Answers (1)

jzheaux
jzheaux

Reputation: 7762

It looks like you are using Spring Security's Legacy OAuth 2.0 support (org.springframework.security.oauth:spring-security-oauth2). If that's the case, then you have two options:

Use the newer support

If your application is new enough, you may prefer to switch to Spring Security 5's built-in support. Spring Security has a sample for minting self-signed JWTs based on HTTP Basic authentication, that may be useful.

In that case, the /token endpoint is configured using the same HttpSecurity as the rest of your endpoints, meaning you only configure CORS in one place, as you have already done.

Configure in AuthorizationServerSecurityConfigurer

In the legacy support, the OAuth endpoints are added in a separate Spring Security filter chain. As such, you need to configure that filter chain for CORS as well.

If you need to stick with the legacy support, then to configure the authorization server endpoints, like /oauth/token, you need to use the AuthorizationServerSecurityConfigurer like so:

@EnableAuthorizationServer
@Configuration
public class MyAuthorizationServerConfiguration 
        extends AuthorizationServerConfigurerAdapter {
    // ...

    @Override
    public void configure(AuthorizationServerSecurityConfigurer server) {
       // other configs

       UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
       CorsConfiguration config = new CorsConfiguration();
       config.applyPermitDefaultValues();

       source.registerCorsConfiguration("/oauth/token", config);
       CorsFilter filter = new CorsFilter(source);
       security.addTokenEndpointAuthenticationFilter(filter);
   }
}

Upvotes: 5

Related Questions