用于Google OAuth的ExternalLogin .net API的奇怪循环

时间:2017-07-29 05:32:17

标签: c# .net google-oauth

我从youtube视频获得了有关如何为.net项目创建Google身份验证的帮助。 Here is his videoand his documentation

我遵循了每一步,但我仍然遇到同样的问题。出于某种原因,AccountController中的ExternalLogin保持循环,当我登录Google时,Chrome告诉我

  

accounts.google.com重定向了你太多次了。

我的代码目前如何运作:

  1. 点击“使用Google登录”
  2. 重定向到Google以获取电子邮件和密码
  3. 输入电子邮件和密码,然后单击登录
  4. ExternalLogin开始循环,Chrome称accounts.google.com重定向次数太多
  5. 我怀疑未生成访问令牌,因为在GoogleAuthentication中的getAccessToken()上,我试图打印出访问令牌,但没有打印任何内容

    这是我在ExternalLogin上的代码

       // GET api/Account/ExternalLogin
            [OverrideAuthentication]
            [HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)]
            [AllowAnonymous]
            [Route("ExternalLogin", Name = "ExternalLogin")]
            public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null)
            {
                if (error != null)
                {
                    return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error));
                }
    
                if (!User.Identity.IsAuthenticated)
                {
                    return new ChallengeResult(provider, this);
                }
    
                ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
    
                if (externalLogin == null)
                {
                    return InternalServerError();
                }
    
                if (externalLogin.LoginProvider != provider)
                {
                    Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                    return new ChallengeResult(provider, this);
                }
    
                ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
                    externalLogin.ProviderKey));
    
                bool hasRegistered = user != null;
    
                if (hasRegistered)
                {
                    Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    
                     ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                        OAuthDefaults.AuthenticationType);
                    ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                        CookieAuthenticationDefaults.AuthenticationType);
    
                    AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                    Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
                }
                else
                {
                    IEnumerable<Claim> claims = externalLogin.GetClaims();
                    ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
                    Authentication.SignIn(identity);
                }
    
                return Ok();
            }
    

    Login.html代码

    <script src="Scripts/jquery-1.10.2.js"></script>
    <script src="Scripts/GoogleAuthentication.js"></script>
    <script>
    $(document).ready(function () {
        getAccessToken();
        $('#btnGoogleLogin').click(function () {
    
            window.location.href = "/api/Account/ExternalLogin?provider=Google&response_type=token&client_id=self&redirect_uri=https%3A%2F%2Flocalhost%3A44345%2FLogin.html&state=TQ9c4kctEKiEhf-2Uis05MLNPgKzzivmdKIwbQhnkrA1";
    
        });
    

    GoogleAuthenticaion.js代码

    function getAccessToken() {
    
        if (location.hash) {
            if (location.hash.split('access_token=')) {
                var accessToken = location.hash.split('access_token=')[1].split('&')[0];
                alert(accessToken);
                if (accessToken) {
                    isUserRegistered(accessToken);
                }
            }
        }
    }
    function isUserRegistered(accessToken) {
        $.ajax({
            url: '/api/Account/UserInfo',
            method: 'GET',
            headers: {
                'content-type': 'application/JSON',
                'Authorization': 'Bearer ' + accessToken
            },
            success: function (response) {
                if (response.HasRegistered) {
                    localStorage.setItem('accessToken', accessToken);
                    localStorage.setItem('userName', response.Email);
                    window.location.href = "Index.html";
                }
                else {
                    signupExternalUser(accessToken);
                }
            }
        });
    }
    function signupExternalUser(accessToken) {
        $.ajax({
            url: '/api/Account/RegisterExternal',
            method: 'POST',
            headers: {
                'content-type': 'application/json',
                'Authorization': 'Bearer ' + accessToken
            },
            success: function () {
                window.location.href = "/api/Account/ExternalLogin?provider=Google&response_type=token&client_id=self&redirect_uri=https%3A%2F%2Flocalhost%3A44345%2FLogin.html&state=T7-tOpA7ERNeeLE8M4CHlZEubafM-I--np0ErWE372w1";
            }
        });
    
    }
    

0 个答案:

没有答案