我使用Angular 2作爲前端,django rest框架作爲後端。如何同步django rest api中的用戶與Auth0
在前端,我使用Auth0驗證用戶身份(https://auth0.com/docs/quickstart/spa/angular2)。之後我的idtoken發送到我的後臺創建新聞用戶(https://auth0.com/docs/quickstart/backend/python連接auth0 在角2的代碼:
import { Component } from '@angular/core';
import { Auth } from './auth.service';
import { AuthHttp } from 'angular2-jwt';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Component({
selector: 'ping',
templateUrl: 'app/ping.template.html'
})
export class PingComponent {
API_URL: string = 'http://localhost:8000/callback/';
message: string;
constructor(private auth: Auth, private http: Http, private authHttp: AuthHttp) {}
// the code for sending idtoken to my backend
//correct me please if I am wrong
public securedPing() {
this.message = '';
this.authHttp.post(`${this.API_URL}`,localStorage.getItem('id_token'))
.map(res => res.json())
.subscribe(
data => this.message= data.text,
error => this.message = error._body || error
);
}
};
,在這裏我的後端在Django代碼:
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.http import JsonResponse
from places_management.serializers import UserSerializer
from django.contrib.auth.models import User
import jwt
class Callbacks(APIView):
authentication_classes = []
permission_classes = []
def authenticate(error):
return Response(error,401)
def post(self, request, format=None):
"""
Callback for after user logs in. It creates a
django auth user if one does not exist, username is the
user_id retured frrom auth0
"""
#token = request.META['HTTP_AUTHORIZATION'].split('JWT ')[1]
auth = request.META.get('HTTP_AUTHORIZATION', None)
if not auth:
return Response({'code': 'authorization_header_missing', 'description': 'Authorization header is expected'},status=status.HTTP_401_UNAUTHORIZED)
parts = auth.split()
if parts[0].lower() != 'bearer':
return authenticate({'code': 'invalid_header', 'description': 'Authorization header must start with Bearer'})
elif len(parts) == 1:
return authenticate({'code': 'invalid_header', 'description': 'Token not found'})
elif len(parts) > 2:
return authenticate({'code': 'invalid_header', 'description': 'Authorization header must be Bearer + \s + token'})
token = parts[1]
try:
payload = jwt.decode(
token,
'Z-HWF9cDxGTk7aMZe0A2Ygt81vGBPihz1FCRzJfS87B0mCw1ClQzp1HgA7U3WsSg',
audience='GwtnxdwhMWsuGz6JxabDkrNvFhAvn5ZJS'
)
except jwt.ExpiredSignature:
return authenticate({'code': 'token_expired', 'description': 'token is expired'})
except jwt.InvalidAudienceError:
return authenticate({'code': 'invalid_audience', 'description': 'incorrect audience, expected: GwtnxdwhMWsuGz6JxabDkrNvFhvn5ZJS'})
except jwt.DecodeError:
return authenticate({'code': 'token_invalid_signature', 'description': 'token signature is invalid'})
#try:
#payload = settings.JWT_AUTH['JWT_DECODE_HANDLER'](token)
#except:
#return Response('text',status=status.HTTP_401_UNAUTHORIZED)
user = User.objects.filter(username=payload['sub']).first()
if(user is None):
password = User.objects.make_random_password()
user = User.objects.create_user(
username=payload['sub'], password=password)
serializer = UserSerializer(user, context={'user': user})
return Response(serializer.data, status=status.HTTP_200_OK)
也許我我錯了,請幫忙
請閱讀。我的意思是Angular 2和Auth0。你可以幫助Auth0和Django的後端 – saius
我只推薦在Django的Auth驗證用戶模型與其餘的API - 謝謝Rahil – Rahil