我已在我的应用程序中实现了Spring Security。我使用了默认实现,即我使用自己的参数(DataSource,安全区域等)配置它,但我没有编写任何自定义实现。
现在我想从用户那里捕获更多数据,这些数据与用户名和密码在同一个表中,如公司名称,ID等。但是,我不想使用此信息才能登录。< / p>
我不知道该怎么做。从我读过的内容来看,它与UserDetailsService有关。但是,如果我想在登录期间使用此信息,那么编写自定义UserDetailsService似乎是必要的,这不是我想要的。我只想在用户登录后在应用程序中使用此信息。
它真的与UserDetailsServer有关吗?这是我唯一需要修改的文件吗?
我发现自定义UserDetailsService的所有示例都使用了用户名和密码,因此我无法理解新数据的来源。
谢谢!
答案 0 :(得分:14)
覆盖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;}
}