Azure AD和OAUTH资源

时间:2018-12-03 15:37:19

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

我正在编写一个需要同时访问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);
    }
}

1 个答案:

答案 0 :(得分: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));

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