7.1 Restricting access based on authorities and roles

7.1.1 Restricting access for all endpoints based on user authorities

  1. @Configuration
  2. public class ProjectConfig extends WebSecurityConfigurerAdapter {
  3. @Bean
  4. public UserDetailsService userDetailsService() {
  5. InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
  6. UserDetails user1 = User.withUsername("john")
  7. .password("12345")
  8. .authorities("READ")
  9. .build();
  10. UserDetails user2 = User.withUsername("jane")
  11. .password("12345")
  12. .authorities("WRITE")
  13. .build();
  14. manager.createUser(user1);
  15. manager.createUser(user2);
  16. return manager;
  17. }
  18. @Bean
  19. public PasswordEncoder passwordEncoder() {
  20. return NoOpPasswordEncoder.getInstance();
  21. }
  22. @Override
  23. protected void configure(HttpSecurity http) throws Exception {
  24. http.httpBasic();
  25. http.authorizeRequests()
  26. .anyRequest()
  27. .hasAnyAuthority("WRITE", "READ");
  28. }
  29. }
  1. @Override
  2. protected void configure(HttpSecurity http) throws Exception {
  3. http.httpBasic();
  4. http.authorizeRequests()
  5. .anyRequest()
  6. // .hasAnyAuthority("WRITE", "READ");
  7. .access("hasAuthority('WRITE')");
  8. }

7.1.2 Restricting access for all endpoints based on user roles

  1. @Bean
  2. public UserDetailsService userDetailsService() {
  3. InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
  4. UserDetails user1 = User.withUsername("john")
  5. .password("12345")
  6. .authorities("ROLE_ADMIN")
  7. .build();
  8. UserDetails user2 = User.withUsername("jane")
  9. .password("12345")
  10. .authorities("ROLE_MANAGER")
  11. .build();
  12. manager.createUser(user1);
  13. manager.createUser(user2);
  14. return manager;
  15. }
  16. @Override
  17. protected void configure(HttpSecurity http) throws Exception {
  18. http.httpBasic();
  19. http.authorizeRequests()
  20. .anyRequest()
  21. .hasRole("ADMIN");
  22. }
  1. @Bean
  2. public UserDetailsService userDetailsService() {
  3. InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
  4. UserDetails user1 = User.withUsername("john")
  5. .password("12345")
  6. // .authorities("ROLE_ADMIN")
  7. .roles("ADMIN")
  8. .build();
  9. UserDetails user2 = User.withUsername("jane")
  10. .password("12345")
  11. // .authorities("ROLE_MANAGER")
  12. .roles("MANAGER")
  13. .build();
  14. manager.createUser(user1);
  15. manager.createUser(user2);
  16. return manager;
  17. }