Springboot Security hasRole 不起作用 [英] Springboot Security hasRole not working

查看:79
本文介绍了Springboot Security hasRole 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在 @PreAuthorize 注释中使用 hasRole 方法.另外 request.isUserInRole(ADMIN") 给出 false.我错过了什么?尽管 .hasAuthority(ADMIN") 工作正常.

I’m unable to use hasRole method in @PreAuthorize annotation. Also request.isUserInRole("ADMIN") gives false. What am I missing? Although .hasAuthority("ADMIN") works fine.

我正在为数据库中的用户分配权限.

I am assigning authorities to the users from a database.

推荐答案

您必须使用前缀 ROLE_ 命名您的权限才能使用 isUserInRole,请参阅 Spring 安全参考:

You have to name your authority with prefix ROLE_ to use isUserInRole, see Spring Security Reference:

HttpServletRequest.isUserInRole(String) 将确定 SecurityContextHolder.getContext().getAuthentication().getAuthorities() 是否包含一个 GrantedAuthority 并将角色传递给 isUserInRole(String).通常用户不应将ROLE_"前缀传入此方法,因为它是自动添加的.例如,如果要确定当前用户是否具有ROLE_ADMIN"权限,则可以使用以下命令:

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 following:

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

hasRole 也一样(还有 hasAnyRole),见 Spring 安全参考:

Same for hasRole (also hasAnyRole), see Spring Security Reference:

如果当前主体具有指定的角色,则返回 true.默认情况下,如果提供的角色不以ROLE_"开头,则会添加它.这可以通过修改 DefaultWebSecurityExpressionHandler 上的 defaultRolePrefix 来自定义.

Returns true if the current principal has the specified role. By default if the supplied role does not start with 'ROLE_' it will be added. This can be customized by modifying the defaultRolePrefix on DefaultWebSecurityExpressionHandler.

这篇关于Springboot Security hasRole 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