Springboot Security hasRole not working

前端 未结 2 823
执笔经年
执笔经年 2020-11-22 08:53

I’m unable to use hasRole method in @PreAuthorize annotation. Also request.isUserInRole(“ADMIN”) gives false. What am I m

2条回答
  •  爱一瞬间的悲伤
    2020-11-22 09:30

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

    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");
    

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

    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.

提交回复
热议问题