Announcement Announcement Module
Collapse
No announcement yet.
How to tell if current user has a specific role? Page Title Module
Move Remove Collapse
This topic is closed
X
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to tell if current user has a specific role?

    What's the best way to tell if the current logged in user has a specific role? Can this code be relied on? Or is their a more appropriate way to do this?

    Code:
        public static boolean isRoleHeld(Role role) {
            GrantedAuthority[] authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
            for (GrantedAuthority authority : authorities)
                if (role.getName().equals(authority.getAuthority()))
                    return true;
            return false;
        }
    I would have expected to see a method like the above as part of the Spring Security API, but couldn't find one. Did I just miss it? The Javadoc comments for the getAuthority() method seem a bit unclear as to whether I'll always get the role string...

  • #2
    hi

    When you're in standard web application, you can use HttpServletRequest.isUserInRole()

    Or you can (in JSPs) use Spring Security custom tag "authorize".

    This works with standard Spring Security configuration (particularily SecurityContextHolderAwareFilter).

    regards
    Grzegorz Grzybek

    Comment


    • #3
      oh, I didn't realize there was a standard JEE method for checking if a user has a specific role! Nor did I know it would work with Spring Security... Thanks Grzegorz.

      Comment

      Working...
      X