python-3.x Google Oath2库在调用flow.InstalledAppFlow.from_client_secrets_file()时引发CSRF警告

ulydmbyx  于 2023-11-20  发布在  Python
关注(0)|答案(1)|浏览(126)

我有以下Python代码:

scopes = ['https://www.googleapis.com/auth/drive',
          'https://www.googleapis.com/auth/spreadsheets',
          'https://www.googleapis.com/auth/gmail.compose']

appflow = flow.InstalledAppFlow.from_client_secrets_file(
            "client_secret.json", scopes=scopes
        )

appflow.run_local_server()

credentials = appflow.credentials

return credentials

字符串
一切似乎都很好,它打开了一个Web浏览器选项卡并请求用户授权,但是,当返回到脚本时,它引发了这个错误:

test_pytest.py:34: in <module>
    HF_CALC = Calculator(SHEET_URLS)
app\helpers\hf_calculations.py:24: in __init__
    self.gspread_accessor = GspreadAccessor()
app\helpers\utilities.py:547: in __init__
    self.google_sheets = self.authorize_google_sheets()
app\helpers\utilities.py:552: in authorize_google_sheets
    credentials = get_credentials()
app\helpers\utilities.py:84: in get_credentials
    appflow.run_local_server()
appvenv\lib\site-packages\google_auth_oauthlib\flow.py:480: in run_local_server
    self.fetch_token(authorization_response=authorization_response)
appvenv\lib\site-packages\google_auth_oauthlib\flow.py:288: in fetch_token
    return self.oauth2session.fetch_token(self.client_config["token_uri"], **kwargs)
appvenv\lib\site-packages\requests_oauthlib\oauth2_session.py:240: in fetch_token
    authorization_response, state=self._state
appvenv\lib\site-packages\oauthlib\oauth2\rfc6749\clients\web_application.py:203: in parse_request_uri_response
    response = parse_authorization_code_response(uri, state=state)
appvenv\lib\site-packages\oauthlib\oauth2\rfc6749\parameters.py:262: in parse_authorization_code_response
    raise MismatchingStateError()
E   oauthlib.oauth2.rfc6749.errors.MismatchingStateError: (mismatching_state) CSRF Warning! State not equal in request and response.


我还没有用同样的方法发现同样的错误,所以没有答案对我的情况有用。

编辑

这是我的client_secret.json

{
    "installed": {
        "client_id": "my_client_id",
        "project_id": "my_project_id",
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "token_uri": "https://oauth2.googleapis.com/token",
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
        "client_secret": "my_client_secret",
        "redirect_uris": [
            "urn:ietf:wg:oauth:2.0:oob",
            "http://localhost"
        ]
    }
}

rdlzhqv9

rdlzhqv91#

根据错误MismatchingStateError,似乎您没有在请求中正确传递某些内容。
错误是由oauth2 rfc6749 parameters file.中的此代码产生的

def parse_authorization_code_response(uri, state=None):
    """Parse authorization grant response URI into a dict.
    If the resource owner grants the access request, the authorization
    server issues an authorization code and delivers it to the client by
    adding the following parameters to the query component of the
    redirection URI using the ``application/x-www-form-urlencoded`` format:
    **code**
            REQUIRED.  The authorization code generated by the
            authorization server.  The authorization code MUST expire
            shortly after it is issued to mitigate the risk of leaks.  A
            maximum authorization code lifetime of 10 minutes is
            RECOMMENDED.  The client MUST NOT use the authorization code
            more than once.  If an authorization code is used more than
            once, the authorization server MUST deny the request and SHOULD
            revoke (when possible) all tokens previously issued based on
            that authorization code.  The authorization code is bound to
            the client identifier and redirection URI.
    **state**
            REQUIRED if the "state" parameter was present in the client
            authorization request.  The exact value received from the
            client.
    :param uri: The full redirect URL back to the client.
    :param state: The state parameter from the authorization request.
    For example, the authorization server redirects the user-agent by
    sending the following HTTP response:
    .. code-block:: http
        HTTP/1.1 302 Found
        Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA
                &state=xyz
    """
    if not is_secure_transport(uri):
        raise InsecureTransportError()

    query = urlparse.urlparse(uri).query
    params = dict(urlparse.parse_qsl(query))

    if state and params.get('state', None) != state:
        raise MismatchingStateError()

    if 'error' in params:
        raise_from_error(params.get('error'), params)

    if not 'code' in params:
        raise MissingCodeError("Missing code parameter in response.")

    return params

字符串
parameters文件中的这一行将触发错误:

if state and params.get('state', None) != state:
        raise MismatchingStateError()


由于您使用的是InstalledAppFlowrun_local_server()' I think that the error is linked to your client_secret.json文件。 我在你的client_secret.json文件中注意到你正在使用可选参数auth_provider_x509_cert_url.根据API,当使用这个可选参数时,client_secret.json`文件的正确格式是这样的:

{
  "installed": {
    "client_id": "[[INSERT CLIENT ID HERE]]",
    "client_secret": "[[INSERT CLIENT SECRET HERE]]",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token",
    "client_email": "",
    "redirect_uris": [
      "urn:ietf:wg:oauth:2.0:oob",
      "oob"
    ],
    "client_x509_cert_url": "",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs"
  }
}

相关问题