Get More Information From The User - Spring Security

I applied Spring Security in my application. I used the default implementation, i.e. Configured it with my own parameters (DataSource, Secured Areas, etc.), but I did not write any custom implementation.

Now I want to get more data from the user, that is, in the same table as the username and password, for example, company name, identifier, etc. However, I do not want to use this information for login.

I am not sure how to do this. From what I read, this is related to UserDetailsService. However, it seems that writing a custom UserDetailsService would be necessary if I wanted to use this information during login, and this is not what I want. I just want to use this information inside the application after user login.

Is it really related to UserDetailsServer? Is this the only file I need to modify?

All the examples that I found in the user-defined UserDetailsService just used a username and password, so I cannot figure out where the new data will go.

Thanks!

+8
java spring security login
source share
1 answer

Overriding UserDetailsService is what we did. You will 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;} } 
+14
source share

All Articles