springspring-securityactive-directoryazure-active-directoryspring-security-ldap

Java Spring - Active Directory- How can I Get AD User Details (telNumber, full name, mail , address, description)?


In my college project i would like to get user informations from an AD Server such as the telephone number, the mail, the full name after an authentication.

So i use the default spring security login page and after the authentication, i get the dn and the permissions with an Authentication object. I would like to know how can i get the details of an ad user.

I would like to get his phone number to send a message with an API. This part is already working. I just need to extract the Ad user details to do it.

You will find my code below :

SecurityConfiguration.java :

package com.le_chatelet.le_chatelet_back.ldap;

import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider;

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {

        ActiveDirectoryLdapAuthenticationProvider activeDirectoryLdapAuthenticationProvider =
                new ActiveDirectoryLdapAuthenticationProvider( "mydomain.com", "ldap://adserverip:389");

       activeDirectoryLdapAuthenticationProvider.setConvertSubErrorCodesToExceptions(true);
        activeDirectoryLdapAuthenticationProvider.setUseAuthenticationRequestCredentials(true);
        return activeDirectoryLdapAuthenticationProvider;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception{
        authenticationManagerBuilder
                .authenticationProvider(activeDirectoryLdapAuthenticationProvider());
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception{
        httpSecurity
                .authorizeRequests()
                .anyRequest()
                .fullyAuthenticated()
                .and()
                .formLogin();
    }
}

LoginController.java :

package com.le_chatelet.le_chatelet_back.ldap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.stream.Collectors;

@RestController
public class LoginController {
    @Autowired
    private UserInterface userInterface;

    Logger logger = LoggerFactory.getLogger(LoginController.class);

    @GetMapping("/hello")
    public String sayHello()
    {
        return "hello world";
    }

    @GetMapping("/user")
    @ResponseBody
    public Authentication getLoggedUserDetail(Authentication authentication) {

        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        //get username
        String username = authentication.getName();
        logger.info("username : "+username);

        // concat list of authorities to single string seperated by comma
        String authorityString = authentication
                .getAuthorities()
                .stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.joining(","));
        String role = "role_A";
        boolean isCurrentUserInRole = authentication
                .getAuthorities()
                .stream()
                .anyMatch(role::equals);
        return authentication;
    }
}

If someone can show me code example it would be appreciated.


Solution

  • You can set the a UserDetailsContextMapper on your Provider which allows custom strategy to be used for creating the UserDetails that will be stored as the principal in the Authentication.

    provider.setUserDetailsContextMapper(new PersonContextMapper());
    

    Then you can use the @AuthenticationPrincipal annotation in your Controller to get the Person (or a custom class) instance.

    @GetMapping("/phone-number")
    public String phoneNumber(@AuthenticationPrincipal Person person) {
        return "Phone number: " + person.getTelephoneNumber();
    }
    

    You can find a full LDAP sample application provided by the Spring Security team.