同学们,大家好。 尝试过使用不同的变体但没有任何反应。
我有一个代码,下一个方法是:
public List<String> getUserRoles() {
List<String> roles = new ArrayList<>();
for (GrantedAuthority authority : SecurityContextHolder.getContext().getAuthentication().getAuthorities()) {
roles.add(authority.getAuthority().toUpperCase());
}
return roles;
}
我想从 Active Directory 获取所有用户权限,但仅获取前缀“ROLE_”
我尝试过:
使用application.yaml +代码(yaml中的前缀==null):
方法(AbstractContextSource ldapContext, AuthenticationManagerBuilder 构建器)...
builder.ldapAuthentication() .ldapAuthoritiesPopulator(populator) .contextSource(ldapContext) .userSearchFilter(userSearchFilter) .userSearchBase(userSearchBase) .groupSearchBase(groupSearchBase) .groupSearchFilter(groupSearchFilter) .rolePrefix(rolePrefix);
这不起作用。
2.不同的自定义类也不起作用。
我的问题是如何获取没有前缀 ROLE_ 的所有角色。
最佳答案
如果使用hasRole
进行授权,有两种方法:
Java配置
@Bean
public DefaultWebSecurityExpressionHandler defaultWebSecurityExpressionHandler() {
DefaultWebSecurityExpressionHandler defaultWebSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();
defaultWebSecurityExpressionHandler.setDefaultRolePrefix("");
return defaultWebSecurityExpressionHandler;
}
XML 配置
<beans:bean id="expressionHandler" class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler">
<beans:property name="defaultRolePrefix" value="" />
</beans:bean>
或者您可以使用 hasAuthority()
代替 hasRole()
。上一个在进行访问检查时不会添加 PREFIX
。
关于java - Spring Security如何配置ROLE前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49819754/