9

Authentication: Remote LDAP Server in WebFlux - DZone Java

 2 years ago
source link: https://dzone.com/articles/authentication-with-remote-ldap-server-in-spring-w
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Authentication With Remote LDAP Server in Spring WebFlux

A guide for Java developers who want to integrate Spring Boot Webflux applications with a remote LDAP server and authenticate/authorize their users with JWT.

Jan. 12, 22 · Java Zone · Tutorial

Join the DZone community and get the full member experience.

Join For Free

In my previous article, we covered authentication and authorization with remote LDAP servers in Spring Web MVC. Since base concepts are the same, some sections are unavoidably the same in these two articles and they are kept in both articles in order to create a seamless reading experience for WebFlux and MVC learners. 

In this article, we will develop a reactive Spring Boot project and integrate into remote LDAP through Spring Security. In addition, we will perform authentication (auth) and authorization (autz) operations over JWT (JSON Web Token) for the APIs we will open. 

As a business scenario, our application will serve as a user portal service that authenticates and authorizes users against specific APIs with their LDAP authorities. First, let's talk about the terms we will use.

  • Authentication (Auth): Validation of your credentials (i.e., Username/ID and password) to verify your identity. In short, it is about WHO you are.
  • Authorization (Autz): Authorization takes place after auth and is for determining the access ability of authenticated users to resources and to what extent. In short, it is about WHAT you can do.
  • JWT (JSON Web Token): An open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. You may get detailed information from its official website.
  • LDAP: Lightweight Directory Access Protocol is an industry-standard application protocol for accessing and maintaining distributed directory information services. A common use of LDAP is to provide a central place to store user information such as username, password, organizational info (team, manager, etc.).

Development Environment Information

For the sake of being on the same page, below is our development environment information. Version information for project dependencies is discussed in the next section.

  • OS: Windows 10 20H2
  • IDE: IntelliJ IDEA 2019.3.1 (Ultimate Edition)
  • Java: 1.8
  • Spring Boot: 2.5.8
  • Apache Maven: 3.5.0

Preparing the Spring Boot Project

We are initializing our Spring Boot project from Spring Initializr.

15528016-1641733366642.png

The dependencies shown above are not the ultimate list. We will add needed dependencies while walking through the following titles.

LDAP Integration

We will integrate to a remote LDAP server to authenticate the user and retrieve information (roles, manager, email, etc.) about him to authorize for specific resources. In order to see what is in the directory, we use Apache Directory Studio (Version: 2.0.0.v20210213-M16). 

Apache Directory Studio sample screen.

In order to integrate with the LDAP server, we should add the following dependency to our project;

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.ldap</groupId>
    <artifactId>spring-ldap-core</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-ldap</artifactId>
</dependency>

With the above steps, we have prepared our application for talking to a remote LDAP server. We'll cover how to talk with it for auth/autz purposes in later sections.

Before we deliver code samples, it is useful to know that field declarations, imports, and Javadocs have been cropped out from the code samples below to keep this article as fluent as possible. Please refer to the GitHub repo for full versions.

Preparing APIs

For this project, we have two roles: FINANCE and BUSINESS. We authorize these roles for paths /finance-zone and /business-zone respectively. We prepare FinanceController and BusinessController for this purpose as follows:

@RestController
@RequestMapping("/finance-zone")
public class FinanceController {
    @GetMapping
    public ResponseEntity<String> financeMethod() {
            return ResponseEntity.ok("Congrats! If you see this, you have FINANCE role...");
    }
}
@RestController
@RequestMapping("/business-zone")
public class BusinessController {
    @GetMapping
    public ResponseEntity<String> businessMethod() {
            return ResponseEntity.ok("Congrats! If you see this, you have BUSINESS role...");
    }
}

Now, it is time to describe how authentication is being handled. 

Authentication is done by querying the remote LDAP server, with the client's LDAP username/password being sent to the /authentication API. This is a @RestController, which calls PortalUserService (that is actually a service class implementing UserDetailsService of Spring Security Core. This service is also used in the authorization phase.)

