嘿,我想要成功连接到 ldap 服务器,并使用用户名和密码登录,但之后我想获取登录用户的电子邮件,我该怎么做?
@Controller
public class DemoController{
public MutationServices ms = new MutationServices();
@RequestMapping("login")
public String logout (ModelMap model){
return "/login";
}
@RequestMapping("uploadFile")
public String uploadPage(ModelMap model){
return "/upload";
}
@RequestMapping("utilisateurs")
public String getSimpleUserPage(ModelMap model){
Authenticationauth=SecurityContextHolder.getContext().getAuthentication();
String username = auth.getName();
@SuppressWarnings("unchecked")
Collection<SimpleGrantedAuthority> authorities
(Collection<SimpleGrantedAuthority>) auth.getAuthorities();
System.out.println("auth : " + authorities);
model.addAttribute("username", username);
return "/user";
}}
这是我的 spring 安全
<http>
<form-login login-page="/login"
authentication-failure-url="/login"
/>
<intercept-url pattern="/utilisateurs**" access="ROLE_USERS" />
<logout logout-success-url="/index.jsp" />
<http-basic />
</http>
<authentication-manager>
<ldap-authentication-provider
user-search-filter="(cn={0})"
user-search-base="dc=example,dc=com"
group-search-filter="(member={0})"
group-search-base="dc=example,dc=com"
group-role-attribute="cn"
role-prefix="ROLE_">
</ldap-authentication-provider>
</authentication-manager>
<ldap-server url="ldap://0.0.0.0:10389"
manager-dn="uid=admin,dc=example,dc=com" manager-password="admin"/>
最佳答案
假设您使用 inetOrgPerson
LDAP 架构。
为此 LDAP 模式定义 bean,这将在登录时检索电子邮件:
@Bean
public InetOrgPersonContextMapper userContextMapper() {
return new InetOrgPersonContextMapper();
}
将 bean 引用添加到 LDAP 配置:
<ldap-authentication-provider
user-search-filter="(cn={0})"
user-search-base="dc=example,dc=com"
group-search-filter="(member={0})"
group-search-base="dc=example,dc=com"
group-role-attribute="cn"
role-prefix="ROLE_"
user-context-mapper-ref="userContextMapper">
然后您可以像这样检索电子邮件:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
InetOrgPerson person = (InetOrgPerson)auth.getPrincipal();
String email = person.getMail();
关于java - 我如何使用 ldap 和 spring security 获取登录用户的电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43607674/