从用户 - Spring Security获取更多信息

Joã*_*iel 8 java security spring login

我在我的应用程序中实现了Spring Security.我使用了默认实现,即我使用自己的参数(DataSource,Secured Areas等)配置它,但我没有编写任何Custom实现.

现在我想从用户那里捕获更多数据,即与用户名和密码在同一个表上,如公司名称,ID等.但是,我不想使用此信息才能登录.

我不知道怎么做.从我读过的内容来看,它与UserDetailsS​​ervice有关.但是,如果我想在登录期间使用此信息,那么编写自定义UserDetailsS​​ervice似乎是必要的,这不是我想要的.我只想在用户登录后在应用程序中使用此信息.

它真的与UserDetailsS​​erver有关吗?这是我必须修改的唯一文件吗?

我发现自定义UserDetailsS​​ervice的所有示例都使用了用户名和密码,因此我无法理解新数据的来源.

谢谢!

Pet*_*ete 14

覆盖UserDetailsS​​ervice就是我们所做的..你需要实现自己的UserDetailsS​​ervice和你自己的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;}
}
Run Code Online (Sandbox Code Playgroud)

  • ((CustomUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getCompany()为我工作 (3认同)
  • `((CustomUserDetails)SecurityContextHolder.getContext().getAuthentication().getDetails()).getCompany()`应该有效. (2认同)