@RestController
@RequestMapping("/authenticate")
@RequiredArgsConstructor
@Slf4j
public class AuthenticateController {
    private final PortalUserService portalUserService;
    @PostMapping
    public ResponseEntity<AuthResponse> authenticate(@RequestBody @NonNull AuthRequest authRequest) {
            log.info("Authentication request for user {} received!", authRequest.getUsername());
            return ResponseEntity.ok(portalUserService.authenticateUser(authRequest.getUsername(), authRequest.getPassword()));
    }
}

Introducing Auth/Autz Exception Handling Mechanisms

For unauthenticated requests (i.e., access attempts with expired JWT tokens) we prepare AuthenticationEntryPointto handle this case and return the descriptive response to the client. Here is the code:

@Configuration
@Slf4j
public class AuthenticationEntryPoint implements ServerAuthenticationEntryPoint {
    @Override
    public Mono<Void> commence(ServerWebExchange serverWebExchange, AuthenticationException e) {
        if (CollectionUtils.isNotEmpty(serverWebExchange.getRequest().getHeaders().get(Constants.HEADER_AUTHORIZATION))) {
            return Mono.empty();
        } else {
            log.info("Unauthenticated access attempt to resource {} with HttpMethod of {} Token: {}",
                    serverWebExchange.getRequest().getPath(),
                    StringUtils.defaultString(serverWebExchange.getRequest().getMethod().name(), StringUtils.EMPTY),
                    serverWebExchange.getRequest().getHeaders().get(Constants.HEADER_AUTHORIZATION));
            return Mono.error(new UnauthenticatedException("Please login to access this resource!"));
        }
    }
}

For this scenario, the client will receive a "HttpStatus.400 (Bad Request)" response since the authentication info being sent is bad.

For unauthorized requests (i.e., access attempts to an API that is not allowed by that user's role), we prepare AccessDeniedHandlerto handle this case and return the descriptive response to the client. Here is the code:

@Configuration
@Slf4j
public class AccessDeniedHandler implements ServerAccessDeniedHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange, AccessDeniedException e) {
        log.info("Access Denied. Unauthorized access attempt to resource {} from {} with HttpMethod of {} Authorization header: {}",
                serverWebExchange.getRequest().getPath(),
                Optional.ofNullable(serverWebExchange.getRequest().getHeaders().get(Constants.HEADER_X_FORWARDED_FOR))
                        .orElse(Collections.singletonList(serverWebExchange.getRequest().getRemoteAddress().getHostName())),
                StringUtils.defaultString(serverWebExchange.getRequest().getMethod().name(), StringUtils.EMPTY),
                serverWebExchange.getRequest().getHeaders().get(Constants.HEADER_AUTHORIZATION));
        return Mono.error(new UnauthorizedException("You are trying to access to a resource that you're not allowed to."));
    }
}

We'll use both mechanisms while configuring security in later topics.

Introducing JWT Handling Mechanism

