我已经在我的应用程序中实现了Spring Security。我使用了默认实现,也就是说,我已经用我自己的参数(数据源,安全区域等)配置了它,但我还没有编写任何自定义实现。
现在我想从用户中捕获更多数据,这些数据与用户名和密码位于同一表中,如公司名称、id等。但是,我不想使用这些信息来登录。
我不知道该怎么做。据我所知,它与UserDetailsService有关。然而,如果我想在登录期间使用这些信息,似乎编写自定义UserDetailsService是必要的,而这不是我想要的。我只是想在用户登录后在应用程序中使用这些信息。
它真的与UserDetailsServer有关吗?这是我唯一需要修改的文件吗?
所有的例子,我发现自定义UserDetailsService只是使用用户名和密码,所以我不明白新的数据会在哪里。
谢谢!
重写UserDetailsService就是我们所做的。你需要实现你自己的UserDetailsService和UserDetails对象:
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;}
}