Programing

Spring Security에서 역할과 권한 부여 권한의 차이점

lottogame 2020. 5. 7. 07:56
반응형

Spring Security에서 역할과 권한 부여 권한의 차이점


Spring Security 에는 액세스 권한 을 부여 / 제어하는 권한GrantedAuthority얻는 인터페이스 와 같은 개념과 구현 이 있습니다.

나는 다음과 같은 허용 작업에 그런 것 createSubUsers , 또는 deleteAccounts 내가에 허용 것, 관리자 (역할을 ROLE_ADMIN).

온라인에서 볼 수있는 튜토리얼 / 데모로 혼동되고 있습니다. 나는 내가 읽은 것을 연결하려고 노력하지만, 우리는 두 가지를 상호 교환 적으로 취급한다고 생각합니다.

문자열을 hasRole소비하는 것을 보았 GrantedAuthority습니까? 나는 분명히 이해하는 데 잘못하고 있습니다. Spring Security에서 개념적으로 무엇입니까?

해당 역할의 권한과 별도로 사용자 역할을 어떻게 저장합니까?

또한 org.springframework.security.core.userdetails.UserDetails인증 공급자가 참조한 DAO에서 사용되는 인터페이스를 살펴보고 있습니다 User(마지막 GrantedAuthority 참고).

public User(String username, 
            String password, 
            boolean enabled, 
            boolean accountNonExpired,
            boolean credentialsNonExpired, 
            boolean accountNonLocked, 
            Collection<? extends GrantedAuthority> authorities)

아니면 다른 두 가지를 구별하는 다른 방법이 있습니까? 아니면 지원되지 않고 스스로 만들어야합니까?


GrantedAuthority를 ​​"권한"또는 "권리"라고 생각하십시오. 이러한 "권한"은 (일반적으로) 문자열 ( getAuthority()방법 과 함께)로 표현됩니다 . 이 문자열을 통해 권한을 식별하고 유권자가 무언가에 대한 액세스 권한을 부여할지 결정할 수 있습니다.

보안 컨텍스트에 배치하여 사용자에게 다른 GrantedAuthority (권한)를 부여 할 수 있습니다. 일반적으로 필요한 GrantedAuthorities를 리턴하는 UserDetails 구현을 리턴하는 고유 한 UserDetailsService를 구현하여이를 수행합니다.

역할 (많은 예제에서 사용됨)은 역할이 접두사로 시작하는 GrantedAuthority라는 이름 지정 규칙이있는 "권한"입니다 ROLE_. 더 이상 아무것도 없습니다. 역할은 단지 GrantedAuthority- "권한"- "권리"입니다. ROLE_접두사가 붙은 역할이 접두사가 ROLE_기본값으로 사용되는 RoleVoter와 같이 접두사가 있는 역할이 특별히 처리 되는 스프링 보안의 많은 부분이 있습니다 . 이를 통해 ROLE_접두사없이 역할 이름을 제공 할 수 있습니다 . Spring security 4 이전에는 이러한 "역할"의 특수한 처리가 일관되게 따르지 않았으며 권한과 역할이 종종 동일하게 취급되었습니다 (예 :hasAuthority()hasRole()). 봄 보안 4과 함께, 역할의 치료는 "역할"을 가진 거래 (같은 것을보다 일관되고 코드 RoleVoterhasRole표현 등이) 항상 추가 ROLE_당신을 위해 접두사. 그래서 hasAuthority('ROLE_ADMIN')와 같은 의미 hasRole('ADMIN')때문에 ROLE_접두사가 자동으로 추가됩니다. 추가 정보 는 스프링 보안 3-4 마이그레이션 안내서 를 참조하십시오.

그러나 여전히 : 역할은 특별한 ROLE_접두사가 있는 권한입니다 . 따라서 스프링 보안 3의 @PreAuthorize("hasRole('ROLE_XYZ')")경우와 동일하며 @PreAuthorize("hasAuthority('ROLE_XYZ')")스프링 보안 4의 @PreAuthorize("hasRole('XYZ')")경우와 동일합니다 @PreAuthorize("hasAuthority('ROLE_XYZ')").

사용 사례와 관련하여 :

사용자에게는 역할이 있으며 역할은 특정 작업을 수행 할 수 있습니다.

GrantedAuthorities사용자가 속한 역할과 역할이 수행 할 수있는 작업으로 끝날 수 있습니다. GrantedAuthorities역할에 대한 접두사를 가지고 ROLE_와 작업은 접두사가 OP_. 조작 권한에 대한 일례 일 수 OP_DELETE_ACCOUNT, OP_CREATE_USER, OP_RUN_BATCH_JOB역할 ROLE_ADMIN, ROLE_USER 등이 될 수 등에