The /authentication API, described under previous sections, returns a JWT to the client. The client should send this token in the Authorization request header with the "Bearer" prefix while consuming APIs. In this phase, our application validates and extracts JWT from the request and executes authorization checks by the data enclosed in that token. (All data should not be stored in tokens for security purposes. We'll extract the username from the token and query the LDAP server for the roles of that user. Authorization checks are being executed on that data.)

Our JwtUtil class, copied (partially) below, sits in the center of the logic described above:

@Service
@Slf4j
public class PortalUserService implements UserDetailsService {
    private static final String LDAP_ATTRIBUTE_USERPASSWORD = "userpassword";
    private BaseLdapPathContextSource contextSource;
    @PostConstruct
    private void prepareLdapContext() {
        String ldapFullUrl = new StringBuilder(this.ldapUrl)
                .append(":")
                .append(this.ldapPort)
                .append("/")
                .append(this.ldapRoot)
                .toString();
        DefaultSpringSecurityContextSource localContextSource = new DefaultSpringSecurityContextSource(ldapFullUrl);
        localContextSource.setUserDn(this.ldapManagerDn);
        localContextSource.setPassword(this.ldapManagerPassword);
        localContextSource.afterPropertiesSet();
        this.contextSource = localContextSource;
    }
    @Override
    public UserDetails loadUserByUsername(String username) {
        try {
            log.info("Searching LDAP for user {}", username);
            SearchControls searchControls = new SearchControls();
            searchControls.setReturningAttributes(new String[]{Constants.LDAP_ATTRIBUTE_ISMEMBEROF, Constants.LDAP_ATTRIBUTE_UID});
            SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate(this.contextSource);
            template.setSearchControls(searchControls);
            DirContextOperations searchResult = template.searchForSingleEntry(this.ldapUserSearchBase, this.ldapUserSearchFilter, new String[]{username});
            List<String> grantedAuthorities = new ArrayList<>(this.getGrantedAuthorities(searchResult));
            log.info("User {} retrieved. User's roles are: {}", username, grantedAuthorities);
            return new PortalUserPrincipal(PortalUser.builder()
                    .username(username)
                    .grantedAuthorities(grantedAuthorities)
                    .build());
        } catch (IncorrectResultSizeDataAccessException ex) {
            log.error("Unexpected result size returned from LDAP for search for user {}", username);
            if (ex.getActualSize() == 0) {
                throw new UsernameNotFoundException("User " + username + " not found in LDAP.");
            } else {
                throw ex;
            }
        }
    }
    public AuthResponse authenticateUser(String username, String password) {
        Assert.isTrue(StringUtils.isNotBlank(username), "Username should not left blank!");
        Assert.isTrue(StringUtils.isNotBlank(password), "Password should not left blank!");
        List<String> grantedAuthorities = this.doLdapSearch(username, password);
        log.info("Authentication of {} successfull! Users groups are: {}", username, grantedAuthorities);
        PortalUserPrincipal portalUserPrincipal = new PortalUserPrincipal(PortalUser.builder()
                .username(username)
                .grantedAuthorities(grantedAuthorities)
                .build());
        Authentication authentication = new UsernamePasswordAuthenticationToken(portalUserPrincipal, null, portalUserPrincipal.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        List<String> userRoles = portalUserPrincipal.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());
        return AuthResponse.builder()
                .username(username)
                .message(Constants.MESSAGE_SUCCESS)
                .status(Constants.STATUS_CODE_SUCCESS)
                .userRoles(userRoles)
                .userPermissions(new ArrayList<>())
                .token(JwtUtils.createJWTToken(username, this.jwtSecret, this.jwtTimeout, userRoles))
                .build();
    }
    private List<String> doLdapSearch (String username, String password) {
        try {
            PortalUserPrincipal portalUserPrincipal = new PortalUserPrincipal(PortalUser.builder().username(username).build());
            Authentication authentication = new UsernamePasswordAuthenticationToken(portalUserPrincipal, password);
            PasswordComparisonAuthenticator passwordComparisonAuthenticator = new PasswordComparisonAuthenticator(this.contextSource);
            passwordComparisonAuthenticator.setPasswordEncoder(new LdapShaPasswordEncoder());
            passwordComparisonAuthenticator.setUserDnPatterns(new String[]{this.ldapUserSearchFilter + "," + ldapUserSearchBase});
            passwordComparisonAuthenticator.setUserAttributes(new String[]{Constants.LDAP_ATTRIBUTE_ISMEMBEROF, LDAP_ATTRIBUTE_USERPASSWORD});
            DirContextOperations authenticationResult = passwordComparisonAuthenticator.authenticate(authentication);
            return this.getGrantedAuthorities(authenticationResult);
        } catch (BadCredentialsException e) {
            log.error("LDAP authentication failed for {}. Wrong password!", username);
            throw e;
        } catch (UsernameNotFoundException e) {
            log.error("LDAP authentication failed for {}. No such user!", username);
            throw e;
        }
    }
    private List<String> getGrantedAuthorities(DirContextOperations ldapResult) {
        if (ArrayUtils.isEmpty(ldapResult.getStringAttributes(Constants.LDAP_ATTRIBUTE_ISMEMBEROF))) {
            log.info("No roles found for user: {}. Returning empty granted authorities list.", ldapResult.getStringAttribute(Constants.LDAP_ATTRIBUTE_UID));
            return  new ArrayList<>();
        }
        return Arrays.asList(ldapResult.getStringAttributes(Constants.LDAP_ATTRIBUTE_ISMEMBEROF)).stream()
                .filter(groupDn -> StringUtils.endsWith(groupDn, this.groupBase))
                .map(groupDn -> StringUtils.substringBetween(StringUtils.upperCase(groupDn), "CN=", ","))
                .collect(Collectors.toList());
    }
}

Configuring Spring Security

This is the point where we should describe the core of this whole mechanism: WebSecurityConfiguration. In this class, we configure the security of our web application under the configure method:

@Configuration
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
@RequiredArgsConstructor
public class WebSecurityConfiguration {
    private final AuthenticationSuccessHandler authenticationSuccessHandler;
    private final AuthenticationEntryPoint authenticationEntryPoint;
    private final AccessDeniedHandler accessDeniedHandler;
    private final PortalUserService portalUserService;
    @Value("${autz.permitted.paths.all}")
    private String[] permittedPaths;
    @Value("${autz.permitted.paths.finance}")
    private String[] financeRolePermittedPaths;
    @Value("${autz.permitted.paths.business}")
    private String[] businessRolePermittedPaths;
    @Value("${jwt.secret}")
    private String jwtSecret;
    @Bean
    SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        AuthenticationWebFilter authenticationWebFilter = new AuthenticationWebFilter(new UserDetailsRepositoryReactiveAuthenticationManager(portalUserService));
        authenticationWebFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
        http
                .cors()
                .and()
                .csrf()
                    .disable()
                .addFilterAt(authenticationWebFilter, SecurityWebFiltersOrder.FIRST)
                .authorizeExchange()
                    .pathMatchers(permittedPaths).permitAll()
                    .pathMatchers(financeRolePermittedPaths).hasAuthority(Constants.LDAP_ROLE_FINANCE)
                    .pathMatchers(businessRolePermittedPaths).hasAuthority(Constants.LDAP_ROLE_BUSINESS)
                    .anyExchange().denyAll()
                .and()
                    .exceptionHandling()
                    .authenticationEntryPoint(this.authenticationEntryPoint)
                    .accessDeniedHandler(this.accessDeniedHandler)
                .and()
                    .securityContextRepository(NoOpServerSecurityContextRepository.getInstance())
                    .logout()
                        .disable()
                    .formLogin()
                        .disable();
        http.addFilterAt(new JwtRequestFilter(jwtSecret, portalUserService, authenticationSuccessHandler), SecurityWebFiltersOrder.FIRST);
        return http.build();
    }
}

