[英]Authentication using JWT in Django
what I am trying to do is authenticate my Django project using JWT. 我想要做的是使用JWT对Django项目进行身份验证。 Firstly i am confused which library i have to install one is django-jwt-auth and other one is djangorestframework-jwt . 首先,我很困惑,我必须安装哪个库是django-jwt-auth ,另一个是djangorestframework-jwt 。
So here is my views.py, in which i have a user model and i want to authenticate when a new user is being generated. 所以这是我的views.py,其中有一个用户模型,我想在生成新用户时进行身份验证。
class UserDetails(APIView):
def get(self, request, *args, **kwargs):
users = Users.objects.all().order_by('-created_at')
serializer = UserSerializer(users, many=True)
return Response(serializer.data)
def options(self, request, *args, **kwargs):
return Response()
def post(self, request, *args, **kwargs):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(status=HTTP_201_CREATED)
return Response(status=HTTP_400_BAD_REQUEST)
I have models.py 我有models.py
class Users(models.Model):
group_id = models.IntegerField()
name = models.CharField(max_length=100, null=True)
email = models.CharField(max_length=100, null=True)
password = models.CharField(max_length=255, null=False)
remember_token = models.CharField(max_length=255, null=True)
activated = models.IntegerField(default=1)
banned = models.IntegerField(default=0)
ban_reason = models.CharField(max_length=255, null=True)
otp = models.CharField(max_length=255, null=True)
created_at = models.DateTimeField()
updated_at = models.DateTimeField(null=True)
my url.py 我的url.py
urlpatterns = [
url(r'^api-token-auth/', 'rest_framework_jwt.views.obtain_jwt_token'),
url(r'userdetails/$', UserDetails.as_view()),
Now i don't know how to access that api-token-auth. 现在我不知道如何访问该api-token-auth。 where to put authentication in views.py 将身份验证放置在views.py中的位置
and where i ahve to add these settings 以及我要添加这些设置的位置
JWT_ENCODE_HANDLER = 'jwt_auth.utils.jwt_encode_handler'
JWT_DECODE_HANDLER = 'jwt_auth.utils.jwt_decode_handler',
JWT_PAYLOAD_HANDLER = 'jwt_auth.utils.jwt_payload_handler'
JWT_PAYLOAD_GET_USER_ID_HANDLER = 'jwt_auth.utils.jwt_get_user_id_from_payload_handler'
JWT_SECRET_KEY: SECRET_KEY
JWT_ALGORITHM = 'HS256'
JWT_VERIFY = True
JWT_VERIFY_EXPIRATION = True
JWT_LEEWAY = 0
JWT_EXPIRATION_DELTA = datetime.timedelta(seconds=300)
JWT_ALLOW_REFRESH = False
JWT_REFRESH_EXPIRATION_DELTA = datetime.timedelta(days=7)
JWT_AUTH_HEADER_PREFIX = 'Bearer'
and some post say i have to this to my settings.py 有的帖子说我必须在我的settings.py
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',
),
}
So please tell me how to use JWT. 因此,请告诉我如何使用JWT。
djangorestframework-jwt
您应该安装djangorestframework-jwt
Add this decorators to functions where you want authentication(change GET appropriate to method you are using, add AllowAny to DEFAULT_AUTHENTICATION_CLASSES if you want to have views accessible without auth) 将此装饰器添加到要进行身份验证的函数中(更改GET以适合您使用的方法,如果要使视图无需身份验证即可访问,则将AllowAny添加到DEFAULT_AUTHENTICATION_CLASSES中)
@api_view(['GET']) @permission_classes((IsAuthenticated, ))
Call api-token-auth/
with username and password to get token 使用用户名和密码调用api-token-auth/
以获取令牌
Authorization: JWT <your_token>"
调用受Authorization: JWT <your_token>"
保护的函数时,将令牌添加到您的请求标头中: Authorization: JWT <your_token>"
All settings must be added to settings.py
file like described here I see that your User
model doesn't extend AbstractUser
or BaseUser
model. 如此处所述,所有设置都必须添加到settings.py
文件中。我看到您的User
模型没有扩展AbstractUser
或BaseUser
模型。 If you want to use JWT auth with Django, in that easy way desribed here, your User
model should extend one of those models(I suggest AbstractUser). 如果要在Django中使用JWT auth,请以此处描述的简单方式,您的User
模型应扩展其中一种模型(我建议AbstractUser)。 Therfore Django will manage all auth hard-work for you. 因此Django将为您管理所有身份验证工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.