首页 > 解决方案 > 如何处理 Google OAuth2 身份验证中的授权错误?

问题描述

我需要一些帮助来处理 Google 身份验证错误。

我按照本教程将 Google 身份验证集成到我的 ASP.NET MVC 5 Web 应用程序中。我将应用程序类型限制为内部使用,因此只有同事可以使用他们的工作帐户登录(我们在 GMail 中有我们公司的电子邮件)并且一切正常,只要我使用我的工作帐户登录。

当我尝试使用其他(非公司)帐户登录时,如预期的那样,我收到了授权错误。我的问题是错误是来自 Google 的页面,并且我的应用程序没有回调。

我已经在互联网上搜索了很长一段时间,但我似乎无法找到如何设置我的应用程序,以便在授权错误时获得回调。我开始怀疑这是否可能......

有人可以帮我解决这个问题吗?我不确定它是否相关,但这是我的 Startup.Auth.cs 中的 ConfigureAuth 类。

public void ConfigureAuth(IAppBuilder app)
{
    app.CreatePerOwinContext(ApplicationDbContext.Create);
    app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
    app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Account/Login"),
        Provider = new CookieAuthenticationProvider
        {
            OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                validateInterval: TimeSpan.FromMinutes(30),
                regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
        }
    });
    app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
    app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
    app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

    GoogleOAuth2AuthenticationOptions _options = new GoogleOAuth2AuthenticationOptions()
    {
        ClientId = "clientId.apps.googleusercontent.com",
        ClientSecret = "clientSecret"
    };

    _options.Scope.Add("profile");
    _options.Scope.Add("email");
    _options.CallbackPath = new PathString("/Account/LoginResult");
    _options.Provider = new GoogleOAuth2AuthenticationProvider()
    {
        OnAuthenticated = async context =>
        {
            string claimType;
            bool bAddClaim = false;
            foreach (var claim in context.User)
            {
                claimType = string.Empty;
                bAddClaim = false;
                switch (claim.Key)
                {
                    case "picture":
                        claimType = "Picture";
                        bAddClaim = true;
                        break;
                }
                if (bAddClaim)
                {
                    string claimValue = claim.Value.ToString();
                    if (!context.Identity.HasClaim(claimType, claimValue))
                        context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Google"));
                }
            }
        }
    };

    app.UseGoogleAuthentication(_options);
}

我不知道其他什么代码是相关的,所以请询问您是否遗漏了什么。

提前致谢!

标签: c#error-handlingasp.net-mvc-5authorizationgoogle-oauth

解决方案


推荐阅读