4

開始玩弄AspNetCore.Identity,但不能運行簡單的例子,經常收到這樣的例外:發生谷歌認證的AspNetCore.Identity

未處理的異常處理請求。 InvalidOperationException異常:無認證處理程序被配置爲 處理方案:谷歌

Startup.cs

public void ConfigureServices(IServiceCollection services) 
    { 
     // EF services 
     services.AddEntityFramework() 
      .AddEntityFrameworkSqlServer() 
      .AddDbContext<MyContext>(); 

     // Identity services 
     services.AddIdentity<IdentityUser, IdentityRole>() 
      .AddEntityFrameworkStores<MyContext>() 
      .AddDefaultTokenProviders(); 

     // MVC services 
     services.AddMvc().AddJsonOptions(options => { 
      options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; 
      options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 
      options.SerializerSettings.Converters = new JsonConverter[] { new StringEnumConverter(), new IsoDateTimeConverter() }; 
     }); 

Configure.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 
     loggerFactory.AddConsole(); 

     if (env.IsDevelopment()) 
     { 
      app.UseDeveloperExceptionPage(); 
     } 

     app.UseIdentity(); 
     app.UseCookieAuthentication(); 
     app.UseGoogleAuthentication(new GoogleOptions() 
     { 
      ClientId = "xxx", 
      ClientSecret = "xxx", 
      AutomaticChallenge = true, 
      AutomaticAuthenticate = true 
     }); 

     app.UseMvc(routes => 
     { 
      routes.MapRoute(
       name: "default", 
       template: "{controller}/{action}/{id?}"); 
     }); 

AuthController.cs

[HttpGet] 
    [AllowAnonymous] 
    [Route("ExternalLogin", Name = "ExternalLogin")] 
    public IActionResult ExternalLogin(string provider, string returnUrl = null) 
    { 
     var redirectUrl = Url.Action("ExternalLoginCallback", "Auth", new { ReturnUrl = returnUrl }); 
     var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); 
     return new ChallengeResult(provider, properties); 
    } 

例外發生在ChallengeResult返回後。 我錯過了什麼嗎?

+0

我試過你的代碼,併成功地將它重定向到谷歌('ExternalLogin'沒有因'AutomaticChallenge = true'而被調用)。看來還有另一個問題。我懷疑Google認證後可能會發生異常。 –

回答

4

您在您的谷歌中間件上同時使用app.UseIdentity()和設置AutomaticAuthenticate = true爲true。 Identity將cookie auth設置爲AutomaticAuthenticate,並且您只能將一個身份驗證中間件設置爲automatic,否則行爲未定義。

您會在documentation中看到,當facebook連線時,它將而不是設置爲自動驗證。

+0

我會將其標記爲正確答案,謝謝。但我的問題是,在我改變它之後,我通過'google'提供者而不是[G] oogle(大寫)提供了所有建議,它開始工作:/ –