Receiving refresh token from MSAL and Outlook in React App

Vadym S 0 Reputation points
2024-08-05T16:54:32.3333333+00:00

How can I receive a refresh token from MSAL in a React app where I need to manage refresh tokens myself? When I console.log the response after authorization, I don't see the refresh token nor the refreshOn property. The purpose of the refresh token is to allow offline team members to access a user's email from/to some contact.

Outlook | Windows | Classic Outlook for Windows | For business
Microsoft Security | Microsoft Authenticator
{count} votes

1 answer

Sort by: Most helpful
  1. Konstantinos Passadis 19,591 Reputation points MVP
    2024-08-05T17:13:24.37+00:00

    Hello @Vadym S

    Welcome to Micrsoft QnA!

    Method 1

    1. Authentication Flow: When a user successfully authenticates (signs in), MSAL stores the refresh token internally.
    2. Acquire Token Silent: After the initial login, use acquireTokenSilent to get a new access token. MSAL will automatically use the refresh token (if needed) to obtain a fresh access token behind the scenes. Here's an example:

    JavaScript

    import { InteractionRequiredAuthError } from "@azure/msal-browser";
    import { msalInstance } from "./authConfig";
    async function acquireToken() {
      const accounts = msalInstance.getAllAccounts();
      if (!accounts || accounts.length === 0) {
        throw new Error("No user account found");
      }
      const request = {
        scopes: ["User.Read", "Mail.Read"], // Include the scopes you need
        account: accounts[0], // Assuming you only have one user
      };
      try {
        const response = await msalInstance.acquireTokenSilent(request);
        const accessToken = response.accessToken;
        // Extract Refresh Token Here:
        const refreshToken = response.refreshToken; // If available
        // You can store the refresh token and the refreshOn time.
        // Store your tokens
        if (refreshToken) localStorage.setItem("refreshToken", refreshToken);
        // Set refreshOn time
        const now = new Date();
        const refreshOn = new Date(now.getTime() + 1000 * response.expiresIn);
        localStorage.setItem("refreshOn", refreshOn);
        return accessToken;
      } catch (error) {
        if (error instanceof InteractionRequiredAuthError) {
          // Trigger interactive authentication (login)
          msalInstance.acquireTokenRedirect(request);
        } else {
          throw error;
        }
      }
    }
    
    
    
    

    Refresh Token Storage: You can extract the refresh token and refreshOn time. Store these securely (e.g., encrypted in localStorage or using a more robust storage mechanism).

    OR Method 2 :

    Manual Refresh Flow

    1. Check Refresh Time: Before each API call, compare the current time with the stored refreshOn time. If it's time to refresh, proceed.
    2. Acquire Token with Refresh Token: Use MSAL's acquireTokenByRefreshToken method, passing in the stored refresh token to get a new access token.

    Example: Refreshing Token

    JavaScript

    async function refreshToken() {
      const refreshToken = localStorage.getItem("refreshToken");
      if (!refreshToken) {
        throw new Error("Refresh token not found");
      }
      const response = await msalInstance.acquireTokenByRefreshToken({
        refreshToken,
        scopes: ["User.Read", "Mail.Read"],
      });
      const newAccessToken = response.accessToken;
      // Store the new access token
      localStorage.setItem("accessToken", newAccessToken);
      // Set the new refreshOn time
      const now = new Date();
      const refreshOn = new Date(now.getTime() + 1000 * response.expiresIn);
      localStorage.setItem("refreshOn", refreshOn);
      return newAccessToken;
    }
    
    

    These are examples you may need to adjust so your Application can work ! !

    --

    I hope this helps!

    Kindly mark the answer as Accepted and Upvote in case it helped!

    Regards

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.