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(大写)提供了所有建议,它开始工作:/ –