【问题标题】:Google oauth with angularjs带有 angularjs 的谷歌 oauth
【发布时间】:2014-08-23 11:00:08
【问题描述】:

我正在尝试在 angularjs 中实现 Google Oauth。下面是创建谷歌登录按钮的代码和回调函数。

  // Google sign in intialization function
  <script type="text/javascript">
    a = function() {
     var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
     po.src = 'https://apis.google.com/js/client:plusone.js';
     var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
   };
  </script>

  // Callback function after signin
  <script type="text/javascript">
    var access_token = ''
    function signinCallback(authResult) {
      console.log(authResult)
      if (authResult['status']['signed_in']) {
        access_token = authResult['access_token']
        if (window.location.pathname != "/album")
          window.location = "/#/albums";
        document.getElementById('signinButton').setAttribute('style', 'display: none');
      } else {
        console.log('Sign-in state: ' + authResult['error']);
      }
    }  
  </script>    

上述代码在每次页面加载时执行。它将从 Google 收到的访问令牌存储在名为 access_token 的变量中。我有一个角度服务,它使用这个 access_token 来调用 Google api。这是代码-

picasaServices.factory('Phone', ['$resource',
  function($resource){
    return $resource('https://picasaweb.google.com/data/feed/api/user/default', {}, {
      query: {method: 'GET', params:{alt: 'json', access_token: access_token}, isArray: false}
    });
  }
]);

问题是,当 Google 将访问令牌返回给我时,访问令牌 Angular 服务会使用 nil access_token 自行执行。我该如何解决这个问题。如果我的整个方法有缺陷,我也想。

【问题讨论】:

    标签: javascript angularjs oauth-2.0 google-oauth


    【解决方案1】:

    没有简单的答案。您需要处理在 Angular 初始化之前您的身份验证成功的可能性,以及相反(更有可能)的可能性。

    您可以采取多种方法。需要考虑的一件事是,如果您尝试在没有访问令牌的情况下调用 Google API,您将收到 401 错误。 401 也可能在令牌过期一小时后自然发生。因此,无论如何您都需要为 401 响应编写代码,因此您可以在令牌准备好之前使用相同的逻辑来处理 AngularJS 的初始化。需要注意的一个问题是不要多次调用 auth。

    希望 Google 中的某个人正在为 JS 库创建一个 AngularJS 友好的包装器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-06
      • 2014-07-11
      • 2016-08-04
      • 2015-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-20
      相关资源
      最近更新 更多