簡體   English   中英

Azure AD和OAUTH資源

[英]Azure AD and OAUTH resources

我正在編寫一個需要同時訪問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);
    }
}

您無需在首次登錄過程中就獲得針對不同資源的每個訪問令牌。

假設您是第一次在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參數,它將使用刷新令牌來獲取新資源的訪問令牌。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM