【问题标题】:google oauth how to get the "code" from step2 url谷歌oauth如何从step2 url获取“代码”
【发布时间】:2016-06-06 22:32:27
【问题描述】:

我正在尝试使用 Google OAuth 进行身份验证,但在学习本教程时遇到了一些问题。

这是我目前的设置:

    FLOW = OAuth2WebServerFlow(
        client_id='67490467925.apps.googleusercontent.com',
        client_secret='K1tkrPK97B2W16ZGY',
        scope='https://www.googleapis.com/auth/calendar',
        user_agent='Real_Hub/1.0',
        redirect_uri='http://127.0.0.1:8000/',)


    storage = Storage('calendar.dat')
    credentials = storage.get()
    if credentials is None or credentials.invalid == True:
        auth_uri = FLOW.step1_get_authorize_url()
        return auth_uri
    else:
        http = httplib2.Http()
        http = credentials.authorize(http)

        service = build(serviceName='calendar', version='v3', http=http,
                        developerKey='AIzaSyCBGjIQ2uNbThW_2oMO9P-Ufb8kc')

        return service
        #End OAUTH...

我不确定我应该将credentials = flow.step2_exchange(code)storage.put(credentials) 放在哪里,以及如何获取“代码”变量?在 API 中,它从重定向 url 说。但我不知道如何做到这一点。

【问题讨论】:

    标签: python django api oauth


    【解决方案1】:

    您需要定义一个方法来处理来自 OAuth 提供者的回调,然后将该回调方法映射到您的应用程序上的一个 url,类似于

      http://yourserver/auth_callback
    

    然后在创建 Flow 类时将redirect_uri 设置为auth_callback url

      FLOW = OAuth2WebServerFlow(
        client_id='67490467925.apps.googleusercontent.com',
        ...
        redirect_uri='http://yourserver/auth_callback')
    

    获得auth_uri 后,您需要将用户重定向到该uri,以便他们可以进行身份​​验证/授权

      self.redirect(auth_uri, ...)
    

    身份验证/授权后,OAuth 提供者将“回电”到您之前指定的 redirect_uri。在您的回调处理程序方法中,您现在将解析 code 或者如果它不存在,请检查 error 参数

      code = self.request.get("code")
      credentials = FLOW.step2_exchange(code)
    

    注意:我没有对此进行测试,也有一段时间没有使用过 python,所以语法可能不正确,但希望你能大致了解。

    【讨论】:

    • 我只是继续阅读API并想通了,但这个答案是正确的(:谢谢。
    • 这个答案中的 self 是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    相关资源
    最近更新 更多