WebSecurityConfigurerAdapter
class allows customisation of an applications WebSecurity
.WebSecurityConfigurerAdapter
and is annotated with both @Configuration
and @EnableWebSecurity
.@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// Put most of your configuration here.
// This is a simple config to enable form login.
http.formLogin();
}
}
HttpSecurity
object inside your own class that is annotated with @EnabledWebSecurity
, that (and any other) default disappears.dashboard
using the standard spring security login page.@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests(authorizeRequests ->
authorizeRequests
.mvcMatchers("/dashboard").authenticated()
.anyRequest().denyAll()
)
.formLogin(formLogin ->
formLogin
.permitAll()
).logout(logout ->
logout
.permitAll());
}
Positive: You may notice the above syntax is the newer DSL style. Both that and the old style are valid, see https://spring.io/blog/2019/11/21/spring-security-lambda-dsl to understand the difference.
/users/
and /admin/
paths, but allow anybody to access the /signup
page.@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests(authorizeRequests ->
authorizeRequests
.mvcMatchers("/dashboard").authenticated()
.mvcMatchers("/users/**").authenticated()
.mvcMatchers("/admin/**").authenticated()
.mvcMatchers("/styles/**").permitAll()
.mvcMatchers("/signup").permitAll()
.anyRequest().denyAll()
)
.formLogin(formLogin ->
formLogin
.permitAll()
).logout(logout ->
logout
.permitAll());
}
/dashboard
and anything inside the paths /users/*
and /admin/*
requires authentication, but /signup
does not./styles/**
to the permitAll list. That is, anything inside your src/main/resources/static/styles
folder will be accessible e.g. your CSS files. You would need similar for your JavaScript files etc. signup
page and the login
page.