React SPA中的msal-使用从AcquireTokenRedirect收到的访问令牌 [英] msal in React SPA - use access token received from AcquireTokenRedirect

查看:63
本文介绍了React SPA中的msal-使用从AcquireTokenRedirect收到的访问令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个React SPA,并且我正在使用msal使用loginRedirect对Microsoft用户进行身份验证.登录后,我正在使用AcquireTokenSilent来静默获取访问令牌,以调用Web API.当获取访问令牌失败并且需要进行交互时,我正在使用acquireTokenRedirect.

I have a React SPA and I'm using msal to authenticate Microsoft users using loginRedirect. After the login, I'm acquiring an access token silently using acquireTokenSilent to call a web API. When acquiring the access token fails and interaction is required, I'm using acquireTokenRedirect.

当我使用acquireTokenRedirect时,我看到的是:1.将用户重定向到login.microsoftonline.com.2.返回带有位置标头的302响应,该标头包含重定向URL +访问令牌.3.对我的重定向URL的GET请求-调用我的回调.4.另一个重定向到我的应用程序根目录.

When I use acquireTokenRedirect, what I see is: 1. The user is redirected to login.microsoftonline.com. 2. A 302 response is returned with Location header that contains the redirect url + the access token. 3. A GET request to my redirect url - my callback gets called. 4. Another redirect to my app root.

上一次重定向使我的应用程序可以再次使用,并且我从应用程序的状态中丢失了访问令牌.此外,我失去了将用户重定向到特定路由的功能.

This last redirect makes my app to be served again and I lose the access token from the state of the app. In addition, I lost the ability to redirect the user to a specific route.

获取访问令牌:

getAccessToken = async () => {
    let accessTokenRequest = { scopes: [...]
    };
    try {
      var accessTokenResponse = await 
      this.authAgent.acquireTokenSilent(accessTokenRequest);
      return accessTokenResponse.accessToken;
    } catch (error) {
      const errorCode = error.name;
      if (errorCode === "consent_required" || errorCode === "interaction_required") {
        await this.authAgent.acquireTokenRedirect(accessTokenRequest);
      }

      throw error;
    }
  };

推荐答案

为避免额外的重定向,我需要做的是将Auth config中的"navigateToLoginRequestUrl"参数设置为false.这解决了我的问题.

To avoid the extra redirect, what I needed to do is set the "navigateToLoginRequestUrl" param in Auth config to false. This solves my problem.

这篇关于React SPA中的msal-使用从AcquireTokenRedirect收到的访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