Google身份验证ASP.NET Core Web Api

mAr*_*ial 5 c# authentication google-oauth asp.net-identity asp.net-core

我在Google重定向到回调方法时遇到一些问题,它引发异常:oauth状态丢失或无效。

启动文件

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<Conte>(config =>
            config.UseSqlServer(Configuration.GetConnectionString("Identity")));
        services.AddIdentity<IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores<Conte>()
            .AddDefaultTokenProviders();

        services.AddAuthentication()
                .AddCookie("Cook")
                .AddGoogle(config =>
                {
                    config.SignInScheme = "Cook";
                    config.ClientId = Configuration["Authentication:Google:Client_Id"];
                    config.ClientSecret = Configuration["Authentication:Google:Client_Secret"];

                    config.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "UserId");
                    config.ClaimActions.MapJsonKey(ClaimTypes.Email, "EmailAddress", ClaimValueTypes.Email);
                    config.ClaimActions.MapJsonKey(ClaimTypes.Name, "Name");

                });

                    services.AddMvc();
    }
Run Code Online (Sandbox Code Playgroud)

AccountController.cs

[AllowAnonymous]
    [HttpGet]
    [Route("/api/google-login")]
    public async Task LoginGoogle()
    {
        await HttpContext.ChallengeAsync("Google", new AuthenticationProperties() { RedirectUri = "/signin-google" });
    }

    [AllowAnonymous]
    [HttpGet]
    [Route("/signin-google")]
    public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
    {   
        var info = await _signInManager.GetExternalLoginInfoAsync();

        // Sign in the user with this external login provider if the user already has a login.
        var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
        if (result.Succeeded)
        {
            return Redirect(returnUrl);
        }
        return BadRequest();
    }
Run Code Online (Sandbox Code Playgroud)

转到 Google帐户

当我试图授权时,会抛出异常

d_f*_*d_f 7

根据MS的教程

本教程后面配置的 Google 身份验证将自动处理 /signin-google 路由中的请求以实现 OAuth 流程。

/signin-google 路由由中间件处理,而不是由您的 MVC 控制器处理。您的外部登录应路由到类似 /ExternalLoginCallback 的内容