【问题标题】:Django JWT HTTP Authorization not passingDjango JWT HTTP 授权未通过
【发布时间】:2018-06-07 17:44:17
【问题描述】:

我正在尝试将 JWT 令牌身份验证与 Django 休息框架一起使用。我能够成功获得访问和刷新令牌。我确保令牌是有效的。但是当我尝试使用访问令牌访问一些受保护的 apiview 时。它说

{"detail":"Authentication credentials were not provided."}.

curl -H "Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTE0MzQzNzcxLCJqdGkiOiIwYmE5YTcxZTJmMzQ0YmRmOTM1ZWQ3MTU3ZmI2NDkyZiIsInVzZXJfaWQiOjh9.dI3t8yvNe2Z7MKXojGvFpq_Etf1cLg8QSYsNobJ6jQ0" http://localhost:8000/users/me/

但是,在服务器端,我确实得到了 request.META,其中包含一个包含上述令牌的 HTTP_AUTHORIZAITON 字段。

我目前在 localhost 而不是 Apache 上进行开发,具有以下文件和配置:

在views.py中:

class GetMyInfo(views.APIView):

 def get(self,request):
  print(request.META)
  user = request.user
  profile = user.profile
  profile_serializer = ProfileSerializer(instance = profile)
  return Response(profile_serializer.data, status = HTTP_200_OK)

在 url.py 中:

urlpatterns = [
    re_path(r'^admin/', admin.site.urls),
    re_path(r'^api/$', get_schema_view()),
    re_path(r'^api/auth/', include('rest_framework.urls')),
    re_path(r'^api/auth/token/obtain/$', TokenObtainPairView.as_view(), name = 'token_obtain_pair'),
    re_path(r'^api/auth/token/refresh/$', TokenRefreshView.as_view(), name = 'token_refresh'),
    re_path(r'^api/auth/token/verify/$', TokenVerifyView.as_view(), name = 'token_verify'),
    #re_path(r'^api-token-auth/', authviews.obtain_auth_token, name = 'obtain_auth_token'),
    re_path(r'^users/$', views.CreateUser.as_view(), name = 'register'),
    re_path(r'users/(?P<uuid>[0-9a-f-]+)/$', views.GetUserInfo.as_view(), name = 'info'),
    re_path(r'users/me/$', views.GetMyInfo.as_view(), name = 'myinfo'),
]

settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'api'
]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES':(
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES':(
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        #'rest_framework.authentication.SessionAuthentication',
        #'rest_framework.authentication.TokenAuthentication',
        #'rest_framework.authentication.BasicAuthentication',
    ),
    'TEST_REQUEST_DEFAULT_FORMAT': 'json',
}


AUTH_USER_MODEL = 'api.User'

在models.py中:

@receiver(post_save, sender = settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance = None, created = False, **kwargs):
 if created:
  Token.objects.create(user = instance)

class User(AbstractUser):
 uuid = models.UUIDField(default = uuid.uuid4, unique = True)

class Profile(models.Model):
 owner = models.OneToOneField(settings.AUTH_USER_MODEL, 
 on_delete = models.CASCADE, 
 primary_key = True,
 related_name = 'profile')
 displayname = models.CharField(max_length = 30)
 location = models.CharField(max_length = 100, null = True)
 bio = models.CharField(max_length = 500, null = True)
 relationships = models.ManyToManyField('self', 
 through = 'Followings', 
 symmetrical = False,
 related_name = 'related_to')

【问题讨论】:

    标签: python django django-rest-framework jwt


    【解决方案1】:

    据我所知,您正在使用 rest_framework_simplejwt 包来处理 JWT 身份验证。

    文档中的一个示例指定您应该使用: Authorization: Bearer &lt;token&gt; 访问受保护的视图。

    所以不是

    curl -H "Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTE0MzQzNzcxLCJqdGkiOiIwYmE5YTcxZTJmMzQ0YmRmOTM1ZWQ3MTU3ZmI2NDkyZiIsInVzZXJfaWQiOjh9.dI3t8yvNe2Z7MKXojGvFpq_Etf1cLg8QSYsNobJ6jQ0" http://localhost:8000/users/me/
    

    使用:

    curl -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTE0MzQzNzcxLCJqdGkiOiIwYmE5YTcxZTJmMzQ0YmRmOTM1ZWQ3MTU3ZmI2NDkyZiIsInVzZXJfaWQiOjh9.dI3t8yvNe2Z7MKXojGvFpq_Etf1cLg8QSYsNobJ6jQ0" http://localhost:8000/users/me/
    

    【讨论】:

    • 如果要使用JWT,需要在配置中指定:SIMPLE_JWT = {'AUTH_HEADER_TYPES': ['JWT']}
    猜你喜欢
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 2018-02-02
    • 2018-01-20
    • 2019-04-18
    • 2023-02-23
    • 2018-03-18
    相关资源
    最近更新 更多