django 怎么在请求头中加 Authorization: Bearer <token>
时间: 2024-03-18 09:40:53 浏览: 224
在 Django 中,你可以通过 Django REST framework 提供的 Authentication 来进行身份认证。如果你使用 JWT 认证,可以使用 `rest_framework_jwt.authentication.JSONWebTokenAuthentication` 来进行认证。
你可以在 DRF 的视图函数中添加 `authentication_classes` 属性,来指定该视图使用的身份认证类。例如:
```python
from rest_framework.views import APIView
from rest_framework.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
class MyView(APIView):
authentication_classes = [JSONWebTokenAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request):
# 在这里获取用户信息,并返回响应
return Response({'username': request.user.username})
```
当客户端发送请求时,需要在请求头中添加 `Authorization: Bearer <token>`,其中 `<token>` 是从服务端获取的 JWT Token。
如果你使用其他的身份认证方式,也可以将 `authentication_classes` 属性替换为相应的身份认证类即可。
阅读全文
相关推荐


















