如何通过ldap和spring安全性从登录用户那里获得电子邮件

时间:2017-04-25 10:08:29

标签: java spring spring-security ldap

嘿,我想成功连接到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";
}}

这是我的春季安全

<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"/>

1 个答案:

答案 0 :(得分:1)

假设您使用inetOrgPerson LDAP架构。

为此LDAP模式定义bean,这将在登录时检索电子邮件:

@Bean
public InetOrgPersonContextMapper userContextMapper() {
    return new InetOrgPersonContextMapper();
}

将bean引用添加到LDAP config:

<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();