"error":"invalid_grant","error_description" -AADSTS65001

MA 0 Reputation points
2023-05-07T17:48:35.38+00:00
Hi, 
I am trying to get the get dynamics token using 'adal-node' library using below snippet, but I am getting invalid grant issue. please do the needfull. FYI, I have given all the required access in client application.

Kind confirm the Dynamic scopes access as in screen shot.

Code :
######

   function acquireToken(dynamicsWebApiCallback){
       //a callback for adal-node
       function adalCallback(error, token) {
           if (!error) {
               //call DynamicsWebApi callback only when a token has been retrieved
               tokenTemp=token.accessToken;
               console.log("Successfully acquired token.");
               dynamicsWebApiCallback(token);
               callback(null,tokenTemp);
           }
           else{
               console.log('Token has not been retrieved. Error: ' + error.stack);
               callback(error,null);
           }
       }
       //call a necessary function in adal-node object to get a token
       adalContext.acquireTokenWithUsernamePassword(resource, username, password, clientId, adalCallback);
   }



Error: Get Token request returned http error: 400 and server response:
###################################################################### {"error":"invalid_grant","error_description":"AADSTS65001: The user or administrator has not consented to use the application with ID 'XXXXXXXXXXXXX' named 'XXXXXX'. Send an interactive authorization request for this user and resource.\r\nTrace ID: 7c07ff1a-315e-480f-9816-0592d67ff600\r\nCorrelation ID: 75c78763-ed0c-4a0d-9cbb-4b6a4693aed8\r\nTimestamp: 2023-05-07 17:22:42Z","error_codes":[65001],"timestamp":"2023-05-07 17:22:42Z","trace_id":"7c07ff1a-315e-480f-9816-0592d67ff600","correlation_id":"75c78763-ed0c-4a0d-9cbb-4b6a4693aed8","suberror":"consent_required"}
Microsoft Security | Microsoft Entra | Microsoft Entra External ID
Microsoft Security | Microsoft Entra | Microsoft Entra ID
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. VasimTamboli 5,215 Reputation points
    2023-05-07T19:13:46.05+00:00

    The error message "invalid_grant" with the description "AADSTS65001" indicates that there is an issue with the credentials being used to acquire the token. There are several possible reasons for this error, including incorrect credentials, expired credentials, or incorrect permission settings for the application.

    Here are a few steps you can take to troubleshoot this issue:

    Check the credentials: Make sure that the username and password being used to acquire the token are correct. If the credentials are incorrect, you will receive an "invalid_grant" error. You can try manually logging in to the application to verify that the credentials are correct.

    Check the expiration date of the credentials: If the credentials have expired, you will receive an "invalid_grant" error. Check the expiration date of the credentials and make sure they are still valid.

    Check the permission settings for the application: If the application does not have the necessary permissions to access the Dynamics API, you will receive an "invalid_grant" error. Verify that the application has been granted the appropriate permissions to access the Dynamics API.

    Try using a different authentication method: If the above steps do not resolve the issue, you can try using a different authentication method. For example, you can try using an OAuth token instead of username and password authentication.

    Check the DynamicsWebApi library: Finally, you can also check the DynamicsWebApi library to ensure that it is set up correctly and is making the correct API calls to the Dynamics API.

    I hope these steps help you resolve the "invalid_grant" error and successfully acquire the Dynamics token using the 'adal-node' library.

    0 comments No comments

  2. Akshay-MSFT 17,956 Reputation points Microsoft Employee Moderator
    2023-05-23T06:26:36.72+00:00

    Hello @MA

    I would recommend to migrate a Node.js app from ADAL to MSAL.

    As per https://techcommunity.microsoft.com/t5/microsoft-entra-azure-ad-blog/update-your-applications-to-use-microsoft-authentication-library/ba-p/1257363

    ADAL end of support is now extended to June 30<sup>th</sup>, 2023. We will retire AAD Graph API any time after June 30<sup>th</sup> , 2023. Through the next six months (January 2023 – June 2023) we will continue informing customers about the upcoming end of support along with providing guidance on migration.

    Kindly follow Example for reference:

    // Import dependencies
    const express = require("express");
    const msal = require('@azure/msal-node');
    
    // Authentication parameters
    const config = {
        auth: {
            clientId: "Enter_the_Application_Id_Here",
            authority: "https://login.microsoftonline.com/Enter_the_Tenant_Info_Here",
            clientSecret: "Enter_the_Client_Secret_Here"
        },
        system: {
            loggerOptions: {
                loggerCallback(loglevel, message, containsPii) {
                    console.log(message);
                },
                piiLoggingEnabled: false,
                logLevel: msal.LogLevel.Verbose,
            }
        }
    };
    
    const REDIRECT_URI = "http://localhost:3000/redirect";
    
    // Initialize MSAL Node object using authentication parameters
    const cca = new msal.ConfidentialClientApplication(config);
    
    // Initialize express
    const app = express();
    
    app.get('/auth', (req, res) => {
    
        // Construct a request object for auth code
        const authCodeUrlParameters = {
            scopes: ["user.read"],
            redirectUri: REDIRECT_URI,
        };
    
        // Request auth code, then redirect
        cca.getAuthCodeUrl(authCodeUrlParameters)
            .then((response) => {
                res.redirect(response);
            }).catch((error) => res.send(error));
    });
    
    app.get('/redirect', (req, res) => {
    
        // Use the auth code in redirect request to construct
        // a token request object
        const tokenRequest = {
            code: req.query.code,
            scopes: ["user.read"],
            redirectUri: REDIRECT_URI,
        };
    
        // Exchange the auth code for tokens
        cca.acquireTokenByCode(tokenRequest)
            .then((response) => {
                res.send(response);
            }).catch((error) => res.status(500).send(error));
    });
    
    app.listen(3000, () =>
        console.log(`listening on port 3000!`));
    
    
    
    

    Please do let me know if you have any further queries.

    Thanks,

    Akshay Kaushik

    Please "Accept the answer" (Yes), and share your feedback if the suggestion answers you’re your query. This will help us and others in the community as well.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.