MSAL and OAuth 2.0 - Request an authorization code programmatically

3.5k views Asked by At

Goal is to get access token from MSAL programmatically for Cypress e2e tests. We use V2.0 API.

According to this I first need to get the authorization code: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#request-an-authorization-code

to get the access token https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#request-an-access-token

So in order to get authorization code I would need to do this request

// GET
// Line breaks for legibility only

https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=code
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&response_mode=query
&scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fmail.read
&state=12345
&code_challenge=YTFjNjI1OWYzMzA3MTI4ZDY2Njg5M2RkNmVjNDE5YmEyZGRhOGYyM2IzNjdmZWFhMTQ1ODg3NDcxY2Nl
&code_challenge_method=S256

But this returns text/html so I would need to manually login to get the code.

Is there any way to progammatically to get the authorization code?

1

There are 1 answers

1
anmatika On

This is how I got it solved by creating a login command. The command fetches the token programatically and stores it into localStorage.

import 'cypress-localstorage-commands';

Cypress.Commands.add('login', () => {
  const request = {
    method: 'POST',
    form: true,
    url: `https://login.microsoftonline.com/${Cypress.config('tenantId')}/oauth2/v2.0/token`,
    body: {
      grant_type: 'client_credentials',
      client_id: Cypress.config('clientId'),
      client_secret: Cypress.config('clientSecret'),
      scope: `${Cypress.config('clientId')}/.default`,
    },
  };

  cy.request(request).then(response => cy.setLocalStorage('msal.idtoken', response.body.access_token));
});