ASP.NET Core身份验证中的谷歌身份验证

4

我开始尝试使用AspNetCore.Identity,但无法运行简单示例,总是收到如下异常:

在处理请求时发生了未处理的异常。 InvalidOperationException:没有配置认证处理程序来处理方案:google

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后发生了异常。 我错过了什么吗?


我尝试了你的代码,成功地被重定向到了谷歌(ExternalLogin没有被调用,因为AutomaticChallenge = true)。看起来还有另一个问题。我怀疑异常可能发生在谷歌认证之后。 - adem caglin
1个回答

4
您正在同时使用app.UseIdentity()和将AutomaticAuthenticate = true设置为True的Google中间件,但是Identity会将cookie auth设置为AutomaticAuthenticate。您只能设置一个身份验证中间件自动设置,否则行为就不确定了。
文档中,当Facebook被连接时,它被设置为自动验证。

我会把它标记为正确答案,谢谢。但是我的问题是,在您提出所有建议后,我通过了“google”提供程序,而不是[G]oogle(大写),在我更改之后,它开始工作 :/ - Jevgenij Nekrasov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接