Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

java - 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);
        }
    }

}
question from:https://stackoverflow.com/questions/65932383/cors-policy-and-spring-security

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...