【问题标题】:Using OnAuthorizationCodeReceived to retrieve Azure GraphAPI AccessToken使用 OnAuthorizationCodeReceived 检索 Azure GraphAPI AccessToken
【发布时间】:2017-09-24 11:22:39
【问题描述】:

我目前正在我的管道中使用代码来缓存使用 Azure AD 的 Graph API 的不记名令牌。这段代码是从一个正常工作的 ASP.NET 4 应用程序中移植过来的,但感觉 Core 中的新 OpenIdConnectOptions 应该会使这更容易。是否可以在 OnAuthorizationCodeReceived 事件中使用更直接的调用,一旦收到代码,它将使用 AuthenticationContext 缓存令牌?这是我当前的代码:

var azureSettings = app.ApplicationServices.GetService<IOptions<AzureSettings>>().Value;
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
    ClientId = azureSettings.ClientId,
    ClientSecret = azureSettings.AppKey,
    Authority = string.Format(azureSettings.AadInstance, azureSettings.TenantId),
    Resource = azureSettings.GraphResourceUri,
    ResponseType = OpenIdConnectResponseType.CodeIdToken,
    TokenValidationParameters = new TokenValidationParameters
    {
        RoleClaimType = "roles"
    },
    Events = new OpenIdConnectEvents()
    {
        OnAuthorizationCodeReceived = (context) =>
        {
            string resourceUri = azureSettings.GraphResourceUri;
            var authContext = new AuthenticationContext(context.Options.Authority);
            var credential = new ClientCredential(context.TokenEndpointRequest.ClientId, context.TokenEndpointRequest.ClientSecret);
            var result = authContext.AcquireTokenByAuthorizationCodeAsync(context.TokenEndpointRequest.Code, new Uri(context.TokenEndpointRequest.RedirectUri), credential, resourceUri);

            context.HandleCodeRedemption(result.AccessToken, result.IdToken);
        }
    }
});

上面的代码工作得很好,但感觉就像我复制了很多代码只是为了提交大部分包含在 AuthorizationCodeReceivedContext 中的内容。

有没有更简单的方法可以让我忽略?

【问题讨论】:

  • 我对语法糖做了一些更改,但主要概念保持不变。似乎是手动的一件是设置资源 Uri。但是,如果我必须为多个资源请求令牌,最好保持原样,只需调用 AccountService 的静态方法或类似的方法。

标签: c# asp.net-core-mvc azure-active-directory openid-connect


【解决方案1】:

查看 Microsoft.AspNetCore.Authentication.OpenIdConnect 的代码后,我意识到这个库与 AuthenticationContext 中的令牌缓存机制断开了连接。如果我尝试简化代码,它不会触发缓存机制,这意味着需要在每次请求时检索 Bearer 令牌。

因为我计划使用 TokenCache 来减少对 API 的调用并最终利用我的 Redis 缓存,所以我需要将该代码留在 OnAuthorizationCodeReceived 方法中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-03
    • 2017-02-01
    • 2019-02-07
    相关资源
    最近更新 更多