Tuomas Toivonen
Tuomas Toivonen

Reputation: 23502

Spring boot, how to reconfigure http-security

In Spring Boot with spring-boot-starter-security the HTTP security is automatically configured. I would like to configure the HttpSecurity object after Spring Boot has auto-configured it, i.e making little tweaks to the default configuration without having to reconfigure the whole object. How to do this in Spring Boot?

Upvotes: 1

Views: 1007

Answers (1)

hovanessyan
hovanessyan

Reputation: 31463

One way to tweak the spring-boot security configuration is through properties, which by default are:

# ----------------------------------------
# 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.

If the properties does not offer enough flexibility you can extend WebSecurityConfigurerAdapter and override the configure method as shown here. Example from the 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");
    }
}

This will surpass the auto configured spring-boot security, effectively overriding it with whatever configuration is supplied.

Upvotes: 1

Related Questions