7.1 Restricting access based on authorities and roles
7.1.1 Restricting access for all endpoints based on user authorities
@Configuration
public class ProjectConfig extends WebSecurityConfigurerAdapter {
@Bean
public UserDetailsService userDetailsService() {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
UserDetails user1 = User.withUsername("john")
.password("12345")
.authorities("READ")
.build();
UserDetails user2 = User.withUsername("jane")
.password("12345")
.authorities("WRITE")
.build();
manager.createUser(user1);
manager.createUser(user2);
return manager;
}
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic();
http.authorizeRequests()
.anyRequest()
.hasAnyAuthority("WRITE", "READ");
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic();
http.authorizeRequests()
.anyRequest()
// .hasAnyAuthority("WRITE", "READ");
.access("hasAuthority('WRITE')");
}
7.1.2 Restricting access for all endpoints based on user roles
@Bean
public UserDetailsService userDetailsService() {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
UserDetails user1 = User.withUsername("john")
.password("12345")
.authorities("ROLE_ADMIN")
.build();
UserDetails user2 = User.withUsername("jane")
.password("12345")
.authorities("ROLE_MANAGER")
.build();
manager.createUser(user1);
manager.createUser(user2);
return manager;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic();
http.authorizeRequests()
.anyRequest()
.hasRole("ADMIN");
}
@Bean
public UserDetailsService userDetailsService() {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
UserDetails user1 = User.withUsername("john")
.password("12345")
// .authorities("ROLE_ADMIN")
.roles("ADMIN")
.build();
UserDetails user2 = User.withUsername("jane")
.password("12345")
// .authorities("ROLE_MANAGER")
.roles("MANAGER")
.build();
manager.createUser(user1);
manager.createUser(user2);
return manager;
}