programing tip

역할 및 권한이있는 Spring Security

itbloger 2020. 10. 17. 10:03
반응형

역할 및 권한이있는 Spring Security


권한이있는 역할 기반 보안을 설정하려고합니다. 나는 이것을 Spring-Security와 함께하려고 노력하고 있습니다.

내 요구 사항에 과잉 인 것처럼 보이는 ACL을 설정하고 싶지 않습니다.

문서에 설명 된대로 간단한 권한과 역할 만 갖고 싶습니다 . 불행히도이 기사는 주어진 솔루션을 구현하는 방법을 설명하지 않습니다.

누군가 이미 이것을 시도했고 올바른 방향으로 나를 가리킬 수 있습니까? 구현을 설명하는 다른 블로그 항목이 있습니까?

대단히 감사합니다.


이를 구현하려면 다음을 수행해야합니다.

  1. 모델 (사용자, 역할, 권한)을 만들고 주어진 사용자의 권한을 검색하는 방법을 만듭니다.
  2. 자신을 정의 org.springframework.security.authentication.ProviderManager하고 사용자 정의 org.springframework.security.authentication.AuthenticationProvider. 이 마지막 것은 인증 방법에서 인증을 반환해야합니다.이 인증 org.springframework.security.core.GrantedAuthority은 귀하의 경우 지정된 사용자에 대한 모든 권한으로 설정되어야합니다.

이 기사의 비결은 사용자에게 역할을 할당하지만 Authentication.authorities개체 에서 해당 역할에 대한 권한을 설정하는 것입니다.

이를 위해 API를 읽고 모든 것을 구현하는 대신 기본 ProviderManager 및 AuthenticationProvider를 확장 할 수 있는지 확인하는 것이 좋습니다. org.springframework.security.ldap.authentication.LdapAuthenticationProvider사용자에 대한 올바른 역할을 검색하는 사용자 지정 LdapAuthoritiesPopulator 설정하여이를 수행했습니다 .

이번에는 당신이 찾고있는 것을 얻었기를 바랍니다. 행운을 빕니다.


나는 문제의 기사의 저자입니다.

의심 할 여지없이 여러 가지 방법이 있지만 일반적으로 내가하는 방법 UserDetails은 역할과 권한에 대해 알고 있는 사용자 지정을 구현하는 것입니다 . Role그리고 Permission당신이 쓰는 것을 단지 사용자 정의 클래스이다. (멋진 것은 없습니다 Role. 이름과 Permission인스턴스 세트 Permission가 있고 이름이 있습니다.) 그러면 다음 과 같은 객체를 getAuthorities()반환 GrantedAuthority합니다.

PERM_CREATE_POST, PERM_UPDATE_POST,PERM_READ_POST

같은 것을 반환하는 대신

ROLE_USER, ROLE_MODERATOR

UserDetails구현에 getRoles()메소드 가있는 경우 역할을 계속 사용할 수 있습니다 . (나는 하나 갖는 것이 좋습니다.)

이상적으로는 사용자에게 역할을 할당하면 관련 권한이 자동으로 채워집니다. 여기에는 UserDetailsService해당 매핑을 수행하는 방법을 알고 있는 사용자 지정이 포함 되며 데이터베이스에서 매핑을 소싱하기 만하면됩니다. (스키마에 대한 문서를 참조하십시오.)

그런 다음 역할 대신 권한 측면에서 권한 부여 규칙을 정의 할 수 있습니다.

도움이되기를 바랍니다.


기본 단계는 다음과 같습니다.

  1. 사용자 지정 인증 공급자 사용

    <bean id="myAuthenticationProvider" class="myProviderImplementation" scope="singleton">
    ...
    </bean>
    

  2. 사용자 지정 공급자가 사용자 지정 UserDetails구현을 반환하도록 합니다. 이것은 UserDetailsImpl다음 getAuthorities()과 같습니다.

    public Collection<GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> permissions = new ArrayList<GrantedAuthority>();
        for (GrantedAuthority role: roles) {
            permissions.addAll(getPermissionsIncludedInRole(role));
        }
        return permissions;
    }
    

물론 여기에서 특정 요구 사항에 대한 많은 최적화 / 사용자 지정을 적용 할 수 있습니다.


이것이 가장 간단한 방법입니다. 그룹 권한과 사용자 권한을 허용합니다.

-- Postgres syntax

create table users (
  user_id serial primary key,
  enabled boolean not null default true,
  password text not null,
  username citext not null unique
);

create index on users (username);

create table groups (
  group_id serial primary key,
  name citext not null unique
);

create table authorities (
  authority_id serial primary key,
  authority citext not null unique
);

create table user_authorities (
  user_id int references users,
  authority_id int references authorities,
  primary key (user_id, authority_id)
);

create table group_users (
  group_id int references groups,
  user_id int referenecs users,
  primary key (group_id, user_id)
);

create table group_authorities (
  group_id int references groups,
  authority_id int references authorities,
  primary key (group_id, authority_id)
);

그런 다음 META-INF / applicationContext-security.xml에서

<beans:bean class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" id="passwordEncoder" />

<authentication-manager>
    <authentication-provider>

        <jdbc-user-service
                data-source-ref="dataSource"

                users-by-username-query="select username, password, enabled from users where username=?"

                authorities-by-username-query="select users.username, authorities.authority from users join user_authorities using(user_id) join authorities using(authority_id) where users.username=?"

                group-authorities-by-username-query="select groups.id, groups.name, authorities.authority from users join group_users using(user_id) join groups using(group_id) join group_authorities using(group_id) join authorities using(authority_id) where users.username=?"

                />

          <password-encoder ref="passwordEncoder" />

    </authentication-provider>
</authentication-manager>

Just for sake of completeness (maybe someone else won't have to implement it from scratch):

We've implemented our own small library, as everyone else. It's supposed to make things easier, so that our developers don't have to reimplement it each time. It would be great if spring security would provide support of rbac out of the box, as this approach is much better than the default permission based one.

Have a look at Github (OSS, MIT license) to see if it suits your needs. It's basically only addressing the role <-> privileges mapping. The missing piece, you'll have to provide on your own is basically the user <-> roles mapping, e.g. by mapping groups (racf/ad groups) to roles (1:1) or by implementing an additional mapping. That one's different in each project, so it doesn't make sense to provide some implementation.

We've basically used this internally, so that we can start with rbac from the beginning. We can still replace it with some other implementation later on, if the application is growing, but it's important for us to get the setup right at the beginning.

If you don't use rbac, there's a good chance, that the permissions are scattered throughout the codebase and you'll have a hard time to extract/group those (into roles) later on. The generated graphs do also help to reason about it/restructure it later on.

참고URL : https://stackoverflow.com/questions/6357579/spring-security-with-roles-and-permissions

반응형