[英]Accessing Spring Security Threadlocal user information from outside of spring security
[英]Get more information from User - Spring Security
我在我的應用程序中實現了Spring Security。 我使用了默認實現,即我使用自己的參數(DataSource,Secured Areas等)配置它,但我沒有編寫任何Custom實現。
現在我想從用戶那里捕獲更多數據,即與用戶名和密碼在同一個表上,如公司名稱,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;}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.