代码之家  ›  专栏  ›  技术社区  ›  Itanex

AcquireTokenSilentAsync无法对用户进行身份验证

  •  1
  • Itanex  · 技术社区  · 6 年前

    我正在尝试获取静默令牌请求以初始化 ConfidentialClientApp 对象,如“Microsoft Graph SDK ASPNET Connect”项目中所述,如中所述 Add sign-in with Microsoft to an ASP.NET web app

    通过代码镜像上述示例,我希望调用将返回一个成功的结果,并访问。

    var result = await cca.AcquireTokenSilentAsync(graphScopes, cca.Users.First());
    
    return result.AccessToken;
    

    然而,我得到一个错误,它说用户需要进行身份验证。我不确定我在这些例子中遗漏了什么,这些例子使我在其中发挥了作用。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Marc LaFleur    6 年前

    只有当该用户已经有一个包含您请求的作用域的缓存令牌时,您才能以静默方式获取该令牌(它可以有更多,但至少需要有您所请求的)。

    这就是为什么 AcquireTokenSilentAsync 应始终用Try/Catch块包装。如果找不到匹配的令牌,则需要启动交互式流。以下是 MSAL Wiki :

    AuthenticationResult result = null;
    try
    {
        result = await app.AcquireTokenSilentAsync(scopes, app.Users.FirstOrDefault());
    }
    catch (MsalUiRequiredException ex)
    {
        // A MsalUiRequiredException happened on AcquireTokenSilentAsync. 
        // This indicates you need to call AcquireTokenAsync to acquire a token
        System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");
    
        try
        {
            result = await app.AcquireTokenAsync(scopes);
        }
        catch (MsalException msalex)
        {
            ResultText.Text = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
        }
    }
    catch (Exception ex)
    {
        ResultText.Text = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
        return;
    }
    
    if (result != null)
    {
        string accessToken = result.AccessToken;
        // Use the token
    }