spring - Spring Boot LDAP 身份验证:在身份验证时获取用户数据
问题描述
我开发了一个 Spring Boot 应用程序,我想使用 LDAP 服务器执行身份验证。在生产中它将是一个 Active Directory 服务器,但在开发过程中我只是使用这个公共 LDAP 测试服务器
我使用以下类让它工作:
一个简单的 LDAP 配置类。它从我的文件中读取application.properties
与 LDAP 相关的属性。
@Configuration
public class LdapConfiguration {
//Getting values from properties file
@Value("${ldap.urls}")
private String ldapUrls;
@Value("${ldap.base.dn}")
private String ldapBaseDn;
@Value("${ldap.username}")
private String ldapSecurityPrincipal;
@Value("${ldap.password}")
private String ldapPrincipalPassword;
@Value("${ldap.user.dn.pattern}")
private String ldapUserDnPattern;
@Value("${ldap.enabled}")
private String ldapEnabled;
public LdapConfiguration() {
}
... getters and setters ...
}
还有一个 WebSecurityConfiguration,它实际上从 LdapConfiguration 类中读取以将其用于身份验证:
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private LdapConfiguration ldapConfiguration;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().fullyAuthenticated()
.and()
.formLogin();
}
// Update configure method for the online test server
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.contextSource()
.url(ldapConfiguration.getLdapUrls() +ldapConfiguration.getLdapBaseDn())
.managerDn(ldapConfiguration.getLdapSecurityPrincipal())
.managerPassword(ldapConfiguration.getLdapPrincipalPassword())
.and()
.userDnPatterns(ldapConfiguration.getLdapUserDnPattern());
}
使用此配置,LDAP 身份验证工作:我得到一个带有登录表单的漂亮 HTML 页面,并使用正确的凭据,我可以使用该网站。
这是我的问题:在登录阶段之后,如果我运行类似
UserDetails ud = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
System.out.println(ud);
这就是我会得到的:
LdapUserDetailsImpl@fd8cece1:
Dn: uid=tesla,dc=example,dc=com;
Username: tesla;
Password: [PROTECTED];
Enabled: true;
AccountNonExpired: true;
CredentialsNonExpired: true;
AccountNonLocked: true;
Granted Authorities: ROLE_SCIENTISTS
我对特斯拉的全名一无所知(在 LDAP 服务器中,作为 field CN
)。获得有关经过身份验证的用户的所有数据会很好。
当然,我可以对 LDAP 服务器运行单独的查询,询问有关用户的详细信息 username tesla
。但是,这意味着向 LDAP 服务器发出额外的请求,因此这似乎不是一个好的解决方案。
当我执行身份验证时,有没有办法指定我想从 LDAP 服务器获取哪些字段?(在使用 Active Directory 服务器时,它会发生很大变化吗?)
提前致谢。
解决方案
推荐阅读
- android - 在哪里可以找到 Xamarin Android 在 Visual Studio 中创建的密钥库的默认位置?
- javascript - 快照网站上的所有 CSS
- java - Java使用扫描仪将txt输入到二维数组
- r - 重新编码变量
- jmeter - Jmeter 图片上传脚本
- java - GSON IllegalStateException:应为 BEGIN_OBJECT 但为 BEGIN_ARRAY
- android - 处理表盘中时区的更改
- android - Androidx 和数据绑定
- php - 在另一个while循环中使用while循环的结果
- html - 无法在 iOS 中使用