Authenticate user by LDAP using LdapCtxFactory in Core Java

How I can authenticate User by LDAP using LdapCtxFactory in Core Java.?

Any Java experts please @Vikas_Dhillon @shivang.garg @Mayank

@DebugHorror This solution is already available in IPMS Indusind bank. Any one want to use please deploy the same LDAP microservice.

If we could get a generic code snippet, it would be great

Please find the code:

    protected Mono<Object> validateLdapUser(AuthRequestDto request, ServerRequest.Headers headers) {
        String ldapEndpoint = headers.firstHeader(Constants.X_LDAP_URL);
        log.info("Ldap EndPoint = {} ", ldapEndpoint);
        Assert.hasText(ldapEndpoint, Constants.X_LDAP_URL + Constants.HEADER_NOT_BLANK);
        String ldapDomain = headers.firstHeader(Constants.X_LDAP_DOMAIN);
        log.info("Ldap Domain = {} ", ldapDomain);
        Assert.hasText(ldapDomain, Constants.X_LDAP_DOMAIN + Constants.HEADER_NOT_BLANK);
        String userOrgId = headers.firstHeader(Constants.X_USER_ORG_ID);
        log.info("Ldap User Org Id = {} ", userOrgId);
        Assert.hasText(userOrgId, Constants.X_USER_ORG_ID + Constants.HEADER_NOT_BLANK);
        try {
            Properties env = getLdapProperties(request.getId(), request.getPassword(), ldapEndpoint, ldapDomain);
            DirContext ctx = new InitialDirContext(env);
            ctx.close();
            List<Map<String, Object>> objects = ResponseUtils.getSuccessResponse(request.getId(), userOrgId);
            return Mono.just(objects);
        } catch (Exception e) {
            throw new IllegalArgumentException(e.getMessage(), e);
        }
    }


    private Properties getLdapProperties(String userId, String password, String ldapEndpoint, String ldapDomain) {
        Properties env = new Properties();
        // JNDI provides a standard API for applications to discover and
        // access naming and directory services.
        env.put(Context.INITIAL_CONTEXT_FACTORY, Constants.LDAP_CTX_FACTORY);
        env.put(Context.PROVIDER_URL, ldapEndpoint);
        env.put(Context.SECURITY_PRINCIPAL, userId + ldapDomain);
        env.put(Context.SECURITY_CREDENTIALS, password);
        return env;
    }

3 Likes