【问题标题】:Azure AD and OAUTH resourcesAzure AD 和 OAUTH 资源
【发布时间】:2018-12-03 15:37:19
【问题描述】:

我正在编写一个需要同时访问 PowerBI 和 Microsoft Graph 的 Web 应用程序。我是 OAUTH 的新手,所以我不明白如何请求访问两种不同的资源。这是我访问一个(PowerBI)资源的代码。如何修改它以同时访问 Microsoft Graph?

class ConfigureAzureOptions : IConfigureNamedOptions<OpenIdConnectOptions>
{
    private readonly PowerBiOptions _powerBiOptions;
    private readonly IDistributedCache _distributedCache;
    private readonly AzureADOptions _azureOptions;

    public ConfigureAzureOptions(IOptions<AzureADOptions> azureOptions, IOptions<PowerBiOptions> powerBiOptions, IDistributedCache distributedCache)
    {
        _azureOptions = azureOptions.Value;
        _powerBiOptions = powerBiOptions.Value;
        _distributedCache = distributedCache;
    }

    public void Configure(string name, OpenIdConnectOptions options)
    {
        options.ClientId = _azureOptions.ClientId;
        options.Authority = _azureOptions.Instance + "/" + _azureOptions.TenantId;
        options.UseTokenLifetime = true;
        options.CallbackPath = _azureOptions.CallbackPath;
        options.RequireHttpsMetadata = false;
        options.ClientSecret = _azureOptions.ClientSecret;
        options.Resource = _powerBiOptions.Resource;
        // Without overriding the response type (which by default is id_token), the OnAuthorizationCodeReceived event is not called.
        // but instead OnTokenValidated event is called. Here we request both so that OnTokenValidated is called first which 
        // ensures that context.Principal has a non-null value when OnAuthorizeationCodeReceived is called
        options.ResponseType = "id_token code";

        options.Events.OnAuthorizationCodeReceived = OnAuthorizationCodeReceived;
        options.Events.OnAuthenticationFailed = OnAuthenticationFailed;
    }

    public void Configure(OpenIdConnectOptions options)
    {
        Configure(Options.DefaultName, options);
    }

    private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
    {
        string userObjectId = context.Principal.FindFirst(AccessTokenProvider.Identifier)?.Value;
        var authContext = new AuthenticationContext(context.Options.Authority, new DistributedTokenCache(_distributedCache, userObjectId));
        var credential = new ClientCredential(context.Options.ClientId, context.Options.ClientSecret);

        var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(context.TokenEndpointRequest.Code,
            new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute), credential, context.Options.Resource);

        context.HandleCodeRedemption(authResult.AccessToken, context.ProtocolMessage.IdToken);
    }

    private Task OnAuthenticationFailed(AuthenticationFailedContext context)
    {
        context.HandleResponse();
        context.Response.Redirect("/Home/Error?message=" + context.Exception.Message);
        return Task.FromResult(0);
    }
}

【问题讨论】:

    标签: asp.net-core oauth-2.0 azure-active-directory


    【解决方案1】:

    您不需要在第一次登录过程中获取不同资源的每个访问令牌。

    假设您第一次在OnAuthorizationCodeReceived函数中获取PowerBI的访问令牌,在控制器中,当然您可以直接使用该访问令牌来调用PowerBI的API,因为令牌是缓存的。现在您需要调用 Microsoft Graph,只需尝试以下代码:

    string userObjectID = (User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
    
    // Using ADAL.Net, get a bearer token to access the TodoListService
    AuthenticationContext authContext = new AuthenticationContext(AzureAdOptions.Settings.Authority, new NaiveSessionCache(userObjectID, HttpContext.Session));
    ClientCredential credential = new ClientCredential(AzureAdOptions.Settings.ClientId, AzureAdOptions.Settings.ClientSecret);
    result = await authContext.AcquireTokenSilentAsync("https://graph.microsoft.com", credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
    

    只需设置AcquireTokenSilentAsync函数的resource参数,它将使用刷新令牌获取新资源的访问令牌。

    【讨论】:

    • 谢谢。我从没想过我可以多次获得令牌。
    猜你喜欢
    • 1970-01-01
    • 2020-07-26
    • 2022-08-05
    • 2019-02-19
    • 2023-03-25
    • 2018-06-03
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多