포스트

11.Role Hierarchy

Role Hierarchy

  • 계층 권한이라고 한다
  • 권한 A, B, C가 있고, A < B < C 순으로 권한이 높다고 가정한다.

  • 기존 방식
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{

    http
            .csrf((auth) -> auth.disable());

    http
            .authorizeHttpRequests((auth) -> auth
                    .requestMatchers("/login").permitAll()
                    .requestMatchers("/").hasAnyRole("A", "B", "C")
                    .requestMatchers("/manager").hasAnyRole("B", "C")
                    .requestMatchers("/admin").hasAnyRole("C")
                    .anyRequest().authenticated()
            );

    http
            .formLogin((auth) -> auth.loginPage("/login")
                    .loginProcessingUrl("/loginProc")
                    .permitAll()
            );

    return http.build();
}
  • 코드는 직관적으로 보기 좋다.
  • 하지만 권한의 개수가 많아지면 코드의 길이가 길어진다
  • 또는 권한의 설정이 바뀌게 되면 수정해야하는 양이 많다

  • 계층 권한 방식
1
2
3
4
5
6
7
8
9
10
@Bean
public RoleHierarchy roleHierarchy() {

  RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();

  hierarchy.setHierarchy("ROLE_C > ROLE_B\n" +
          "ROLE_B > ROLE_A");

  return hierarchy;
}
  • SecurityConfig에 권한 설정 메소드를 등록한다
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{

    http
            .csrf((auth) -> auth.disable());

    http
            .authorizeHttpRequests((auth) -> auth
                    .requestMatchers("/login").permitAll()
                    .requestMatchers("/").hasAnyRole("A")
                    .requestMatchers("/manager").hasAnyRole("B")
                    .requestMatchers("/admin").hasAnyRole("C")
                    .anyRequest().authenticated()
            );

    http
            .formLogin((auth) -> auth.loginPage("/login")
                    .loginProcessingUrl("/loginProc")
                    .permitAll()
            );

    return http.build();
}
  • requestMatchers(“/”).hasAnyRole(“A”) : A 이상 모두 접근 가능
  • requestMatchers(“/manager”).hasAnyRole(“B”) : B 이상 모두 접근 가능
참고 사이트

개발자 유미