Spring Security - GrantedAuthoritiesMapper更改不会持久化

时间:2014-08-15 01:27:57

标签: java spring spring-security

我正在使用Spring Security的Active Directory实现。我已经创建了一个自定义的GrantedAuthoritiesMapper来将AD角色映射到我的应用程序角色。但是,对当局的改变似乎没有。

我的配置:

<b:bean id="grantedAuthoritiesMappers"
    class="com.xxx.TestAuthoritiesMapper"/>

<b:bean id="adAuthenticationProvider"
    class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
    <b:constructor-arg value="MYDOMAIN" />
    <b:constructor-arg value="ldap://192.168.2.4/" />
    <b:property name="authoritiesMapper" ref="grantedAuthoritiesMappers"></b:property>
</b:bean>

<authentication-manager>
    <authentication-provider ref="adAuthenticationProvider" />
</authentication-manager>

映射器的代码:

public class TestAuthoritiesMapper implements GrantedAuthoritiesMapper {

    private static Logger logger = Logger
            .getLogger(GrantedAuthoritiesMapper.class.toString());

    @Override
    public Collection<? extends GrantedAuthority> mapAuthorities(
            Collection<? extends GrantedAuthority> authorities) {

        logger.info("Coming in :" + authorities);

        Set newAuths = new HashSet();
        newAuths.addAll(authorities);
        newAuths.add(new SimpleGrantedAuthority("Custom Role"));

        logger.info("Coming out :" + newAuths);

        return newAuths;

    }
}

在这里,我可以看到我增强的权限列表。后来,当我跑:

    Object principal = this.getSecurityContext().getAuthentication().getPrincipal();
    UserDetails ud = (UserDetails) principal;
    log.info("Final auths:" + ud.getAuthorities());

我只看到原始的auths而没有我添加的额外内容。

当我运行调试器时,我的修改后的auths一直存在,直到Spring发布成功的Authentication对象。在被触发事件和我的安全上下文之间的某处,更改将丢失。

2 个答案:

答案 0 :(得分:1)

我遇到了完全相同的问题。 我通过使用新的身份验证对象

解决了这个问题
SecurityContext context = SecurityContextHolder.getContext();
Authentication auth = context.getAuthentication();

// Updated authorities in the new Authentication object. 
// The existing authentication only provides whats available from LDAP when LDAP is used.
Authentication newAuth = new UsernamePasswordAuthenticationToken(
                                 auth.getPrincipal(),
                                 auth.getCredentials(),
                                 context.getAuthentication().getAuthorities());
SecurityContextHolder.getContext().setAuthentication(newAuth);
Object obj = newAuth.getPrincipal();

我有一个扩展LdapUserDetailsMapper的类,它覆盖了mapUserFromContext,其中我使用新的权限集更新了用户

答案 1 :(得分:0)

我通过创建自定义类

解决了这个问题

我能够通过覆盖方法mapUserFromContext来获取用户并更新其权限。 希望这会有所帮助。

public class CustomUserDetailsMapper extends LdapUserDetailsMapper 
                                         implements UserDetailsContextMapper {
    ...
    @Override
    public UserDetails mapUserFromContext(DirContextOperations ctx,
            String username, Collection<? extends GrantedAuthority> authorities) {

            UserDetails user = super.mapUserFromContext(ctx, username,
                updateAuthorities(username));
    ...
}