我有一个ASP.NET Core 2.0应用程序设置,我想使用AzureAd与我公司的目录进行身份验证。我已经设置了类和启动方法,并使验证块工作,我遇到的问题是我正在尝试设置OnAuthorizationCodeReceived事件的事件处理程序,以便我可以请求一个用户令牌,然后用于Microsoft图形调用。ASP.NET Core 2.0 AzureAD身份验证不起作用
在我Startup.cs我有以下代码
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddAzureAd(options => Configuration.Bind("AzureAd", options))
.AddCookie();
services.AddMvc();
services.AddSingleton(Configuration);
services.AddSingleton<IGraphAuthProvider, GraphAuthProvider>();
services.AddTransient<IGraphSDKHelper, GraphSDKHelper>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
在我有以下代码AzureAdAuthenticationBuilderExtensions.cs
然后。
public static class AzureAdAuthenticationBuilderExtensions
{
public static AuthenticationBuilder AddAzureAd(this AuthenticationBuilder builder, IConfiguration configuration)
=> builder.AddAzureAd(_ => { }, configuration);
public static AuthenticationBuilder AddAzureAd(this AuthenticationBuilder builder, Action<AzureAdOptions> configureOptions,
IConfiguration configuration)
{
builder.Services.Configure(configureOptions);
builder.Services.AddSingleton<IConfigureOptions<OpenIdConnectOptions>, ConfigureAzureOptions>();
builder.AddOpenIdConnect(opts =>
{
opts.ResponseType = "code id_token";
opts.ClientId = configuration["AzureAd:ClientId"];
opts.Authority = $"{configuration["AzureAd:Instance"]}{configuration["AzureAd:TenantId"]}";
opts.UseTokenLifetime = true;
opts.CallbackPath = configuration["AzureAd:CallbackPath"];
opts.ClientSecret = configuration["AzureAd:ClientSecret"];
opts.RequireHttpsMetadata = false;
opts.Events = new OpenIdConnectEvents
{
OnAuthorizationCodeReceived = async context =>
{
var credential = new ClientCredential(context.Options.ClientId, context.Options.ClientSecret);
var distributedCache = context.HttpContext.RequestServices.GetRequiredService<IDistributedCache>();
var userId = context.Principal
.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier")
.Value;
var cache = new AdalDistributedTokenCache(distributedCache, userId);
var authContext = new AuthenticationContext(context.Options.Authority, cache);
await authContext.AcquireTokenByAuthorizationCodeAsync(context.TokenEndpointRequest.Code,
new Uri(context.TokenEndpointRequest.RedirectUri, UriKind.RelativeOrAbsolute), credential, context.Options.Resource);
context.HandleCodeRedemption();
}
};
});
return builder;
}
private class ConfigureAzureOptions: IConfigureNamedOptions<OpenIdConnectOptions>
{
private readonly AzureAdOptions _azureOptions;
public ConfigureAzureOptions(IOptions<AzureAdOptions> azureOptions)
{
if (azureOptions != null)
{
_azureOptions = azureOptions.Value;
}
}
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;
}
public void Configure(OpenIdConnectOptions options)
{
Configure(Options.DefaultName, options);
}
}
}
然后AddAzureAd方法被调用,我可以看到它穿行都在这个方法的代码,但是当我把一个断点在OnAuthorizationCodeReceived方法断点从来没有被击中。我已经完成了一堆阅读,看起来我所拥有的是正确的,所以我猜测我必须在这里错过简单的东西,但找不到问题。
Editted 现在我打了OnAuthorizationCodeReceived事件,但现在,应用程序无法继续登录收到以下错误
SecurityTokenException: Unable to validate the 'id_token', no suitable ISecurityTokenValidator was found for: ''."
Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+<HandleRequestAsync>d__12.MoveNext()
Stack Query Cookies Headers
SecurityTokenException: Unable to validate the 'id_token', no suitable ISecurityTokenValidator was found for: ''."
Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler+<HandleRequestAsync>d__12.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+<Invoke>d__6.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+<Invoke>d__7.MoveNext()
我更新了新的AddAzureAd方法和我现在得到的错误,问题是SecurityTokenException:无法验证“id_token”,没有合适的ISecurityTokenValidator是找到:''。“ –
@PaulCavacas要调用'OnAuthorizationCodeReceived'中的'context.HandleCodeRedemption()'方法,需要id_token。或者我们都可以提供id_token和access_token。我已经更新了帖子中的代码,请让我帮忙。 –