Search code examples
azureazure-active-directoryazure-ad-graph-apiadal4j

Authenticate guest user in Azure AD using graph api


I am trying to authenticate users in my web application using Azure AD to store user records. For authenticating the user I am using ADAL4J API (https://github.com/AzureAD/azure-activedirectory-library-for-java). I am using the the AuthenticationContext.acquireToken() method to acquire the token for users. This is working for local users in my directory but not for guest users invited to the directory.

While authenticating guest users I am getting an error : "To sign into this application the account must be added to the directory" . However, I am sure the user has been successfully added to the directory as seen through the Azure Portal. Also, I have verified the same using the graph API where I can see the guest users in the user list in the directory.

So the question is how do I authenticate the guest user in my web application through code (not through redirecting to the Azure UI)?

EDIT : This the method to which I am passing the username and password of the user:

 private static AuthenticationResult getAccessTokenFromUserCredentials(
    String username, String password) throws Exception {
    AuthenticationContext context = null;
    AuthenticationResult result = null;
    ExecutorService service = null;
    try {
         service = Executors.newFixedThreadPool(1);
         context = new AuthenticationContext("https://login.windows.net/<tenant_name>", false, service);
         Future<AuthenticationResult> future = context.acquireToken(
            "https://graph.windows.net", CLIENT_ID, username, password,
            null);
         result = future.get();
     } catch(Exception e){
        e.printStackTrace();
     } finally {
         service.shutdown();
     }

     if (result == null) {
         throw new ServiceUnavailableException(
                 "authentication result was null");
     }
     return result;
 }

Solution

  • With the information you provided, I feel like the issue here is related to the login endpoint. Remember that the common endpoint uses the logged in user to help 'guess' which tenant endpoint to authenticate to. If you are doing more tricky things like guest accounts, it is very likely the common endpoint will not figure out all the right details.

    I recommend you specifically call your tenant's login endpoint, through the whole process, and see if that resolves your issues.

    Let me know if this helps!