Reputation: 8986
I have implemented Spring Security in my application. I have used default implementation, i.e., I have configured it with my own parameters (DataSource, Secured Areas, etc), but I haven't write any Custom implementation.
Now I want to capture more data from the user, that is on the same table as username and password, like company name, id, etc. However, I don't want do use this information in order to login.
I'm not sure how to do it. From what I've read, it's related to UserDetailsService. However, it seems that writing a Custom UserDetailsService would be necessary if I wanted to use this information during the login, and that's not what I want. I just want to use this information inside the application, after the user have logged in.
Is it really related to UserDetailsServer? Is this the only file I have to modificate?
All the examples I found of custom UserDetailsService just used username and password, so I can't understand where new data would come in.
Thanks!
Upvotes: 8
Views: 6028
Reputation: 10918
Overriding the UserDetailsService is what we did.. You'll need to implement your own UserDetailsService and your own UserDetails object:
public class CustomService implements UserDetailsService {
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) {
Account account = accountDAO.findAccountByName(username);
if (account == null) {
throw new UsernameNotFoundException("account name not found");
}
return buildUserFromAccount(account);
}
@SuppressWarnings("unchecked")
@Transactional(readOnly = true)
private User buildUserFromAccount(Account account) {
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;}
}
Upvotes: 14