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

时间:2011-12-16 13:47:35

标签: java security spring login

我已在我的应用程序中实现了Spring Security。我使用了默认实现,即我使用自己的参数(DataSource,安全区域等)配置它,但我没有编写任何自定义实现。

现在我想从用户那里捕获更多数据,这些数据与用户名和密码在同一个表中,如公司名称,ID等。但是,我不想使用此信息才能登录。< / p>

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

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

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

谢谢!

1 个答案:

答案 0 :(得分: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;}
}