Google身份验证ASP.NET核心Web Api

时间:2018-06-08 14:26:20

标签: c# authentication asp.net-core asp.net-identity google-oauth

当谷歌重定向到它抛出的回调方法时,我遇到了一些问题Exception: The oauth state was missing or invalid.

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 Account

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

1 个答案:

答案 0 :(得分:1)

根据MS的tutorial

  

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

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

之类的东西