我也在用python-社交-身份验证 https://github.com/omab/python-social-auth and django-rest-framework-jwt https://github.com/GetBlimp/django-rest-framework-jwt用于用户身份验证。
我能够将两个身份验证系统集成在一起的方法是创建一个自定义视图,该视图包含“访问令牌' 由 oAuth 提供商提供并尝试使用它创建新用户。创建用户后,我不会返回经过身份验证的用户/会话,而是返回 JWT 令牌。
以下代码片段解释了该解决方案。
Back-End
In my views.py文件我包含以下内容:
@psa()
def auth_by_token(request, backend):
"""Decorator that creates/authenticates a user with an access_token"""
token = request.DATA.get('access_token')
user = request.user
user = request.backend.do_auth(
access_token=request.DATA.get('access_token')
)
if user:
return user
else:
return None
class FacebookView(views.APIView):
"""View to authenticate users through Facebook."""
permission_classes = (permissions.AllowAny,)
def post(self, request, format=None):
auth_token = request.DATA.get('access_token', None)
backend = request.DATA.get('backend', None)
if auth_token and backend:
try:
# Try to authenticate the user using python-social-auth
user = auth_by_token(request, backend)
except Exception,e:
return Response({
'status': 'Bad request',
'message': 'Could not authenticate with the provided token.'
}, status=status.HTTP_400_BAD_REQUEST)
if user:
if not user.is_active:
return Response({
'status': 'Unauthorized',
'message': 'The user account is disabled.'
}, status=status.HTTP_401_UNAUTHORIZED)
# This is the part that differs from the normal python-social-auth implementation.
# Return the JWT instead.
# Get the JWT payload for the user.
payload = jwt_payload_handler(user)
# Include original issued at time for a brand new token,
# to allow token refresh
if api_settings.JWT_ALLOW_REFRESH:
payload['orig_iat'] = timegm(
datetime.utcnow().utctimetuple()
)
# Create the response object with the JWT payload.
response_data = {
'token': jwt_encode_handler(payload)
}
return Response(response_data)
else:
return Response({
'status': 'Bad request',
'message': 'Authentication could not be performed with received data.'
}, status=status.HTTP_400_BAD_REQUEST)
In my urls.py我包括以下路线:
urlpatterns = patterns('',
...
url(r'^api/v1/auth/facebook/', FacebookView.as_view()),
...
)
前端
现在后端身份验证已连接,您可以使用任何前端库发送 access_token 并对用户进行身份验证。就我而言,我使用了AngularJS.
在控制器文件中,我像这样调用 API:
/**
* This function gets called after successfully getting the access_token from Facebook's API.
*/
function successLoginFbFn(response) {
var deferred = $q.defer();
$http.post('/api/v1/auth/facebook/', {
"access_token": response.authResponse.accessToken,
"backend": "facebook"
}).success(function(response, status, headers, config) {
// Success
if (response.token) {
// Save the token to localStorage and redirect the user to the front-page.
Authentication.setToken(response.token);
window.location = '/';
}
deferred.resolve(response, status, headers, config);
}).error(function(response, status, headers, config) {
// Error
console.error('Authentication error.');
deferred.reject(response, status, headers, config);
});
}
通过这种方法,您可以混合使用这两个插件。所有发送的代币将来自django-rest-framework-jwt即使用户仍然可以通过 Facebook、Google、Twitter 等网站提供的身份验证自己的身份。
我只展示了通过 Facebook 进行身份验证的方法,但是您可以对其他提供商采用类似的方法。