GrantedAuthority이 (의사 코드) 예제와 같이 엔티티를 구현하게 할 수 있습니다 .

@Entity
class Role implements GrantedAuthority {
    @Id
    private String id;

    @OneToMany
    private final List<Operation> allowedOperations = new ArrayList<>();

    @Override
    public String getAuthority() {
        return id;
    }

    public Collection<GrantedAuthority> getAllowedOperations() {
        return allowedOperations;
    }
}

@Entity
class User {
    @Id
    private String id;

    @OneToMany
    private final List<Role> roles = new ArrayList<>();

    public Collection<Role> getRoles() {
        return roles;
    }
}

@Entity
class Operation implements GrantedAuthority {
    @Id
    private String id;

    @Override
    public String getAuthority() {
        return id;
    }
}

데이터베이스에서 생성 한 역할 및 작업의 ID는 "ROLE_ADMIN", "OP_DELETE_ACCOUNT"등과 같은 GrantedAuthority 표현이됩니다. 사용자가 인증되면 모든 역할 및 해당 작업의 모든 GrantedAuthorities가 리턴되는지 확인하십시오. UserDetails.getAuthorities () 메소드

Example: The admin role with id ROLE_ADMIN has the operations OP_DELETE_ACCOUNT, OP_READ_ACCOUNT, OP_RUN_BATCH_JOB assigned to it. The user role with id ROLE_USER has the operation OP_READ_ACCOUNT.

If an admin logs in the resulting security context will have the GrantedAuthorities: ROLE_ADMIN, OP_DELETE_ACCOUNT, OP_READ_ACCOUNT, OP_RUN_BATCH_JOB

If a user logs it, it will have: ROLE_USER, OP_READ_ACCOUNT

The UserDetailsService would take care to collect all roles and all operations of those roles and make them available by the method getAuthorities() in the returned UserDetails instance.


AFAIK GrantedAuthority and roles are same in spring security. GrantedAuthority's getAuthority() string is the role (as per default implementation SimpleGrantedAuthority).

For your case may be you can use Hierarchical Roles

<bean id="roleVoter" class="org.springframework.security.access.vote.RoleHierarchyVoter">
    <constructor-arg ref="roleHierarchy" />
</bean>
<bean id="roleHierarchy"
        class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
    <property name="hierarchy">
        <value>
            ROLE_ADMIN > ROLE_createSubUsers
            ROLE_ADMIN > ROLE_deleteAccounts 
            ROLE_USER > ROLE_viewAccounts
        </value>
    </property>
</bean>

Not the exact sol you looking for, but hope it helps

Edit: Reply to your comment

Role is like a permission in spring-security. using intercept-url with hasRole provides a very fine grained control of what operation is allowed for which role/permission.

The way we handle in our application is, we define permission (i.e. role) for each operation (or rest url) for e.g. view_account, delete_account, add_account etc. Then we create logical profiles for each user like admin, guest_user, normal_user. The profiles are just logical grouping of permissions, independent of spring-security. When a new user is added, a profile is assigned to it (having all permissible permissions). Now when ever user try to perform some action, permission/role for that action is checked against user grantedAuthorities.

Also the defaultn RoleVoter uses prefix ROLE_, so any authority starting with ROLE_ is considered as role, you can change this default behavior by using a custom RolePrefix in role voter and using it in spring security.


Another way to understand the relationship between these concepts is to interpret a ROLE as a container of Authorities.

Authorities are fine-grained permissions targeting a specific action coupled sometimes with specific data scope or context. For instance, Read, Write, Manage, can represent various levels of permissions to a given scope of information.

Also, authorities are enforced deep in the processing flow of a request while ROLE are filtered by request filter way before reaching the Controller. Best practices prescribe implementing the authorities enforcement past the Controller in the business layer.

On the other hand, ROLES are coarse grained representation of an set of permissions. A ROLE_READER would only have Read or View authority while a ROLE_EDITOR would have both Read and Write. Roles are mainly used for a first screening at the outskirt of the request processing such as http. ... .antMatcher(...).hasRole(ROLE_MANAGER)

The Authorities being enforced deep in the request's process flow allows a finer grained application of the permission. For instance, a user may have Read Write permission to first level a resource but only Read to a sub-resource. Having a ROLE_READER would restrain his right to edit the first level resource as he needs the Write permission to edit this resource but a @PreAuthorize interceptor could block his tentative to edit the sub-resource.

Jake

참고URL : https://stackoverflow.com/questions/19525380/difference-between-role-and-grantedauthority-in-spring-security

반응형