我正在开发一个基于 spring java 的应用程序,我想使用 apache directory studio ldap 来管理用户,所以我想给每个用户一个角色并管理我使用 spring security 的角色。
这是我的安全上下文.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.2.xsd">
<security:authentication-manager>
<security:ldap-authentication-provider
user-search-filter="(uid={0})" user-search-base="ou=users"
group-search-filter="(uniqueMember={0})" group-search-base="ou=groups"
group-role-attribute="cn" role-prefix="ROLE_" />
</security:authentication-manager>
<security:ldap-server url="ldap://localhost:8389/o=mojo"
manager-dn="uid=admin,ou=system" manager-password="secret" />
<security:http use-expressions="true">
<security:intercept-url pattern="/" access="hasRole('ROLE_Admin')" />
<security:form-login />
</security:http>
这是我的 ldap 层次结构
这对我不起作用,即使我使用管理员凭据登录,也会出现访问被拒绝的 403 错误。
有什么帮助吗?
最佳答案
尝试在 <security:intercept-url pattern="/" access="hasRole('ROLE_ADMIN')" />
中设置您的角色以这种方式大写。
默认 <security:ldap-authentication-provider />
, 它会自动配置一个 org.springframework.security.ldap.authentication.LdapAuthenticationProvider创建 org.springframework.security.ldap.userdetails.LdapUserDetailsMapper 的实例默认情况下具有以下属性:
public class LdapUserDetailsMapper implements UserDetailsContextMapper {
// ~ Instance fields
// ================================================================================================
private final Log logger = LogFactory.getLog(LdapUserDetailsMapper.class);
private String passwordAttributeName = "userPassword";
private String rolePrefix = "ROLE_";
private String[] roleAttributes = null;
private boolean convertToUpperCase = true;
以此类推,当convertToUpperCase设置为true时,这个方法
/**
* Creates a GrantedAuthority from a role attribute. Override to customize authority
* object creation.
* <p>
* The default implementation converts string attributes to roles, making use of the
* <tt>rolePrefix</tt> and <tt>convertToUpperCase</tt> properties. Non-String
* attributes are ignored.
* </p>
*
* @param role the attribute returned from
* @return the authority to be added to the list of authorities for the user, or null
* if this attribute should be ignored.
*/
protected GrantedAuthority createAuthority(Object role) {
if (role instanceof String) {
if (this.convertToUpperCase) {
role = ((String) role).toUpperCase();
}
return new SimpleGrantedAuthority(this.rolePrefix + role);
}
return null;
}
最终转换您的 ou:groups
Admin
至 ROLE_ADMIN
, 这与 ROLE_Admin
不匹配
关于使用 Ldap 进行 spring 授权和角色管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43029887/