Spring启动,如何重新配置​​http-security

时间:2018-04-02 07:40:42

标签: java spring security spring-boot spring-security

在使用spring-boot-starter-security的Spring Boot中,自动配置HTTP安全性。我希望在 Spring Boot自动配置它之后配置HttpSecurity对象,即对默认配置进行一些调整,而不必重新配置整个对象。如何在Spring Boot中执行此操作?

1 个答案:

答案 0 :(得分:0)

调整spring-boot安全配置的一种方法是properties,默认情况下是:

# ----------------------------------------
# SECURITY PROPERTIES
# ----------------------------------------
# SECURITY (SecurityProperties)
spring.security.filter.order=-100 # Security filter chain order.
spring.security.filter.dispatcher-types=async,error,request # Security filter chain dispatcher types.
spring.security.user.name=user # Default user name.
spring.security.user.password= # Password for the default user name.
spring.security.user.roles= # Granted roles for the default user name.

# SECURITY OAUTH2 CLIENT (OAuth2ClientProperties)
spring.security.oauth2.client.provider.*= # OAuth provider details.
spring.security.oauth2.client.registration.*= # OAuth client registrations.

如果属性没有提供足够的灵活性,您可以扩展WebSecurityConfigurerAdapter并覆盖如here所示的configure方法。 official doc的示例:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/css/**", "/index").permitAll()       
                .antMatchers("/user/**").hasRole("USER")            
                .and()
            .formLogin()
                .loginPage("/login").failureUrl("/login-error");    
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}

这将超越自动配置的spring-boot安全性,有效地使用提供的任何配置覆盖它。