Google OAuth问题

时间:2017-05-22 16:48:09

标签: umbraco oauth2-playground

我有一个Umbraco网站,其谷歌登录按钮配置如下:

在页面顶部(标题部分内)我有调用google API的脚本:

<script src="https://apis.google.com/js/client:platform.js?onload=start" async defer></script>
<script>
        function start() {
          gapi.load('auth2', function() {
            auth2 = gapi.auth2.init({
              client_id: '<myapp client Id>.apps.googleusercontent.com',
              // Scopes to request in addition to 'profile' and 'email'
              redirect_uri: 'http://localhost:40136/umbraco/Surface/AuthSurface/GoogleAuthrizedUser',
              scope: 'profile email'
            });
          });
        } 
 </script>

在代码的正文部分,我有谷歌按钮设置和相关的点击功能:

<script>
 function onSignIn(authResult) {
    if (authResult['code']) {
      var authCode = authResult['code'];
      console.log("Authorization Code: " + authCode);
      $.post("/umbraco/Surface/AuthSurface/GoogleAuthrizedUser", { code: authCode })
        .done(function(msg) {
            // Success settings
         })
        .fail(function(xhr, status, error) {

        });
    } else {
       //authResult['code'] is null
       //handle the error message.
    }
  };
 </script>

处理服务器端回调的控制器代码:

  public class AuthSurfaceController : SurfaceController
  {
       public ActionResult GoogleAuthrizedUser()
      {
        string AuthCode = HttpContext.Request["code"];
        var info = new GoogleAccessTokenResponse();
        var client = new GoogleOAuthClient();
        try
        {
          info = client.GetAccessTokenFromAuthorizationCode(AuthCode);
        }
        catch (Exception ex)
        {
          var strMessage = String.Format("<div class=\"info\"><p>{0}</p><p>{1}</p></div>", "Google Login Error",
          ex.Message);
         return Json(new AjaxOperationResponse(false, strMessage));
        }
     }
 }

在Serverside上我使用Skybrud Social插件访问谷歌apis。

google身份验证在弹出窗口中发生,并使用凭据授权客户端, authResult ['code'] 具有有效代码。

在初始化客户端并调用函数 GetAccessTokenFromAuthorizationCode(AuthCode)时,在控制器中,它返回“无效请求”的异常

我尝试检查https://developers.google.com/oauthplayground/

中的javascript函数onSignIn中返回的 authResult ['code']

相同的错误说明显示为“无效的请求”。我不确定为什么会这样。返回的错误是“invalid_grant”

任何人都可以解决这个问题吗?我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

在表面控制器中,您正在初始化GoogleOAuthClient的新实例,但不设置任何属性。 GetAccessTokenFromAuthorizationCode方法要求ClientIdClientSecretRedirectUri属性具有值。您可以像这样初始化属性:

// Initialize a new instance of the OAuth client
GoogleOAuthClient oauth = new GoogleOAuthClient {
    ClientId = "The client ID of your project",
    ClientSecret = "The client secret of your project",
    RedirectUri = "The return URI (where users should be redirected after the login)"
};

您可以在文档中阅读有关身份验证的更多信息:http://social.skybrud.dk/google/authentication/(解释的方法不会使用任何JavaScript)