javaandroidactive-directory

How to authenticate User Credentials against AD from Android Java


I have a User Login, which I need to authenticate using the Active Directory. Is there a way to do this?

I'm using Android/Java. I am in the same Network as the Domain Controller.


Solution

  • You can use the UnboundID LDAP SDK.

    UnboundID: "UnboundID Website"

    This would then allow you to authenticate the Credentials against the Domain Controller.

    private static final String DC_ADDRESS = "xx.xxx.xxx.xxx";
    
    public static Boolean authenticate(String bindDN, String password) {
        String searchFilter = "(sAMAccountName=" + username +")";
    
        final SSLUtil sslUtil = new SSLUtil(new TrustAllTrustManager());
    
        try {
            SSLSocketFactory sslSocketFactory = sslUtil.createSSLSocketFactory();
            JavaToLDAPSocketFactory ldapSocketFactory =
                    new JavaToLDAPSocketFactory(sslSocketFactory);
            LDAPConnection c = new LDAPConnection(ldapSocketFactory, DC_ADDRESS, 636);
    
            BindResult bindResult = c.bind(bindDM, password);
    
            if (c.isConnected()) {
                c.close();
            }
    
            if(bindResult.getResultCode() != ResultCode.SUCCESS) {
                Log.w(TAG, "Authentication failed");
                return false;
            }
    
            return true;
        } catch(LDAPException e) {
            LogUtil.w(TAG, "Authentication failed: " + e.getMessage());
            LogUtil.e(TAG, "StackTrace: " + Arrays.toString(e.getStackTrace()));
            return e.toLDAPResult().getResultCode();
        } catch(Exception e) {
            LogUtil.e(TAG, "Exception caught while authenticating: " + e.getMessage());
            LogUtil.e(TAG, "StackTrace: " + Arrays.toString(e.getStackTrace()));
        }
        return false;
    }