javascriptreactjsaxiosmsal.js

Get the access token in localStorage generated by MSAL.JS and put it in Axios


Good day,

I'm trying to implement MSAL.js in my application. Basically, I'm able to implement the msal.js and log in using my email from the AD. I also configured the msal to save my tokenid and accessToken in my localStorage

The accessToken is working in my backend because I tested it using Postman software. But in my app, I don't know how can acquire and put it in my Axios header because the key in the localStorage shows like this:

enter image description here

Where it has a Key in the localStorage of an object.

{"authority":"https://login.microsoftonline.com/TENANTID/","clientId":"CLIENT_ID","scopes":"CLIENT_ID","homeAccountIdentifier":"SOME_HASH"}

With an value of:

accessToken: 'TOKEN_HASH_HERE'
idToken: 'TOKEN_HASH_HERE'
expiresIn: 'TOKEN_HASH_HERE'
homeAccountIdentifier: 'TOKEN_HASH_HERE'

I need to get the access token to be able to put it in my axios header like this:

axios.defaults.headers.common['Authorization'] = `Bearer ${accessTokenFromMsal}`

Thank you in advance.


Solution

  • If you are using msal package in your project, you can visit this samples from Github Repo of MSAL Azure AD.

    Take a look at this AuthProvider.js on line 70

    enter image description here Basically, you can put a console.log(tokenResponse) after the if(tokenResponse) statement. Like this:

    if(tokenResponse){
        console.log(tokenResponse)
    }
    

    On your console log, you'll see the details of the token response. It's tricky but the parameter name of the accessToken that you're looking is idToken.rawIdToken not the accessToken (because as far as I know, the access token is for the request token to the ms graph).

    Then here's you can set an item to your localStorage.

    if (tokenResponse) {
    localStorage.setItem("webApiAccessToken", tokenResponse.idToken.rawIdToken)
    ...
    }
    

    So you'll be able to put it on your request header. Like if you case, using axios

    axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('webApiAccessToken')}`
    

    Note: Make sure to clear that webApiAccessToken in the localStorage whenever the user has clicked the logout method. To do that, just simply localStorage.removeItem("webApiAccessToken")

    I hope it helps you.