역할 및 권한이있는 Spring Security
권한이있는 역할 기반 보안을 설정하려고합니다. 나는 이것을 Spring-Security와 함께하려고 노력하고 있습니다.
내 요구 사항에 과잉 인 것처럼 보이는 ACL을 설정하고 싶지 않습니다.
이 문서에 설명 된대로 간단한 권한과 역할 만 갖고 싶습니다 . 불행히도이 기사는 주어진 솔루션을 구현하는 방법을 설명하지 않습니다.
누군가 이미 이것을 시도했고 올바른 방향으로 나를 가리킬 수 있습니까? 구현을 설명하는 다른 블로그 항목이 있습니까?
대단히 감사합니다.
이를 구현하려면 다음을 수행해야합니다.
- 모델 (사용자, 역할, 권한)을 만들고 주어진 사용자의 권한을 검색하는 방법을 만듭니다.
- 자신을 정의
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
해당 매핑을 수행하는 방법을 알고 있는 사용자 지정이 포함 되며 데이터베이스에서 매핑을 소싱하기 만하면됩니다. (스키마에 대한 문서를 참조하십시오.)
그런 다음 역할 대신 권한 측면에서 권한 부여 규칙을 정의 할 수 있습니다.
도움이되기를 바랍니다.
기본 단계는 다음과 같습니다.
사용자 지정 인증 공급자 사용
<bean id="myAuthenticationProvider" class="myProviderImplementation" scope="singleton"> ... </bean>
사용자 지정 공급자가 사용자 지정
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
'programing tip' 카테고리의 다른 글
하위 도메인에서 localStorage 사용 (0) | 2020.10.17 |
---|---|
System V IPC 대 POSIX IPC (0) | 2020.10.17 |
활성 레코드-오늘 이전에 생성 된 레코드 찾기 (0) | 2020.10.17 |
모델 속성을 사용하는 ModelSerializer (0) | 2020.10.17 |
중첩 된 try / except 블록에서 예외를 다시 발생시키는 방법은 무엇입니까? (0) | 2020.10.17 |