WEB/Security

Lesson 24,25 - Authorities, Roles and Matcher methods (mvc,ant)

Tony Lim 2022. 5. 14. 14:50
728x90

authorities and roles are logical terms.

authority = actions

role = badges

both of them are based on GrantedAuthority interface

 

var u1 = User.withUsername("john")
      .password("12345")
      .authorities("ROLE_ADMIN")  // -> a role ADMIN
      .build();

var u2 = User.withUsername("bill")
      .password("12345")
      .roles("MANAGER")   // -> authority ROLE_MANAGER
      .build();

if we use roles() method it automatically add ROLE_ prefix -> and create SimpleGrantedAuthority which implement GrantedAuthority

 

public static List<GrantedAuthority> createAuthorityList(String... authorities) {
    List<GrantedAuthority> grantedAuthorities = new ArrayList(authorities.length);
    String[] var2 = authorities;
    int var3 = authorities.length;

    for(int var4 = 0; var4 < var3; ++var4) {
        String authority = var2[var4];
        grantedAuthorities.add(new SimpleGrantedAuthority(authority));
    }

    return grantedAuthorities;
}
public User.UserBuilder roles(String... roles) {
    List<GrantedAuthority> authorities = new ArrayList(roles.length);
    String[] var3 = roles;
    int var4 = roles.length;

    for(int var5 = 0; var5 < var4; ++var5) {
        String role = var3[var5];
        Assert.isTrue(!role.startsWith("ROLE_"), () -> {
            return role + " cannot start with ROLE_ (it is automatically added)";
        });
        authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
    }

    return this.authorities((Collection)authorities);
}

both of them (authority , roles) are returning List of GrantedAuthority

 


http.authorizeRequests()
      .mvcMatchers("/hello").hasRole("ADMIN")
      .mvcMatchers("/ciao").hasRole("MANAGER")
      .mvcMatchers("/c/{name}").authenticated()
      .anyRequest().authenticated();

hasRole will find ROLE_ prefixed from User's GrantedAuthority

 

http.authorizeRequests()
      .antMatchers("/a").authenticated() // /a
      .anyRequest().permitAll(); // /a/

alway use mvcMatchers because spring will consider "/a" and "/a/" same but ant matchers is exact match

so if some one sends non authenticated request to "/a/" , it will go to permitAll()

 

 

 

 

728x90