试图逆向工程此示例app。只有我没有创建自己的服务,只是试图使用Microsoft Graph API获取我的个人资料信息。获取以下错误:AdalSilentTokenAcquisitionException:由于在缓存中找不到令牌,因此无法默认获取令牌。调用方法AcquireToken
AdalSilentTokenAcquisitionException:无法默认获取令牌,因为在缓存中找不到令牌。调用方法AcquireToken
我很新,但我已经通过了所有与该错误相关的stackoverflow问题,一直没能弄明白。
我正在使用Asp.net核心最新版本。 AcquireTokenSilentAsync上面的错误我总是失败。任何提示或想法都会有所帮助。
以下是我到目前为止。
Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseApplicationInsightsExceptionTelemetry();
app.UseStaticFiles();
app.UseSession();
//app.UseCookieAuthentication();
// Populate AzureAd Configuration Values
Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"];
ClientId = Configuration["Authentication:AzureAd:ClientId"];
ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"];
GraphResourceId = Configuration["Authentication:AzureAd:GraphResourceId"];
GraphEndpointId = Configuration["Authentication:AzureAd:GraphEndpointId"];
// Configure the OWIN pipeline to use cookie auth.
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
ClientId = ClientId,
ClientSecret = ClientSecret,
Authority = Authority,
CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"],
ResponseType = OpenIdConnectResponseType.CodeIdToken,
GetClaimsFromUserInfoEndpoint = false,
Events = new OpenIdConnectEvents
{
OnRemoteFailure = OnAuthenticationFailed,
OnAuthorizationCodeReceived = OnAuthorizationCodeReceived,
}
});
OnAuthorizationCodeReceived:
private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
{
// Acquire a Token for the Graph API and cache it using ADAL. In the TodoListController, we'll use the cache to acquire a token to the Todo List API
string userObjectId = (context.Ticket.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
ClientCredential clientCred = new ClientCredential(ClientId, ClientSecret);
AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectId, context.HttpContext.Session));
AuthenticationResult authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
context.ProtocolMessage.Code, new Uri(context.Properties.Items[OpenIdConnectDefaults.RedirectUriForCodePropertiesKey]), clientCred, GraphResourceId);
// Notify the OIDC middleware that we already took care of code redemption.
context.HandleCodeRedemption();
}
MyProfileController:
public async Task<IActionResult> Index()
{
AuthenticationResult result = null;
var user = new ADUser();
try
{
string userObjectID = (User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID, HttpContext.Session));
ClientCredential credential = new ClientCredential(Startup.ClientId, Startup.ClientSecret);
var tc = authContext.TokenCache.ReadItems();
result = await authContext.AcquireTokenSilentAsync(Startup.GraphResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.RequiredDisplayableId));
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
String responseString = await response.Content.ReadAsStringAsync();
List<Dictionary<String, String>> responseElements = new List<Dictionary<String, String>>();
}
}
catch (Exception)
{
throw;
}
return View();
}
谢谢你回到我身边。我试过了,但它仍然无法工作。然而,我注意到,如果我在这一行上放置一个断点:result = await authContext.AcquireTokenSilentAsync(Startup.GraphResourceId,credential,new UserIdentifier(userObjectID,UserIdentifierType.UniqueId));然后等待几分钟,代码将继续执行错误。 –
您是否可以使用ADAL日志和/或网络跟踪来更新问题?从ADAL收集日志的临时说明在这里:https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/issues/527。重要的网络跟踪将是login.microsoftonline.com的任何会话 – dstrockis