The following list explains the above code:

  1. Cors and csrf strategies are declared. We disabled csrf since we use JWT for authorization in each and every request.
  2. Under authorizeExchange(), we declared "who has access to where." Authorization checks are done according to these rules.
  3. Since we authorize each request with JWT, we don't need a session. We declared the session creation policy as stateless by setting securityContextRepository to NoOpServerSecurityContextRepository. (This also works well if you don't share sessions between application servers.)
  4. What will happen when an authentication or authorization error occurs? This question is being answered under exceptionHandling(). We covered the contents of these classes in previous sections. 
  5. At last, we disabled the built-in login mechanism of Spring Security, since we provided the  /authentication API. We also disabled the logout mechanism, because it is beyond the scope of this article.

Testing

We test our application with Postman. You can find the exported Postman collection in my GitHub repository.

First things first; we authenticate our Finance user and retrieve the token:
Screenshot showing user authentication.

Here is the response we received:Screenshot of user authentication response.

Now its time to call the /finance API with the above token:Screenshot of the Finance API.

Here is the response we received;
Response returned for Finance API.

So what if we call the /business API with our Finance user? Here is the request:
Screenshot showing /business API request.

Here is the response:

15528021-1641734839567.png

Conclusion

In this article, we developed a Spring Boot project and integrated it into a remote LDAP through Spring Security. In addition, we performed authentication and authorization operations over JWT for the APIs we opened. 

You can get the full implementation of this article from my GitHub repository.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK