使用pyjwt实现django用户登录验证
时间: 2024-01-01 16:03:13 浏览: 241
步骤:
1. 安装pyjwt
```
pip install pyjwt
```
2. 在Django中创建一个自定义的认证后端
```python
from django.contrib.auth.backends import BaseBackend
from django.contrib.auth import get_user_model
from jwt.exceptions import ExpiredSignatureError, InvalidTokenError
from jwt import encode, decode
User = get_user_model()
class JWTAuthenticationBackend(BaseBackend):
def authenticate(self, request, **kwargs):
token = kwargs.get('token', None)
if token:
try:
decoded = decode(token, 'secret', algorithms=['HS256'])
user = User.objects.get(username=decoded['username'])
return user
except (ExpiredSignatureError, InvalidTokenError, User.DoesNotExist):
return None
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
```
3. 在settings.py文件中配置认证后端
```python
AUTHENTICATION_BACKENDS = [
'path.to.JWTAuthenticationBackend',
'django.contrib.auth.backends.ModelBackend',
]
```
4. 在视图函数中添加JWT认证
```python
import datetime
import jwt
def login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
token = jwt.encode({'username': user.username, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)}, 'secret', algorithm='HS256')
return JsonResponse({'token': token})
else:
return JsonResponse({'error': 'Invalid credentials'})
```
5. 在需要认证的视图函数中添加装饰器
```python
from django.contrib.auth.decorators import login_required
@login_required(login_url='/login/')
def protected_view(request):
return JsonResponse({'data': 'You are logged in'})
```
6. 在前端发送请求时带上JWT token
```javascript
fetch('/protected_view/', {
headers: {
'Authorization': 'Bearer ' + token
}
})
```
阅读全文