Get the Logged In User

Discussion on JDAL Core Library

Moderator: Jose Luis Martin

Get the Logged In User

Postby okbonn » Wed Jul 15, 2015 8:15 am

I need to get the actual Logged In User.
okbonn
 
Posts: 3
Joined: Wed Jul 15, 2015 8:13 am

Re: Get the Logged In User

Postby Jose Luis Martin » Fri Jul 17, 2015 8:39 am

Hi,

Currently, getting the logged user depends on implementation as there is not a method method like getCurrentUser() in AuthService..

Are you using Swing or Vaadin with Spring Security?.

Cheers
Jose Luis Martin
 
Posts: 39
Joined: Thu Jun 09, 2011 10:53 am

Re: Get the Logged In User

Postby okbonn » Fri Jul 17, 2015 8:48 am

Vaadin with Spring Security

I tried:
@Autowired
private LoginView loginView;
to get the Credentials from the login screen, but it resulted in an instance of the screen containing only null credentials.
okbonn
 
Posts: 3
Joined: Wed Jul 15, 2015 8:13 am

Re: Get the Logged In User

Postby Jose Luis Martin » Fri Jul 17, 2015 9:09 am

Hi,

For Spring security I'm using this utility class to do it. It's still unpublished but should work.

Code: Select all

public abstract class Auth {

   private static final String prefix = "ROLE_";
   private static final AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
   private static final String ADMIN = "ADMIN";

   /**
    * Check if user has role.
    * @param role role to check
    * @return true if current user has assigned role, false otherwise.
    */
   public static boolean hasRole(String role) {
      Authentication auth = getAuthentication();
      
      if (auth == null)
         return false;
      
      if( prefix != null ) {
         role = prefix + role;
      }

      Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();

      if (authorities == null) {
         return false;
      }

      for (GrantedAuthority grantedAuthority : authorities) {
         if (role.equals(grantedAuthority.getAuthority())) {
            return true;
         }
      }

      return false;
   }

   /**
    * Gets current user Authentication
    * @return authentication of the current user.
    */
   public static Authentication getAuthentication() {
      Authentication auth = SecurityContextHolder.getContext().getAuthentication();

      if (!resolver.isAnonymous(auth)) {
         return auth;
      }

      return null;
   }
   
   /**
    * Gets current logged user
    * @return current user
    */
   public static User getCurrentUser() {
      Authentication auth = getAuthentication();
      
      return (User) (auth != null ? auth.getPrincipal() : null);
   }

   /**
    * Test for admin role.
    * @return true if current user is admin
    */
   public static boolean isAdmin() {
      return hasRole(ADMIN);
   }


}

Jose Luis Martin
 
Posts: 39
Joined: Thu Jun 09, 2011 10:53 am


Return to JDAL Core

Who is online

Users browsing this forum: No registered users and 1 guest

cron