[英]Spring security role assignment
JEE容器通常提供一種機制,該機制使用專有的部署描述符將外部用戶角色映射到內部用戶角色。 也就是說,應用程序在web.xml中聲明並使用內部角色,並且有一個文件(例如,用於weblogic的weblogic.xml)將分配給用戶的實際角色映射到內部角色。
使用Spring Security時如何實現這種映射? 我正在使用Spring Security3.0.x。
Spring Security3.0.x。 不提供開箱即用的映射。
但是,您可以通過擴展用於身份驗證方法的身份驗證提供程序來自己實現它。
如果使用DaoAuthenticationProvider
(內部使用UserDetailsService
),則可以重寫addCustomAuthorities(String username, List<GrantedAuthority> authorities)
方法,以根據已經授予的角色添加新角色/映射角色。
例如Extended UserDetailsService
:
...
@Override
protected void addCustomAuthorities(String username, List<GrantedAuthority> authorities) {
super.addCustomAuthorities(username, authorities);
List<GrantedAuthority> additional = new ArrayList<GrantedAuthority>();
for (GrantedAuthority role : authorities) {
additional .addAll(vourMappingService.getAdditionalForRole(role));
}
authorities.addAll(additional );
}
使用YourMappingService
映射角色(通過將新角色添加到現有角色一次)
public class YourMappingService
/**
* Property bases mapping of roles to privileges.
* Every role is one line, the privileges are comma separated.
*/
private Properties roleToPrivileges;
public YourMappingService(Properties roleToPrivileges) {
if (roleToPrivileges == null) {
throw new IllegalArgumentException("roleToPrivileges must not be null");
}
this.roleToPrivileges = roleToPrivileges;
}
@Override
public Collection<? extends GrantedAuthority> getAdditionalForRole(GrantedAuthority role) {
String authority = role.getAuthority();
if(authority != null) {
String commaSeparatedPrivileges = roleToPrivileges.getProperty(role.getAuthority());
if (commaSeparatedPrivileges != null) {
List<GrantedAuthority> privileges = new ArrayList<GrantedAuthority>();
for(String privilegeName : StringUtils.commaDelimitedListToSet(commaSeparatedPrivileges)) {
privileges.add(new GrantedAuthorityImpl(privilegeName.trim()));
}
return privileges;
} else {
return Collections.emptyList();
}
} else {
return Collections.emptyList();
}
}
}
組態:
<bean id="myUserDetailsService" class="de.humanfork.springsecurityroles.impl.JdbcDaoPrivilegesImpl">
<constructor-arg ref="yourMappingService"/>
<property name="dataSource" ref="dataSource"/>
<property name="usersByUsernameQuery" value="SELECT login,encryptedPassword,loginEnabled FROM user WHERE login = ?"/>
<property name="enableAuthorities" value="true"/>
<property name="authoritiesByUsernameQuery" value="SELECT u.login, r.securityRoles FROM user u, user2security_roles r WHERE u.login= ? AND u.id = r. User_fk;"/>
</bean>
<bean id="yourMappingService" class="ZourMappingService">
<constructor-arg>
<props>
<prop key="ROLE_ADMIN">
ROLE_backend_access,
ROLE_user_mngt,
ROLE_passwordLostRequest_mngt,
ROLE_log_mngt
</prop>
<prop key="ROLE_USER">
</prop>
</props>
</constructor-arg>
</bean>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.