微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决Google Oath2 库在调用 flow.InstalledAppFlow.from_client_secrets_file() 时引发 CSRF 警告

我有以下 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 = HelloFreshCalculator(SHEET_URLS)
marvin\helpers\hf_calculations.py:24: in __init__
    self.gspread_accessor = GspreadAccessor()
marvin\helpers\utilities.py:547: in __init__
    self.google_sheets = self.authorize_google_sheets()
marvin\helpers\utilities.py:552: in authorize_google_sheets
    credentials = get_credentials()
marvin\helpers\utilities.py:84: in get_credentials
    appflow.run_local_server()
marvinvenv\lib\site-packages\google_auth_oauthlib\flow.py:480: in run_local_server
    self.fetch_token(authorization_response=authorization_response)
marvinvenv\lib\site-packages\google_auth_oauthlib\flow.py:288: in fetch_token
    return self.oauth2session.fetch_token(self.client_config["token_uri"],**kwargs)
marvinvenv\lib\site-packages\requests_oauthlib\oauth2_session.py:240: in fetch_token
    authorization_response,state=self._state
marvinvenv\lib\site-packages\oauthlib\oauth2\rfc6749\clients\web_application.py:203: in parse_request_uri_response
    response = parse_authorization_code_response(uri,state=state)
marvinvenv\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"
        ]
    }
}

解决方法

根据错误 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

参数文件中的这一行触发了错误:

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"
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。