Fetch azure access token using MSAL(React)

How can I fetch the Access Token token using react-aad-msal?I try with authProvider.getAccessToken() but this is for every API call, I need to get my token from local storage. Here is my code:

import { authProvider } from './const/authProvider';

const token =  authProvider.getAccessToken();
  React.useEffect(()=>{
   fetch(url,{
    method: "GET",
        headers: {
          Authorization:  "Bearer" + token,
          'Content-Type': 'application/json'
        },
      })
    .then(res=> res.json())
    .then((response) => {
  
 response.name)
    })
    .catch((error) => console.log(error));
  },[]);

The code you’ve got there gets it from your local browser storage, it’s only going to actually make a request if the token isn’t there or has expired (I assume it either leverages AbortController under the hood or the session function returns if one is there and the function exits early), if I’m looking at the right docs. (And if I’m looking at the right docs, which I seem to be, is there a reason you’re using this deprecated library rather than Microsoft’s own one which is recommended?)

The token is located in local storage , I don’t know how to access this token here is how it looks like

in authProvider this is the code:

// authProvider.js

import { MsalAuthProvider, LoginType } from "react-aad-msal";

// Msal Configurations

const config = {

  auth: {

    authority:

      "https://login.microsoftonline.com/...",

    clientId: "...",

    navigateToLoginRequestUrl: true,

  },

  cache: {

    cacheLocation: "localStorage",

    storeAuthStateInCookie: true,

  },

};

// Authentication Parameters

const authenticationParameters = {

  scopes: [],

};

// Options

const options = {

  loginType: LoginType.Redirect,

  tokenRefreshUri: window.location.origin + "/auth.html",

};

export const authProvider = new MsalAuthProvider(config, options);

What are you trying to get out of the token? Tokens aren’t encrypted, so you can literally just decode it and get at the values in it, but that library will provide methods to do that for you

I need to get “authority” and its value “client_Id”.I need this to access my API, it used bearer token authorization. I try to get this with localstorage.getitem but it gives null.

So, with the auth for the API, if it’s the same as AWS I assume you need to make requests like theAPI.makerequest(key, request). If so, I assume you should be able to pass the result of whatever the access token function returns to. What are you trying to run afterwards?

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.