创建会话时如何检测过期的访问令牌?

dan*_*ast 1 python oauth rauth

我有以下测试程序:

from   rauth.service import OAuth1Service, OAuth2Service

SUPPORTED_SERVICES = {
    'twitter'  : ( 'OAuth1', 'twitter',  'https://api.twitter.com/oauth',        'request_token', 'access_token', 'authorize', 'https://api.twitter.com/1/',  None),
    'facebook' : ( 'OAuth2', 'facebook', 'https://graph.facebook.com/oauth',     None,            'access_token', 'authorize', 'https://graph.facebook.com/', 'https://www.facebook.com/connect/login_success.html'),
    'google'   : ( 'OAuth2', 'google',   'https://accounts.google.com/o/oauth2', None,            'token',        'auth',      None,                          'http://localhost'),
}

CLIENT_DATA = {
    'twitter'  : ('dummy_client_id', 'dummy_client_secret'),
    'facebook' : ('dummy_client_id', 'dummy_client_secret'),
    'google'   : ('dummy_client_id', 'dummy_client_secret'),
}

USER_TOKENS = {
    'user1' : {
        'twitter'  : ('dummy_access_token', 'dummy_access_token_secret'),
        'facebook' : ('dummy_access_token', None),
        'google'   : ('dummy_access_token', None),
    }
}

def test_google(user_id):
    service_id = 'google'
    oauthver, name, oauth_base_url, request_token_url, access_token_url, authorize_url, base_url, redirect_uri = SUPPORTED_SERVICES[service_id]
    request_token_url = oauth_base_url + '/' + (request_token_url or '')
    access_token_url  = oauth_base_url + '/' + access_token_url
    authorize_url     = oauth_base_url + '/' + authorize_url
    client_id, client_secret = CLIENT_DATA[service_id]
    google = OAuth2Service(
        client_id=client_id,
        client_secret=client_secret,
        name=name,
        authorize_url=authorize_url,
        access_token_url=access_token_url,
        base_url=base_url)
    access_token, access_token_secret = USER_TOKENS[user_id][service_id] # access_token_secret only needed for twitter (OAuth1)
    session = google.get_session(access_token)
    user = session.get('https://www.googleapis.com/oauth2/v1/userinfo').json()
    print user

test_google('user1')
Run Code Online (Sandbox Code Playgroud)

我已经授权我的应用程序访问 的google帐户user1,并获得了access_token。该访问令牌已经过期,我的程序的输出是:

{u'error': {u'code': 401, u'message': u'Invalid Credentials', u'errors': [{u'locationType': u'header', u'domain': u'global', u'message': u'Invalid Credentials', u'reason': u'authError', u'location': u'Authorization'}]}}
Run Code Online (Sandbox Code Playgroud)

我想在创建会话时而不是请求数据时检查访问令牌是否已过期。这可能吗?如何验证会话对象是否真正被授权?

为了澄清起见,我想做的是:

  1. 首先让用户授权我的应用程序
  2. 保存访问令牌以供将来使用(在数据库中,但在测试代码中,这是在脚本中硬编码的)
  3. 每当稍后访问检测到令牌已过期时,请返回步骤1

我目前在第 3 步中遇到问题。我当然可以检测到 GET 的 json 回复中的 401,但强制验证所有 GET 访问看起来相当麻烦。我想要做的是验证会话在创建会话时是否确实处于活动状态,然后假设在会话对象的整个持续时间内它将保持活动状态。通常这只是几毫秒,而我的 web 应用程序正在处理请求并使用 OAuth 会话对象访问 google API。

gat*_*tto 5

您必须get_authorization_url先调用,哪个用户必须打开并授予您访问他的帐户的权限,作为回报,您将从redirect_uri回调的查询参数中获得一个代码,您可以兑换该代码access_token

params = {
    'scope': 'email',
    'response_type': 'code',
    'redirect_uri': redirect_uri,
    'access_type': 'offline', # to get refresh_token
}

print google.get_authorize_url(**params)
Run Code Online (Sandbox Code Playgroud)

根据文档,此代码应该有效:

data = {
    'code': 'code you got from callback',
    'grant_type': 'authorization_code',
    'redirect_uri': 'http://localhost/oauth2',
}

response = google.get_raw_access_token(data=data)
Run Code Online (Sandbox Code Playgroud)

作为响应,您将得到如下 JSON 数据:

{
  "access_token" : "ya29.AHE<....>n3w",
  "token_type" : "Bearer",
  "expires_in" : 3600,
  "id_token" : "eyJh<...>QwNRzc",
  "refresh_token" : "1/X86S<...>Vg4"
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,有expires_in(秒),您必须存储获得令牌的时间,并稍后与当前时间 + 进行比较expires_in

如果令牌过期,您可以refresh_token稍后刷新它,而无需再次要求用户确认:

response = google.get_raw_access_token(data={
    'refresh_token': refresh_token,
    'grant_type': 'refresh_token',
})
print response.content
Run Code Online (Sandbox Code Playgroud)

请注意,refresh_token只有在用户第一次授权该应用程序时才会返回该信息。有关详细信息,请参阅此问题。

唉,看来你不能使用get_auth_session,因为在内部它只提取access_token而其他所有内容都被丢弃。

如果您access_token没有code先获得身份验证就立即获取,您仍然会收到expires_in回调。来自文档

https://oauth2-login-demo.appspot.com/oauthcallback#access_token=1/fFBGRNJru1FQd44AzqT3Zg&token_type=Bearer&expires_in=3600