SpringSecurity : How to list the User Authorities in Controller,Filter and Services

How to get the User Authorities in Controller,Filter and Services

  1. You can get the user authorities from the SecurityContextHolder.
  2. getContext().getAuthenication().getAuthorities() will return the authorities for the currently logged in user.
  3. You cannot add the user Authority to this collection of user Authorities.
    public Object authorities(){
        Set<grantedauthority> authorities = (Set<grantedauthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        if(authorities.contains("ADMIN")){
            // do something
            return "";
        }else if(authorities.contains("USER")){
            // do something else
            return "";
        }else{
            // do something else
            return "";
        }
    }

As shown in the example above you can get the user authorities by the following method.

Collection authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();

Also Read

No comments:

Powered by Blogger.