【发布时间】:2015-10-28 06:18:56
【问题描述】:
我正在尝试在我的单页 Angular 应用程序中启用身份验证,在前端使用 Satellizer 作为客户端,在后端使用 django rest framework 启用 python social auth。主要问题是我想使用 JWT 而不是会话身份验证。
我尝试将用户确认弹出窗口后得到的响应传递给social/complete/backend(python 社交身份验证视图),但没有成功。
在我把谷歌配置的卫星器中:
$authProvider.google({
clientId:'609163425136-1i7b7jlr4j4hlqtnb1gk3al2kagavcjm.apps.googleusercontent.com',
url: 'social/complete/google-oauth2/',
optionalUrlParams: ['display', 'state'],
state: function() {
return Math.random();
}
});
我遇到的问题是在python social auth:
缺少所需的参数状态
对于 google-oauth2 和
缺少所需的参数代码
为 facebook。
这对我来说很奇怪,因为这些参数存在于请求负载中,然后我可以在我自己的自定义视图中获取。
我最接近解决方案的方法是编写自己的视图,在该视图中我可以正常接受参数state。
这是我的视图,它处理响应并使用django-rest-framework-jwt 创建一个新的 jwt 令牌:
class SocialAuthView(APIView):
throttle_classes = ()
permission_classes = ()
authentication_classes = ()
social_serializer = SocialAuthSerializer
user_serializer = None
def post(self, request):
access_token_url = 'https://accounts.google.com/o/oauth2/token'
people_api_url = 'https://www.googleapis.com/plus/v1/people/me/openIdConnect'
from django.conf import settings
payload = dict(client_id=request.data['clientId'],
redirect_uri=request.data['redirectUri'],
client_secret=settings.SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET,
code=request.data['code'],
grant_type='authorization_code')
# Step 1. Exchange authorization code for access token.
import requests
import json
r = requests.post(access_token_url, data=payload)
token = json.loads(r.text)
headers = {'Authorization': 'Bearer {0}'.format(token['access_token'])}
# Step 2. Retrieve information about the current user.
r = requests.get(people_api_url, headers=headers)
profile = json.loads(r.text)
try:
user = User.objects.filter(email=profile['email'])[0]
except IndexError:
pass
import jwt
from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler
if user:
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
return Response({'token': token.decode('unicode_escape')},
status=status.HTTP_200_OK)
u = User.objects.create(username=profile['name'], first_name=profile['given_name'],
last_name=profile['family_name'], email=profile['email'])
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
return Response({'Bearer': token.decode('unicode_escape')},
status=status.HTTP_200_OK)
我的意思是,它可以工作,但是如果我可以使用 python social auth 来实现它,我并没有得到所有的好处。也许有一种方法可以通过 python social auth 从这个视图调用一些函数,如 do_auth 进行身份验证?
让我吃惊的是我在这个问题上的挣扎。
欢迎所有帮助。
tl,dr:如何使用 Satellizer、django-rest-framework 实现 angular 单页 应用程序, python 社交验证 和 JWT?
【问题讨论】:
标签: python angularjs django django-rest-framework satellizer