How to get Access Token from Microsoft with grant_type as password using Apex in Salesforce?

How to get Access Token from Microsoft with grant_type as password using Apex in Salesforce?

Get the Tenant Id, client secret value(not the id).


Sample Code:

String strEndPoint = 'https://login.microsoftonline.com/{Enter_Tenant_Id}/oauth2/v2.0/token';
String strBody = 'grant_type=password&scope=https%3a%2f%2fgraph.microsoft.com%2f.default';
strBody += '&client_id={Enter_Client_Id}&client_secret={Enter_Client_Secret}';
strBody += '&username={Enter_Username}&password={Enter_Password}';
HttpRequest req = new HttpRequest();
req.setEndpoint( strEndPoint );
req.setMethod( 'POST' );
req.setHeader( 'Content-Length', String.valueOf( strBody.length() ) );
req.setHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
req.setHeader( 'Accept', 'application/json' );
req.setBody( strBody );
req.setTimeout( 120000 );
Http http = new Http();
HTTPResponse res = http.send( req );
System.debug( res.getBody() );
JSONParser parser = JSON.createParser( res.getBody() );
String strAccessToken;


while ( parser.nextToken() != null ) {


    if ( ( parser.getCurrentToken() == JSONToken.FIELD_NAME ) && 
        ( parser.getText() == 'access_token') ) {
        
        parser.nextToken();
        strAccessToken = parser.getText();
        break;
        
    }
    
}
System.debug( 'Access Token is ' + strAccessToken ); 

Leave a Reply