gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:37:36 25 4
gpt4 key购买 nike

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

现在我想从用户那里获取更多数据,这些数据与用户名和密码在同一个表中,例如公司名称、ID 等。但是,我不想使用这些信息来登录。

我不知道该怎么做。据我了解,它与 UserDetailsS​​ervice 有关。但是,如果我想在登录期间使用此信息,似乎必须编写自定义 UserDetailsS​​ervice,而这不是我想要的。我只想在用户登录后在应用程序中使用此信息。

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

我找到的自定义 UserDetailsS​​ervice 的所有示例都只使用了用户名和密码,所以我不明白新数据会从哪里进来。

谢谢!

最佳答案

我们所做的就是覆盖 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;}
}

关于java - 从用户获取更多信息 - Spring Security,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8535083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com