我知道
SecurityContextHolder.getContext().getAuthentication().getPrincipal();
将返回一个UserDetails对象,可以获取用户名。但是我们假设我需要来自自定义用户对象(MyUser)的更多数据。从UserDetails对象获取MyUser的正确方法是,例如,UserDetails只提供名称,但同一个名称可以由多个用户使用。 我的意思是如果我只使用名称搜索MyUser的存储库,它就可以返回多个用户。
答案 0 :(得分:1)
此用户名并不代表真实的用户名。校长的“名字”通常是独一无二的。例如,它可以是userId。
public static String getCurrentUserLogin() {
SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication = securityContext.getAuthentication();
String userName = null;
if (authentication != null) {
if (authentication.getPrincipal() instanceof UserDetails) {
UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
userName = springSecurityUser.getUsername();
} else if (authentication.getPrincipal() instanceof String) {
userName = (String) authentication.getPrincipal();
}
}
return userName;
}
答案 1 :(得分:0)
您只需要转换自定义UserDetails对象,例如,在我的案例中,Customer对象实现了UserDetails对象。
Customer userDetails = (Customer)SecurityContextHolder.getContext().
getAuthentication().getPrincipal();
我的WebSecurityConfig是
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private MyCustomAuthoritiesPopulator customerAuthPopulator;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().fullyAuthenticated().and().formLogin();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.ldapAuthentication().ldapAuthoritiesPopulator(customerAuthPopulator)
.userDetailsContextMapper(userDetailsContextMapper())
.userDnPatterns("CN={0},OU=People,DC=com").contextSource()
.url("ldap://myCompanyAD-Domain:389");
}
@Bean
public UserDetailsContextMapper userDetailsContextMapper() {
return new CustomUserDetailsContextMapper();
}
}
CustomUserDetailsContextMapper实现
@Configuration
public class CustomUserDetailsContextMapper extends LdapUserDetailsMapper implements UserDetailsContextMapper {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Override
public LdapUserDetails mapUserFromContext(DirContextOperations ctx, String username,
Collection<? extends GrantedAuthority> authorities) {
log.info("LdapUserDetails start");
LdapUserDetailsImpl details = (LdapUserDetailsImpl) super.mapUserFromContext(ctx, username, authorities);
Customer user = new Customer(details);
// details = (Customer) super.mapUserFromContext(ctx, username, authorities);
try {
user.setDisplayName(ctx.getStringAttribute("displayName"));
user.setEmail(ctx.getStringAttribute("mail"));
user.setPhone(ctx.getStringAttribute("telephoneNumber"));
user.setOrgUnit(ctx.getStringAttribute("division"));
log.info("DN from ctx: " + ctx.getDn()); // return correct DN
for (NamingEnumeration attr = ctx.getAttributes().getAll(); attr.hasMore();) {
Attribute attribute = (Attribute) attr.next();
log.info("Attribute id: " + attribute.getID());
for (NamingEnumeration val = attribute.getAll(); val.hasMore();) {
log.info("Attribute value: " + val.next());
}
}
log.info("Attributes size: " + ctx.getAttributes().size()); // always returns 0
} catch (NamingException e) {
log.error("Exception Caught", e);
}
return user;
}
@Override
public void mapUserToContext(UserDetails user, DirContextAdapter ctx) {
// default
}
}
客户实施
@Component
public class Customer implements LdapUserDetails {
private String DisplayName;
private String Email;
private String Phone;
private String OrgUnit;
private LdapUserDetailsImpl ldapCtx;
public Customer() {
super();
// TODO Auto-generated constructor stub
}
public Customer(LdapUserDetailsImpl copyMe ) {
super();
ldapCtx = copyMe;
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Customer [DisplayName=" + DisplayName + ", Email=" + Email + ", Phone=" + Phone + ", OrgUnit=" + OrgUnit
+ "] LdapUserDetails [" + ldapCtx.toString() + "]";
}
public String getDisplayName() {
return DisplayName;
}
public void setDisplayName(String displayName) {
DisplayName = displayName;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getOrgUnit() {
return OrgUnit;
}
public void setOrgUnit(String orgUnit) {
OrgUnit = orgUnit;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
// TODO Auto-generated method stub
ArrayList<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
list.add((new SimpleGrantedAuthority("ROLE_USER")));
return list;
}
@Override
public String getPassword() {
// TODO Auto-generated method stub
return ldapCtx.getPassword();
}
@Override
public String getUsername() {
// TODO Auto-generated method stub
return ldapCtx.getUsername();
}
@Override
public boolean isAccountNonExpired() {
// TODO Auto-generated method stub
return ldapCtx.isAccountNonExpired();
}
@Override
public boolean isAccountNonLocked() {
// TODO Auto-generated method stub
return ldapCtx.isAccountNonLocked();
}
@Override
public boolean isCredentialsNonExpired() {
// TODO Auto-generated method stub
return ldapCtx.isCredentialsNonExpired();
}
@Override
public boolean isEnabled() {
// TODO Auto-generated method stub
return ldapCtx.isEnabled();
}
@Override
public void eraseCredentials() {
// TODO Auto-generated method stub
}
@Override
public String getDn() {
// TODO Auto-generated method stub
return ldapCtx.getDn();
}
}