0

我目前使用我的管道中的代碼來緩存使用Azure AD的Graph API的不記名令牌。這段代碼是從正在運行的ASP.NET 4應用程序中移植過來的,但感覺像Core中新的OpenIdConnectOptions應該使這更容易。是否有一個更直接的調用,我可以在OnAuthorizationCodeReceived事件中使用,一旦接收到代碼,它將使用AuthenticationContext來緩存令牌。這裏是我當前的代碼:使用OnAuthorizationCodeReceived檢索Azure GraphAPI AccessToken

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裏面了。

有沒有一個簡單的方法,我只是俯瞰?

+0

我對語法糖做了一些修改,但主要概念保持不變。似乎是手動的一件是設置資源Uri。但是,如果我不得不爲多個資源請求令牌,那麼最好不要使用它,只需調用AccountService的靜態方法或類似的方法即可。 –

回答

0

查看完Microsoft.AspNetCore.Authentication.OpenIdConnect的代碼後,我意識到該庫與AuthenticationContext中的令牌緩存機制斷開連接。如果我嘗試簡化代碼,它不會觸發緩存機制,這意味着需要在每個請求中檢索承載令牌。

因爲我打算使用TokenCache來減少對API的調用並最終利用我的Redis緩存,所以我需要將該代碼保留在OnAuthorizationCodeReceived方法中。