user3127896
user3127896

Reputation: 6563

Spring security get User object

I have implemented user authentication through Spring Security Framework and everything works fine. I can log in and log out, I can get logged user name for example like this:

String userName = ((UserDetails) auth.getPrincipal()).getUsername();

Now i want to get user like an object from database(i need user id and other user properties).

This how i have tried so far:

User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

Thereafter i got following exception:

Request processing failed; nested exception is java.lang.ClassCastException: org.springframework.security.core.userdetails.User cannot be cast to net.viralpatel.contact.model.User

Here is a question - how can i get User as object, how should i modify my classes UserDetailsServiceImpl and UserAssembler, any ideas?

@Component
@Transactional
public class UserDetailsServiceImpl implements UserDetailsService{

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private UserAssembler userAssembler;

    private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        User user = userDAO.findByEmail(username);

        if(null == user) throw new UsernameNotFoundException("User not found");
        return userAssembler.buildUserFromUser(user);
    }
}

And another one:

@Service("assembler")
public class UserAssembler {

    @Autowired
    private UserDAO userDAO;

    @Transactional(readOnly = true)
    public User buildUserFromUser(net.viralpatel.contact.model.User user) {
        String role = "ROLE_USER";//userEntityDAO.getRoleFromUserEntity(userEntity);

        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new GrantedAuthorityImpl(role));

        return new User(user.getLogin(), user.getPassword(), true, true, true, true,  authorities);
    }
}

Upvotes: 14

Views: 24273

Answers (3)

Bipul Sinha
Bipul Sinha

Reputation: 266

It looks like your User class in not extending Spring's org.springframework.security.core.userdetails.User class.

Here is an example code for reference, I have termed class named as 'AuthenticUser':

 public class AuthenticUser extends User {

        public AuthenticUser(String username, String password, boolean enabled,
        boolean accountNonExpired, boolean credentialsNonExpired,
        boolean accountNonLocked,
        Collection<? extends GrantedAuthority> authorities) {

        super(username, password, enabled, accountNonExpired, credentialsNonExpired,
            accountNonLocked, authorities);
    }
   .....
   .....
 }

Now you can create an object of this class in your code and set it as part of Spring Authentication Context, e.g.

  AuthenticUser user  = new AuthenticUser(username, password, .... rest of the parameters);
  Authentication authentication =  new UsernamePasswordAuthenticationToken(user, null,
      user.getAuthorities());
  SecurityContextHolder.getContext().setAuthentication(authentication);

This will authenticate your user and set user in Security context.

Upvotes: 0

Mayur Gupta
Mayur Gupta

Reputation: 780

You need to implement your own UserDetailsService and your own UserDetails object(as per your wish):

public class CustomService implements UserDetailsService {
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String userId) {

    Account account = accountDAO.findAccountByName(userId);

    // validation of the account
    if (account == null) {
        throw new UsernameNotFoundException("not found");
    }
    return buildUserFromAccount(account);
}


@SuppressWarnings("unchecked")
@Transactional(readOnly = true)
private User buildUserFromAccount(Account account) {

    // take whatever info you need
    String username = account.getUsername();
    String password = account.getPassword();
    boolean enabled = account.getEnabled();
    boolean accountNonExpired = account.getAccountNonExpired();
    boolean credentialsNonExpired = account.getCredentialsNonExpired();
    boolean accountNonLocked = account.getAccountNonLocked();

    // additional information goes here
    String companyName = companyDAO.getCompanyName(account);


    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    for (Role role : account.getRoles()) {
        authorities.add(new SimpleGrantedAuthority(role.getName()));
    }

    CustomUserDetails user = new CustomUserDetails (username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked,
            authorities, company);

    return user;
}


public class CustomUserDetails extends User{

// ...
public CustomUserDetails(..., String company){
     super(...);
     this.company = company;
}

private String company;

public String getCompany() { return company;}

public void setCompany(String company) { this.company = company;}
}

Note:
This is default implementation of User class you you need have some custom information that you can make a custom class and extend the User class

Upvotes: 0

axtavt
axtavt

Reputation: 242686

Essentially, you need to return an implementation of UserDetails that provides access to your User.

You have two options:

  • Add your User as a field (you can do it be extending org.springframework.security.core.userdetails.User):

    public class UserPrincipal extends org.springframework.security.core.userdetails.User {
        private final User user;
       ...
    }  
    

    and obtain a User from that field:

    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    User user = ((UserPrincipal) principal).getUser();
    
  • Create a class that extends your User and implements UserDetails:

    public class UserPrincipal extends User implements UserDetails {
        ...
        public UserPrincipal(User user) {
            // copy fields from user
        }
    }
    

    This approach allows you to cast the principal to User directly:

    User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    

Upvotes: 13

Related Questions