Вопрос получения ошибки 401 в API состояния отчета - PullRequest
0 голосов
/ 07 апреля 2020

Я занимаюсь разработкой сервиса умного дома Google. И я хочу использовать API «Состояние отчета» (https://developers.google.com/assistant/smarthome/develop/report-state), но в ответ я всегда получаю ошибку аутентификации 401.

Мой шаг следующий,

  1. Я скачал json файл (key_file.json), и я использую закрытый ключ в этом файле.
  2. Я использую google auth для jwt, мой источник googleapi.py от используя python 3.6.
  3. Я получаю jwt_key и вызываю состояние отчета api, используя jwt_key.
  4. Ответ 401.

Я не знаю, в чем дело. Не могли бы вы быстро проверить мою проблему?

  1. googleapi.py
# -*- coding: utf-8 -*-

import requests
import time
import json
import google.auth.crypt as crypt
import google.auth.jwt as jwt

def generate_jwt():
    """Generates a signed JSON Web Token using a Google API Service Account."""
    now = int(time.time())

    keyfile_path = '.\key_file.json'
    with open(keyfile_path, 'r') as keyfileData:
        data = keyfileData.read()

    keyfile = json.loads(data)

    sa_key = str(keyfile['private_key'])

    #build payload
    header = {
        "typ": "JWT",
        "alg": "RS256"
    }
    payload = {
        'iss': 'project_abc@appspot.gserviceaccount.com',
        'scope' : 'https://www.googleapis.com/auth/homegraph',
        'aud' : 'https://accounts.google.com/o/oauth2/token',
        'iat' : now,
        'exp' : now + 3600
    }

    signer = crypt.RSASigner.from_string(sa_key)
    jwt_key = jwt.encode(signer, header=header, payload=payload)

    print(jwt_key)

    return jwt_key

def make_jwt_request(signed_jwt, url, body):
    """Makes an authorized request to the endpoint"""
    headers = {
        'Authorization': 'Bearer {}'.format(signed_jwt.decode('utf-8')),
        'X-GFE-SSL': 'yes',
        'content-type': 'application/json'
    }

    body = json.dumps(body).encode('utf-8')
    print(url, headers, body)
    response = requests.post(url, headers=headers, data=body)

    return response

if __name__ == "__main__":
    url = 'https://homegraph.googleapis.com/v1/devices:reportStateAndNotification'
    body = {
        "requestId": "ABC-123",
        "agentUserId": "ABC-123",
        "payload": {
            "devices": {
                "states": {
                    }
                }
            }
        }
    }
    response = make_jwt_request(generate_jwt(), url, body)
    print(response)
...