Skip to content

선택 - RoleHierarchy 리뷰 부탁드립니다. #26

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: jukekxm
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/main/java/nextstep/app/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,16 @@ public Set<String> getAuthorities() {
public RequestAuthorizationManager requestAuthorizationManager() {
List<RequestMatcherEntry<AuthorizationManager>> mappings = new ArrayList<>();
mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/members/me"), new AuthenticatedAuthorizationManager()));
mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/members"), new HasAuthorityAuthorizationManager("ADMIN")));
mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/members"), new HasAuthorityAuthorizationManager("ADMIN", roleHierarchy())));
mappings.add(new RequestMatcherEntry<>(new MvcRequestMatcher(HttpMethod.GET, "/search"), new PermitAllAuthorizationManager()));
mappings.add(new RequestMatcherEntry<>(new AnyRequestMatcher(), new PermitAllAuthorizationManager()));
return new RequestAuthorizationManager(mappings);
}

@Bean
public RoleHierarchy roleHierarchy() {
return RoleHierarchyImpl.with()
.role("ADMIN").implies("USER")
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,28 @@

import nextstep.security.authentication.Authentication;

import java.util.Collection;

public class HasAuthorityAuthorizationManager implements AuthorizationManager {

private final String authority;
private final RoleHierarchy roleHierarchy;

public HasAuthorityAuthorizationManager(String authority) {
this.authority = authority;
this.roleHierarchy = new NullRoleHierarchy();
}

public HasAuthorityAuthorizationManager(String authority, RoleHierarchy roleHierarchy) {
this.authority = authority;
this.roleHierarchy = roleHierarchy;
}

@Override
public AuthorizationDecision check(Authentication authentication, Object object) {
return new AuthorizationDecision(authentication.getAuthorities().contains(authority));

Collection<String> reachableGrantedAuthorities = roleHierarchy.getReachableGrantedAuthorities(authentication.getAuthorities());

return new AuthorizationDecision(reachableGrantedAuthorities.contains(authority));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package nextstep.security.authorization;

import java.util.Collection;

public class NullRoleHierarchy implements RoleHierarchy {
@Override
public Collection<String> getReachableGrantedAuthorities(Collection<String> authorities) {
return authorities;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package nextstep.security.authorization;

import java.util.Collection;

public interface RoleHierarchy {

Collection<String> getReachableGrantedAuthorities(Collection<String> authorities);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package nextstep.security.authorization;

import org.springframework.util.CollectionUtils;

import java.util.*;

public class RoleHierarchyImpl implements RoleHierarchy {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

만약 다음과 같이 권한의 계층 구조를 설정할 경우에는 어떻게 처리되어야 할까요?

RoleHierarchyImpl.with()
  .role("ADMIN").implies("USER")
  .role("USER").implies("GUEST")
  .build();

현재 구조에서는 직접적인 하위 역할만 추가하고 있어서, ADMIN이 USER만 포함하고 GUEST까지 확장되지 않는 문제가 발생할 수 있습니다.

Spring Security의 RoleHierarchyImpl은 buildRolesReachableInOneOrMoreStepsMap()을 활용하여 모든 계층 관계를 반영하는데, 현재 코드에서는 해당 로직이 없어 다단계 계층 탐색이 누락될 가능성이 있습니다 😢

개선해보면 어떨까요? 😄


private final Map<String, Set<String>> rolesReachableInOneOrMoreStepsMap;

public RoleHierarchyImpl(Map<String, Set<String>> rolesReachableInOneOrMoreStepsMap) {
this.rolesReachableInOneOrMoreStepsMap = rolesReachableInOneOrMoreStepsMap;
}

public static Builder with() {
return new Builder();
}

@Override
public Collection<String> getReachableGrantedAuthorities(Collection<String> authorities) {

Set<String> reachableRoles = new HashSet<>();

if (CollectionUtils.isEmpty(authorities)) {
return Collections.emptyList();
}

for (String authority : authorities) {
addReachableRoles(authority, reachableRoles);
}

return reachableRoles;
}

private void addReachableRoles(String authority, Set<String> reachableRoles) {
reachableRoles.add(authority);
Set<String> lowerRoles = rolesReachableInOneOrMoreStepsMap.computeIfAbsent(authority, k -> new HashSet<>());
reachableRoles.addAll(lowerRoles);
}

public static class Builder {
private final Map<String, Set<String>> hierarchy;

private Builder() {
this.hierarchy = new HashMap<>();
}

public RoleHierarchyImpl build() {
return new RoleHierarchyImpl(hierarchy);
}

public ImpliedRoles role(String role) {
return new ImpliedRoles(role);
}

private Builder addHierarchy(String role, String... impliedRoles) {
Set<String> impliedRoleSet = hierarchy.computeIfAbsent(role, k -> new HashSet<>());
impliedRoleSet.addAll(Arrays.asList(impliedRoles));
return this;
}

public final class ImpliedRoles {
private final String role;

public ImpliedRoles(String role) {
this.role = role;
}

public Builder implies(String... impliedRoles) {
return Builder.this.addHierarchy(this.role, impliedRoles);
}
}
}
}

51 changes: 51 additions & 0 deletions src/test/java/nextstep/app/RoleHierachyTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package nextstep.app;

import nextstep.security.authorization.NullRoleHierarchy;
import nextstep.security.authorization.RoleHierarchyImpl;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

public class RoleHierachyTest {

@DisplayName("상위 권한의 reachable authorities는 사용자의 권한과 하위 권한을 같이 반환한다.")
@Test
public void roleHierarchyTest() {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

테스트 코드 👍

코드 개선해 보시면서 아래 케이스에 대한 테스트 코드도 작성해 보면 좋을 것 같네요 😄

RoleHierarchyImpl.with()
  .role("ADMIN").implies("USER")
  .role("USER").implies("GUEST")
  .build();


// given
RoleHierarchyImpl roleHierarchy = RoleHierarchyImpl.with()
.role("ADMIN").implies("USER")
.build();

Set<String> authorites = new HashSet<>();
authorites.add("ADMIN");

// when
Collection<String> reachableGrantedAuthorities = roleHierarchy.getReachableGrantedAuthorities(authorites);

// then
Assertions.assertThat(reachableGrantedAuthorities).containsOnly("ADMIN", "USER");
}

@DisplayName("NullRoleHierarchy의 reachable authorities는 사용자의 권한 리스트를 그대로 반환한다.")
@Test
public void nullRoleHierarchyTest() {

// given
NullRoleHierarchy nullRoleHierarchy = new NullRoleHierarchy();

Set<String> authorites = new HashSet<>();
authorites.add("ADMIN");
authorites.add("USER");

// when
Collection<String> result = nullRoleHierarchy.getReachableGrantedAuthorities(authorites);

// then
Assertions.assertThat(result).isSameAs(authorites);
}
}