2017-08-30 14 views
1

会社のディレクトリで認証するために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() 

答えて

1

Asp.netコアのOpenIdConnectコンポーネントは、2.0は、暗黙的な使用しています(response_typeの値はid_tokenです)。

OnAuthorizationCodeReceivedのイベントを発生させるには、 'response_type'パラメータの値がcodeのハイブリッドフローを使用する必要があります(例:id_token code)。私は新しいAddAzureAd方法で質問を更新し、私は今取得していますエラーがSecurityTokenExceptionある

.AddOpenIdConnect(options => 
{ 
    options.Authority = String.Format(Configuration["AzureAd:AadInstance"], Configuration["AzureAd:Tenant"]); 
    options.ClientId = Configuration["AzureAd:ClientId"]; 
    options.ResponseType = "code id_token";  
}); 

options.Events = new OpenIdConnectEvents 
{ 
    OnAuthorizationCodeReceived = async context => 
    { 
     var credential = new ClientCredential(context.Options.ClientId, context.Options.ClientSecret); 

     var authContext = new AuthenticationContext(context.Options.Authority); 
     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); 
    }, 
}; 
+0

:「id_token」を検証できません、もし適切なISecurityTokenValidatorはなかったと我々は以下のコードのようなOpenIdConnectOptionsを通してそれを設定する必要があります''のために見つかりました: ''。 –

+0

@PaulCavacas 'OnAuthorizationCodeReceived'で' context.HandleCodeRedemption() 'メソッドを呼び出すには、id_tokenが必要です。あるいは、id_tokenとaccess_tokenの両方を提供できます。それが助けになるかどうか私に教えてください。 –

関連する問題