WEB/Security

Lesson 23 - Configuring endpoint authorization

Tony Lim 2022. 5. 13. 15:52
728x90
@Configuration
public class ProjectConfig extends WebSecurityConfigurerAdapter {

  @Bean
  public UserDetailsService userDetailsService() {
    var uds = new InMemoryUserDetailsManager();

    var u1 = User.withUsername("bill")
              .password("12345")
              .authorities("ROLE_manager") // GrantedAuthority
            .build();

    var u2 = User.withUsername("john")
            .password("12345")
            .authorities("ROLE_admin")
            .build();

    uds.createUser(u1);
    uds.createUser(u2);

    return uds;
  }

  @Bean
  public PasswordEncoder passwordEncoder() {
    return NoOpPasswordEncoder.getInstance();
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic();

    http.authorizeRequests()
//            .anyRequest().hasAuthority("manager");
//            .anyRequest().hasAnyAuthority("admin", "manager");
          .anyRequest().hasRole("manager");
  }
}

even if we authroizeRequests().permitAll() 

we can still access /hello if we don't give any authentication (like Basic Auth)

but we cannot access /hello if we give wrong authenication

reason is because AuthenticationFilter always comes before AuthorizationFilter

 

with allowing only user that has authority "admin"

not giving any credential will give me "unauthorized"

giving a valid credenital(user but doesn't have authority "admin") give me "Forbidden"

 

in spring security there are 2 method about authorization

hasAuthority() , hasRole()

 

728x90