0

我为 DefaultLdapAuthoritiesPopulator 创建了一个 AuthoritiesMapper。角色被正确映射并使用拦截 URL。

如果我尝试使用 getUserPrincipal() 访问控制器中的角色,我仍然会获得 LDAP 组。

查看了填充器中的代码,它应该可以工作。

知道有什么问题或如何解决吗?我需要根据角色显示/隐藏部分视图

/*************************************************************************************
 * Maps Spring Security GrantedAuthorities 
 * e.g. AD groups populated using LdapAuthoritiesPopulator mapped to fixed role names
 * as defined in a Map instance (e.g. populated from a property file)
 * 
 * Sample roleMap:
 * Key          Value
 * Group1       ROLE_USER
 * Group2       ROLE_ADMIN
 * Group3       ROLE_ADMIN,ROLE_USER
 *************************************************************************************/
public class MapBasedGrantedAuthorityMapper implements GrantedAuthoritiesMapper {
    private Map<String,String> roleMap;
    private String stringSeparator = ",";
    private SimpleGrantedAuthority unknownAuthorithy = new SimpleGrantedAuthority("ROLE_UNKNOWN");
    private boolean keepUnknownAuthorities = false;
    public MapBasedGrantedAuthorityMapper(Map<String,String> roleMap){
        this.roleMap = roleMap;
    }

    public Collection<? extends GrantedAuthority> mapAuthorities(Collection<? extends GrantedAuthority> authorities) {
        String[] mappedValues; 
        Set<GrantedAuthority> mapped = new HashSet<GrantedAuthority>(authorities.size());
        for (GrantedAuthority auth : authorities) {
            if (roleMap.containsKey(auth.getAuthority())) {
                mappedValues = StringUtils.split(roleMap.get(auth.getAuthority()),stringSeparator);
                for (String mappedValue: mappedValues) {                    
                    mapped.add(new SimpleGrantedAuthority(StringUtils.trimToEmpty(mappedValue)));
                }
            } else if (keepUnknownAuthorities){ 
                mapped.add(auth);
            } else if (unknownAuthorithy != null){
                mapped.add(unknownAuthorithy);
            }
        }       
        return mapped;
    }
             // getters and setters

}
4

1 回答 1

0

我找到了解决这个问题的方法..

在视图中我可以使用这个spring security taglibs

<sec:authorize access="hasRole('ROLE_ADMIN')"> 

在服务层我可以使用@Secured

于 2013-07-24T13:22:36.247 回答