Spring Security - Authorization Configuration

Authorization Configuration

Sample Authorization Configuration

Here is a sample Authorization configuration:

SecurityConfiguration.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestMethod;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.mvcMatchers("/", "/static/**").permitAll()
.mvcMatchers("/signup", "/login", "/admin/login", "/about").permitAll()
.mvcMatchers("/admin/**").access("hasRole('ADMIN')")
.mvcMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.anyRequest().denyAll()
.and()
.formLogin();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password(passwordEncoder().encode("password"))
.roles("USER")
.and()
.withUser("admin")
.password(passwordEncoder().encode("password"))
.roles("ADMIN");
}
}
  • There are two users configured, ‘user’ with ‘USER’ Role and ‘admin’ with ‘ADMIN’ Role
  • URLs with pattern “/“, “/static/**”, “/signup”, “/login”, “/admin/login”, “/about” are all publicly accessible
  • You need to have role ‘ADMIN’ to access URLs with pattern “/admin/**”. Here access acceps Spel Expression as parameter
  • You need to have role ‘USER’ to access URLs with pattern “/user/**”

You can also use antMatchers method, however, mvcMatchers method is consider more secured because it is more relaxed when it comes to pattern match