如何管理API权限? JavaScript的

时间:2017-04-26 08:16:52

标签: javascript google-api

我写了一些客户端应用并试图测试它。结果只是我可以使用它。其他人都会收到这样的错误。

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "forbidden",
    "message": "Forbidden"
   }
  ],
  "code": 403,
  "message": "Forbidden"
 }
}

这是什么意思?怎么解决这个? 有我的代码。我在那里收到电子邮件,姓名,用户照片。我想获得youtube频道订阅者的数量,以后再与youtube合作。例如,我想直接从网站上评价一些视频。

function resultFindUserByEmail()
{
  if (ajaxRet['isUserFinded'])
  {
    cf_JSON.clear();
    cf_JSON.addItem(    'email',email     );
    var jsonstr = cf_JSON.make();
    ajax_post('doyoutubelogin','loginres','index.php',jsonstr,c_dologin);
  }else{

    gapi.client.init({
      discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/people/v1/rest"],
      clientId: OAUTH2_CLIENT_ID,
      scope: OAUTH2_SCOPES
    }).then(function () {       
      var request = gapi.client.people.people.get({
      'resourceName': 'people/me'
    }).then(function(response) {

        var parsedResponse = JSON.parse(response.body).names;
        surname = parsedResponse[0].familyName;
        name = parsedResponse[0].givenName;

        photo = JSON.parse(response.body).photos[0].url; 
        addYoutubeUser();       
      });                  
    });
  }
}
function addYoutubeUser() {
    cf_JSON.clear();
    cf_JSON.addItem(        'Email',email              );
    cf_JSON.addItem(    'Firstname',name               );
    cf_JSON.addItem(     'Lastname',surname            );
    cf_JSON.addItem(        'Image',photo              );
    var jsonstr = cf_JSON.make();
    ajax_post('addyoutubeuser','loginres','index.php',jsonstr,c_dologin);
}

var API_KEY = '<Key removed for posting>'; 
var API_KEY1='<Key removed for posting>';
var OAUTH2_CLIENT_ID = '<Key removed for posting>';
var OAUTH2_CLIENT_ID1 = '<Key removed for posting>';
var OAUTH2_SCOPES = 'https://www.googleapis.com/auth/youtube.force-ssl';
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"];

  var GoogleAuth;
  function handleClientLoad() {
    // Load the API's client and auth2 modules.
    // Call the initClient function after the modules load.
    gapi.load('client:auth2', initClient);
  }

  function initClient() {
    // Retrieve the discovery document for version 3 of YouTube Data API.
    // In practice, your app can retrieve one or more discovery documents.
    var discoveryUrl = 'https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest';

    // Initialize the gapi.client object, which app uses to make API requests.
    // Get API key and client ID from API Console.
    // 'scope' field specifies space-delimited list of access scopes.  
    gapi.client.init({
        'apiKey': API_KEY,
        'discoveryDocs': [discoveryUrl,"https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"],
        'clientId': OAUTH2_CLIENT_ID,
        'scope': OAUTH2_SCOPES
    }).then(function () {      
      GoogleAuth = gapi.auth2.getAuthInstance();
      //GoogleAuth.grant(OAUTH2_SCOPES);

      // Listen for sign-in state changes.
      GoogleAuth.isSignedIn.listen(updateSigninStatus);

      // Handle initial sign-in state. (Determine if user is already signed in.)
      var user = GoogleAuth.currentUser.get();
      setSigninStatus();

      // Call handleAuthClick function when user clicks on
      //      "Sign In/Authorize" button.
      $('#sign-in-or-out-button').click(function() {
        handleAuthClick();
      }); 
      $('#revoke-access-button').click(function() {
        revokeAccess();      
      }); 
    });
  }

  function handleAuthClick() {
    if (GoogleAuth.isSignedIn.get()) {
      // User is authorized and has clicked 'Sign out' button.
      GoogleAuth.signOut();
    } else {
      // User is not signed in. Start Google auth flow.
      GoogleAuth.signIn();
    }
  }

  function revokeAccess() {
    GoogleAuth.disconnect();
  }

  function setSigninStatus(isSignedIn) {
    var user = GoogleAuth.currentUser.get();

    var isAuthorized = user.hasGrantedScopes(OAUTH2_SCOPES);
    if (isAuthorized) {
      $('#sign-in-or-out-button').html('Sign out');
      $('#revoke-access-button').css('display', 'inline-block');
      $('#auth-status').html('You are currently signed in and have granted ' +
          'access to this app.');

          //// get gmail Email
      gapi.client.init({
        'apiKey': API_KEY,
        'discoveryDocs': ["https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"],
        'clientId': OAUTH2_CLIENT_ID,
        'scope': OAUTH2_SCOPES
      }).then(function () {    
        var request = gapi.client.gmail.users.getProfile({
        'userId': 'me'
      }).then(function(response) {

          email = JSON.parse(response.body).emailAddress;

          cf_JSON.clear();
          cf_JSON.addItem(    'email',email     );
          var jsonstr = cf_JSON.make();
          tryFindUserByEmail(jsonstr);                  
        });                  
      });

      // try to find email


    } else {
      $('#sign-in-or-out-button').html('Вход через Youtube');
      $('#revoke-access-button').css('display', 'none');
      $('#auth-status').html('You have not authorized this app or you are ' +
          'signed out.');
    }
  }

  function updateSigninStatus(isSignedIn) {
    setSigninStatus();
  }

2 个答案:

答案 0 :(得分:0)

如何管理权限:

对用户进行身份验证时,您将获得对该用户帐户数据的访问权限,并且只能访问该用户。因此,如果您尝试访问其他人帐户的数据,他们将无权访问该数据,您将获得403禁止错误。

没有看到你的代码很难知道你在做什么,但我可以猜到。

  1. 您正在使用Oauth2对用户进行身份验证。
  2. 您正在尝试访问属于您的个人帐户的硬编码ID的内容,但用户无法访问该内容。
  3. 如何修复它将取决于你想要做什么。

答案 1 :(得分:0)

您需要在API网址中查看一些身份验证 用户名,ipaddress,令牌等 根据参数,您可以控制API请求的权限。例如

http://some/thing?username="testuser"&ipaddress="323.2323.232.32"

您可以使用以下功能找到参数值

function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, "\\$&");
  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, " "));
}

然后让您检查并实现特定用户的错误和重定向。

我想这对你有帮助,谢谢!