gpt4 book ai didi

java - Spring Security 3.2.7 HttpServletRequest.isUserInRole(String) 不会自动添加 "ROLE_"前缀

转载 作者:行者123 更新时间:2023-12-02 04:41:27 24 4
gpt4 key购买 nike

我正在学习 Spring Security,并且正在使用 Spring Security 3.2.7,并且对 servlet 集成功能有疑问

引用Spring文档

3.1.3. HttpServletRequest.isUserInRole(String)

The HttpServletRequest.isUserInRole(String) will determine if SecurityContextHolder.getContext().getAuthentication().getAuthorities() contains a GrantedAuthority with the role passed into isUserInRole(String).

Typically users should not pass in the "ROLE_" prefix into this method since it is added automatically. For example, if you want to determine if the current user has the authority "ROLE_ADMIN", you could use the the following:

boolean isAdmin = httpServletRequest.isUserInRole("ADMIN");

This might be useful to determine if certain UI components should be displayed. For example, you might display admin links only if the current user is an admin.

但是,当我尝试时,我发现 httpServletRequest.isUserInRole("ADMIN");返回 false,而 httpServletRequest.isUserInRole("ROLE_ADMIN");返回真。

是否有任何特殊配置需要在调用 isUserInRole 时自动添加“ROLE_”前缀?

下面是我的配置(来自示例应用程序)

<authentication-manager>
<authentication-provider>
<user-service>
<user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
<user name="bob" password="bobspassword" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>

最佳答案

我已经找到了解决这个问题的方法。通过比较 Spring Security 3.2.7 和 4.0.1 之间的类 org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper 的源代码,我发现在 4.0.1 中属性 rolePrefix 使用值“ROLE_”进行初始化,但在 3.2.7 中没有。

Spring Security 3.2.7

private final String rolePrefix;

Spring 安全 4.0.1

private String rolePrefix = "ROLE_";

看来 Spring Security 3.2.7 不会自动添加前缀“ROLE_”

Migrating from Spring Security 3.x to 4.x (XML Configuration) 中的示例为例,我创建了一个 BeanPostProcessor 将“ROLE_”设置为 SecurityContextHolderAwareRequestFilter 的 rolePrefix 属性。

public class DefaultRolesPrefixPostProcessor implements BeanPostProcessor, PriorityOrdered {

...

public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

if (bean instanceof SecurityContextHolderAwareRequestFilter) {
SecurityContextHolderAwareRequestFilter filter = (SecurityContextHolderAwareRequestFilter) bean;
filter.setRolePrefix("ROLE_");
}
return bean;
}
}

上述解决方案适用于我的情况,但我不确定这是否是正确的方法。

关于java - Spring Security 3.2.7 HttpServletRequest.isUserInRole(String) 不会自动添加 "ROLE_"前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30146500/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com