akaparadox
akaparadox

Reputation: 27

Get a refresh token of an SPA application using Microsoft Entra(Azure AD)

I have registered an application in Microsoft Entra as an SPA multitanent application with the permissions as Files.ReadWrite,offline_access and User.Read.

I use MSAL library in my frontend .I am able to get access token with loginPopup method provided by the library.

const microsoftLogin=async ()=>
  {
    const loginResponse=await instance.loginPopup(loginRequest).catch((e) => {
      console.log(e);
    });
   console.log(JSON.stringify(loginResponse));
  } 

Now I also need to get refreshToken so that I can use it to get a new access token any later point in time. The method doesn't provide any authCode or refreshToken in the response. I am retrieving access token via sessionStorage where Microsoft saves values with the key as

UNIQUEID+"."+loginResponse.tenantId+"-login.windows.net-refreshtoken-"+MICROSOFT_CLIENT_ID+"----"

However I am not able to get accessToken with that as well. I tried the api via postman.I don't have client secret. getting accessToken via postman

What do I need to do in order to get refresh_token, get access token via refresh_token via SPA configured application. Do I need to change anything in my Entra Application?

Upvotes: 0

Views: 107

Answers (1)

Rukmini
Rukmini

Reputation: 15574

The error "AADSTS9002327: Tokens issued for the 'Single-Page Application' client-type may only be redeemed via cross-origin requests" usually occurs if you are not passing origin as header in the request.

To generate access and refresh token for SPA application, check the below:

Created a Microsoft Entra ID application and configured redirect URL as SPA:

enter image description here

Used the below endpoint to sign in user and generate code:

https://login.microsoftonline.com/common/oauth2/v2.0/authorize? 
response_type=code  
&client_id=ClientID
&scope=Files.ReadWrite offline_access User.Read
&redirect_uri=https://jwt.ms
&code_challenge=XXX
&code_challenge_method=S256

enter image description here

enter image description here

Generated access and refresh tokens by passing below parameters:

https://login.microsoftonline.com/common/oauth2/v2.0/token

client_id : ClientID
grant_type : authorization_code
code : code
redirect_uri : https://jwt.ms
code_verifier : S256
scope : Files.ReadWrite offline_access User.Read

Make sure to pass origin header (Value is redirect URL):

enter image description here

enter image description here

To refresh the access token, make use of below parameters:

https://login.microsoftonline.com/common/oauth2/v2.0/token
client_id:appID
grant_type:refresh_token
refresh_token: xxx //paste the refresh token that you got above

Make sure to pass origin header (Value is redirect URL):

enter image description here

I am able to successfully refresh the access token:

enter image description here

Upvotes: 3

Related Questions