Springboot Security hasRole无法正常工作

arv*_*han 10 spring-security spring-boot

我无法hasRole@PreAuthorize注释中使用方法.也request.isUserInRole(“ADMIN”)给出了false.我错过了什么?虽然.hasAuthority(“ADMIN”)工作正常.

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

dur*_*dur 23

您必须ROLE_使用要使用的前缀命名您的权限isUserInRole,请参阅Spring Security Reference:

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

boolean isAdmin = httpServletRequest.isUserInRole("ADMIN");
Run Code Online (Sandbox Code Playgroud)

hasRole(也hasAnyRole)相同,请参阅Spring Security Reference:

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

  • 通过在安全配置中使用@EnableGlobalMethodSecurity(prePostEnabled = true),也可以解决此问题. (4认同)