Angular 8和Django3。我正在使用自定义视图类user_id
从Django获取token
和CustomAuthToken
。我收到一个包含token
和user_id
的响应。我正在学习一个教程,并想测试将自定义标头发送到django以查看授权是否可行。
我正在使用邮递员,并将标头设置为Authorization: Bearer 1a683...9e428
。当我向http://127.0.0.1:8000/users/dashboard/23
发送GET请求时,得到响应
"detail": "Authentication credentials were not provided."
我的理解是提供这些标题应该起作用吗?还是客户端上有一些东西可以解码头并将其发送回去?
views.py
class CustomAuthToken(ObtainAuthToken):
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data,
context={'request': request})
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({
'token': token.key,
'user_id': user.pk,
})
settings.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticatedOrReadOnly',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
}
urls.py
urlpatterns = [
path('dashboard/<int:pk>', UserDashboard.as_view(), name='dashboard'),
path(r'api-token-auth/', CustomAuthToken.as_view()),
]