会社のディレクトリで認証するためにAzureAdを使用するASP.NET Core 2.0アプリケーションの設定があります。私は、クラスとスタートアップメソッドをセットアップし、認証ピースが動作している、私が持っている問題は、私がOnAuthorizationCodeReceivedイベントへのセットアップとイベントハンドラをしようとしているので、 Microsoftグラフ呼び出しに使用されます。ASP.NET Core 2.0 AzureAD認証が機能しない
私は、次のコードを持っているAzureAdAuthenticationBuilderExtensions.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?}");
});
}
を持っている私のStartup.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()
:「id_token」を検証できません、もし適切なISecurityTokenValidatorはなかったと我々は以下のコードのような
OpenIdConnectOptions
を通してそれを設定する必要があります''のために見つかりました: ''。 –@PaulCavacas 'OnAuthorizationCodeReceived'で' context.HandleCodeRedemption() 'メソッドを呼び出すには、id_tokenが必要です。あるいは、id_tokenとaccess_tokenの両方を提供できます。それが助けになるかどうか私に教えてください。 –