首页 > 解决方案 > 重新启动应用程序时,ASP.NET Core 3.1 Microsoft Graph 访问令牌丢失

问题描述

使用ASP.NET Core 3.1and Microsoft Graph API,当应用程序重新启动时Access Token会丢失。用户仍处于登录状态,但无法执行任何Graph API呼叫。

我已经尝试过这里提到的建议管理增量同意和条件访问,但无法刷新令牌并自动恢复。

这是我的控制器:

 readonly ITokenAcquisition tokenAcquisition;
 private GraphServiceClient graphServiceClient;
    
 public HomeController(GraphServiceClient graphServiceClient, ITokenAcquisition tokenAcquisition)
 {
     this.graphServiceClient = graphServiceClient;          
     this.tokenAcquisition = tokenAcquisition;
 }


[HttpGet]
[AuthorizeForScopes(Scopes = new string[] {"user.read"})]
public async Task<IActionResult> A()
{
    User user;
    try
    {
        var scopes = new string[] { "user.read" };
        var accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(scopes);
        user = await graphServiceClient.Me.Request().GetAsync();
    }
    catch (MicrosoftIdentityWebChallengeUserException ex)
    {
        // token is invalid....
        // the throw causes a redirect to the User Login Page            
        throw ex.MsalUiRequiredException;
    }
    
    user = await graphServiceClient.Me.Request().GetAsync();
    Serilog.Log.Debug("{@User}", user);
        
    return View();
}

在上面的代码中,当应用程序重新启动时,访问令牌会丢失,重新抛出异常会导致重定向到登录页面。

如果我然后单击该Sign-in with Microsoft按钮,则用户已经登录,无需输入凭据。如果我随后访问调用 的控制器Graph API,则 API 调用成功。

如何在调用 API 之前刷新令牌?

另外我该如何调试呢?如果我在它没有用处设置断点throw ex.MsalUiRequiredException;,我看不到重定向从哪里获取它的值。

标签: asp.net-coremicrosoft-graph-apiopenid-connectmicrosoft-identity-web

解决方案


Annotation[AuthorizeForScopes(Scopes = new string[] {"user.read"})] 负责处理重定向。

对于调试,请使用AuthorizeForScopes源文件。

在这种特定情况下,AuthenticationScheme未将其设置为值,并且为空。

注释 Action 方法以强制执行特定的方案。例如AuthenticationScheme=OpenIdConnectDefaults.AuthenticationScheme

  [HttpGet]
  [AuthorizeForScopes(Scopes = new string[] {"user.read"}, AuthenticationScheme=OpenIdConnectDefaults.AuthenticationScheme)]
  public async Task<IActionResult> A()
  {
       // snipped
  }

这导致了所需的重定向路径:

https://login.microsoftonline.com/{}/oauth2/v2.0/authorize?client_id={}


推荐阅读