Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - Cors Error when using CorsFilter and spring security

I'm building an API Service using Spring Boot. It uses Basic Auth for the authentication. When clients try to connect to the API, they will get CORS error.

On the Spring Boot, it throws error

java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*"since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.

I have tried to find the example of allowedOriginPatterns usage but not found yet. Even for its document -https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/CorsRegistration.html#allowedOriginPatterns-java.lang.String... I still don't know what is the pattern I have to put inside config.allowedOriginPatterns();

Below is my CorsFilter code,

@Configuration
public class RequestCorsFilter {

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.setAllowedOrigins(Collections.singletonList("*"));
        config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "responseType", "Authorization"));
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }      

}

And here is my Authentication code,

@Configuration
@EnableWebSecurity
public class AuthenConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
        throws Exception {
    auth
    .inMemoryAuthentication()
    .withUser("thor").password("{noop}P@ssw00rd")
    .authorities("USER");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        String[] AUTH_WHITELIST = {
            // -- swagger ui
            "/v2/api-docs", 
            "/swagger-resources/**", 
            "/configuration/ui",
            "/configuration/security", 
            "/swagger-ui.html",
            "/webjars/**"
        };

        http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .antMatchers(AUTH_WHITELIST).permitAll() // whitelist URL permitted
            .antMatchers("/api").authenticated(); // others need auth
    }

}
question from:https://stackoverflow.com/questions/66060750/cors-error-when-using-corsfilter-and-spring-security

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

1 Answer

0 votes
by (71.8m points)
config.setAllowedOrigins(Collections.singletonList("*"));

This line has to be changed. You should list all servers, that should have access to your application.

E.g. you use angular, so the development server for the frontend is http://localhost:4200. Your server in production is https://you.server.domain.com

Then your config List should look like this

config.setAllowedOrigins(List.of("http://localhost:4200","https://you.server.domain.com"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...