谷歌身份验证 ASP.NET Core Web Api

7

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

Startup.cs

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();
    }

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();
    }

它跳转到Google账户

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

1个回答

7
根据 MS 的 教程,其中指出:

在本教程中稍后配置的 Google 认证将自动处理 /signin-google 路由上的请求来实现 OAuth 流程。

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

这确实是一个问题。谢谢,但无论如何_signInManager.GetExternalLoginInfoAsync();总是返回null。 - mArial
很难在没有额外信息的情况下说出什么。尝试使用开发控制台检查您的流量。直接尝试调用并查看HttpContext?.Request?.Cookies?.Select(x => $"{x.Key}:{x.Value};");。 - d_f

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