Reda Benhaddou
Reda Benhaddou

Reputation: 51

How can i get email from a user who logged in , with ldap and spring security

Hey i want can succesfully connect to the ldap server and also login with a username and a password, but after that i want to get the email of the user who logged in, how can i do that?

@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";
}}

this is my spring Security

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

Upvotes: 2

Views: 3441

Answers (1)

holmis83
holmis83

Reputation: 16644

Assuming that you use the inetOrgPerson LDAP schema.

Define bean for this LDAP schema, this will retrieve e-mail on login:

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

Add bean reference to 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">

Then you can retrieve the e-mail like this:

 Authentication auth = SecurityContextHolder.getContext().getAuthentication();
 InetOrgPerson person = (InetOrgPerson)auth.getPrincipal();
 String email = person.getMail();

Upvotes: 4

Related Questions