認証のためにJWTをユーザーログインAPIに追加したいとします。このコードに従って私は何をすべきですか?私はmanuelによってトークンを作成します。しかし、それは変化しなければならない。どうすれば統合できますか?ありがとうございました。Django Rest FrameworkでのユーザーログインへのJson Web Tokenの作成方法?
シリアライザ
class UserLoginSerializer(ModelSerializer):
token = CharField(allow_blank=True, read_only=True)
class Meta:
model = User
fields = [
'username',
'password',
'token',
]
extra_kwargs = {"password":
{"write_only": True}
}
def validate(self, data):
user_obj = None
username = data.get("username", None)
password = data["password"]
if not username:
raise ValidationError("Kullanıcı adı gerekli.")
user = User.objects.filter(
Q(username=username)
).distinct()
user = user.exclude(email__isnull=True).exclude(email__iexact='')
if user.exists() and user.count() == 1:
user = user.first()
else:
raise ValidationError("Böyle bir Kullanıcı Adı yoktur.")
if user_obj:
if not user_obj.check_password(password):
raise ValidationError("Tekrar deneyiniz.")
data["token"] = "asdasdasdasd"
return data
ビュー
class UserLoginAPIView(APIView):
permission_classes = [AllowAny]
serializer_class = UserLoginSerializer
def post(self, request, *args, **kwargs):
data = request.data
serializer = UserLoginSerializer(data=data)
if serializer.is_valid(raise_exception=True):
new_data = serializer.data
return Response(new_data, status=HTTP_200_OK)
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
設定
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
}
ののURL
urlpatterns = [
url(r'^login/$', UserLoginAPIView.as_view(), name='login'),
url(r'^api-token-auth/', obtain_jwt_token),
url(r'^api-token-refresh/', refresh_jwt_token),
url(r'^api-token-verify/', verify_jwt_token),
url(r'^register/$', UserCreateAPIView.as_view(), name='register'),
]
このパッケージを調べましたか? https://github.com/GetBlimp/django-rest-framework-jwt – jape
はい、私はすでにこのパッケージを見てきました。しかし、私は正確にどのように変更することができないのか分かりません。それについての例があれば教えてください。ありがとうございました – bysucpmeti