创建用户时获取403,到目前为止每一步都是如此

时间:2015-12-08 11:57:54

标签: google-admin-sdk

看起来我已经遵循了每一步(鉴于文档非常缺乏,它来自多个地方)。这是我的代码:

def create_user(cred_file_location, user_first_name, user_last_name, user_email):
    cred_data = json.loads(open(cred_file_location).read())
    access_email = cred_data['client_email']
    private_key = cred_data['private_key']

    # I have tried with the scope as a single string, and also
    # as an array of a single string. Neither worked
    credentials = SignedJwtAssertionCredentials(access_email, private_key, ["https://www.googleapis.com/auth/admin.directory.user"])

    http = Http()
    http = credentials.authorize(http)

    service = build('admin', 'directory_v1', http=http)
    users = service.users()

    userinfo = {
        'primaryEmail': user_email,
        'name': {
            'givenName': user_first_name,
            'familyName': user_last_name
        },
        'password': ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(80))
}

users.insert(body=userinfo).execute()

我正确地下载了JSON键,并正确加载它。这是我的JSON密钥(我正在编写识别信息的某些部分,我在其中保留了一些以显示我正在加载正确的信息):

{
  "type": "service_account",
  "private_key_id": "c6ae56a9cb267fe<<redacted>>",
  "private_key": "<<redacted>>",
  "client_email": "account-1@<<redacted>>.iam.gserviceaccount.com",
  "client_id": "10931536<<redacted>>",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/account-1%40<<redacted>>.iam.gserviceaccount.com"
}

以下是这些凭据在开发者控制台中的显示方式:

google developer console screenshot

我还为服务帐户启用了全站访问权限:

google admin sitewide api access

我不清楚为什么我仍然会得到这些403:

File "/usr/lib/python2.7/site-packages/googleapiclient/http.py", line 729, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/admin/directory/v1/users?alt=json returned "Not Authorized to access this resource/api">

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

最后,在一些随机的stackoverflow答案中,我找到了solutin。我必须以用户身份执行任何请求。 Esentially:

btnGallery.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {

        // Your staff

        Intent intent = new Intent();
        intent.setAction(android.content.Intent.ACTION_VIEW);

        intent.setType("*/*");
        startActivity(intent);
    }

});

更改为:

credentials = SignedJwtAssertionCredentials(
    access_email,
    private_key,
    ["https://www.googleapis.com/auth/admin.directory.user"])

现在,所有请求都将被视为代表credentials = SignedJwtAssertionCredentials( access_email, private_key, ["https://www.googleapis.com/auth/admin.directory.user"], sub="user@example.org")