首页 > 解决方案 > 如何实现谷歌智能锁一键登录

问题描述

我想借助文档https://developers.google.com/identity/one-tap/web/在我的网站上实现 Google 的一键注册和自动登录,但我对如何实现感到困惑在蟒蛇。

def smartlock(request):
    try:
        CLIENT_ID='*******'
        csrf_token_cookie = self.request.cookies.get('g_csrf_token')
        if not csrf_token_cookie:
            webapp2.abort(400, 'No CSRF token in Cookie.')
        csrf_token_body = self.request.get('g_csrf_token')
        if not csrf_token_body:
            webapp2.abort(400, 'No CSRF token in post body.')
        if csrf_token_cookie != csrf_token_body:
            webapp2.abort(400, 'Failed to verify double submit cookie.')
        # Specify the CLIENT_ID of the app that accesses the backend:
        idinfo = id_token.verify_oauth2_token(csrf_token_cookie, requests.Request(), CLIENT_ID)

        # Or, if multiple clients access the backend server:
        # idinfo = id_token.verify_oauth2_token(token, requests.Request())
        # if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]:
        #     raise ValueError('Could not verify audience.')

        if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
            raise ValueError('Wrong issuer.')

        # If auth request is from a G Suite domain:
        # if idinfo['hd'] != GSUITE_DOMAIN_NAME:
        #     raise ValueError('Wrong hosted domain.')

        # ID token is valid. Get the user's Google Account ID from the decoded token.
        userid = idinfo['sub']
    except ValueError:
        # Invalid token
        pass
'''

标签: google-identity

解决方案


如本页“关键点”部分所述:ID 令牌在凭证字段中返回,而不是在 g_csrf_token 字段中。

因此,您需要使用以下代码获取 idinfo:

credential = self.request.get('credential')

idinfo = id_token.verify_oauth2_token(credential, requests.Request(), CLIENT_ID)

g_csrf_token 参数用于不同的目的。它确保请求是从您自己域中的页面提交的,以防止跨站点请求伪造攻击。


推荐阅读