WebSecurityConfig的重要性

当你发布的应用不能直接请求时,多数原因是因为受到WebSecurityConfig.java的拦截。

可以通过修改此文件对某些请求进行放行。

例:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.StrictHttpFirewall;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final Logger log = LoggerFactory.getLogger(WebSecurityConfig.class);

    private final WebProperties webProperties;

    public WebSecurityConfig(WebProperties webProperties) {
    	this.webProperties = webProperties;
    }

	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/video/**").antMatchers("/resources/**").antMatchers("/publics/**")
				.antMatchers("/health-check").antMatchers("/**");
		web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN").antMatchers("/user/**").hasRole("USER")
				.anyRequest().authenticated();

		//http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
	}
	
	@Bean
	public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
	    StrictHttpFirewall firewall = new StrictHttpFirewall();
	    firewall.setAllowUrlEncodedSlash(true);    
	    return firewall;
	}

//
//    @Bean
//    public CorsFilter corsFilter() {
//
//        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        CorsConfiguration config = webProperties.getCors();
//
//        if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
//
//        	log.debug("Registering CORS filter");
//
//            source.registerCorsConfiguration("/api/**", config);
//            source.registerCorsConfiguration("/management/**", config);
//            source.registerCorsConfiguration("/v2/api-docs", config);
//        }
//
//        return new CorsFilter(source);
//    }

}

  

posted @ 2020-12-09 14:45  奥兰王子  阅读(2254)  评论(0编辑  收藏  举报