我正在尝试通过我的 Django 网站上的 Github 进行身份验证。这就是我想出的:
import string
import random
import urllib
from django.conf import settings
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.utils.crypto import constant_time_compare
from django.contrib.auth import login
from rauth import OAuth2Service
from mongoengine.django.auth import User
from utils import make_absolute
SESSION_KEY = '_oauth_access_token'
SESSION_STATE = '_oauth_state'
github = OAuth2Service(
client_id=settings.GITHUB_APP_ID,
client_secret=settings.GITHUB_API_SECRET,
name='github',
authorize_url='https://github.com/login/oauth/authorize',
access_token_url='https://github.com/login/oauth/access_token',
base_url='http://github.com/')
def random_string():
return ''.join(random.choice(string.ascii_letters + string.digits)
for _ in xrange(random.randint(27, 49)))
def flush_and_set(request, key, value):
if key in request.session:
if request.session[key] != value:
request.session.flush()
else:
request.session.cycle_key()
request.session[key] = value
def start_pipeline(request):
state = random_string()
flush_and_set(request, SESSION_STATE, state)
return redirect(github.get_authorize_url(
redirect_uri=make_absolute(reverse('auth-pipeline-end')),
state=state))
def end_pipeline(request):
if not constant_time_compare(request.session[SESSION_STATE],
request.GET['state']):
return redirect('home')
session = github.get_auth_session(data={'code': request.GET['code'],
'redirect_uri':
make_absolute(reverse('home'))})
flush_and_set(request, SESSION_KEY, session.access_token)
user_data = session.get('https://api.github.com/user?' +
urllib.urlencode({'access_token':
session.access_token})).json()
username = user_data['login']
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
user = User(username=username)
for field in ('email',):
d = user_data[field]
if d:
setattr(user, field, d)
user.backend = 'mongoengine.django.auth.MongoEngineBackend'
user.save()
login(request, user)
return redirect('home')
我有两个问题:
- 这样做是否安全可靠?
- 我应该设置会话的到期时间吗?因为现在在我看来,它永远不会过期。
注意:我也在使用 rauth:https ://rauth.readthedocs.org/en/latest/