如何同时使用简单的JWT令牌身份验证和基本身份验证?

huangapple go评论53阅读模式
英文:

How to use both simple jwt token authentication and BasicAuthentication?

问题

我已经实现了DRF API,并使用了SimpleJWT身份验证系统。它在外部脚本连接API时运行良好,这使得我无需存储凭据,只需使用令牌。

但是,我还希望在从浏览器访问API时能够使用DRF界面登录,所以我还实现了BasicAuthentication和SessionAuthentication。这样做是否正确?

在我的settings.py文件中,我进行了如下配置:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ]
}

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=1),
}

在我的api views.py文件中,我有如下视图函数:

from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import permission_classes, authentication_classes

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_all(request):
    # 使用令牌,可以在请求中获得使用该令牌的用户
    user = request.user
    # 仅显示使用提供的令牌的用户的测量数据
    mesures = Mesure.objects.filter(user_id=user.id)
    serializer = MesureSerializer(mesures, many=True)
    return Response(serializer.data)

在我的urls.py文件中,我有以下URL配置:

from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView

urlpatterns = [
    path('mesures/', views.get_all),
    path('mesure-add/', views.add_mesure),
    path('token/', TokenObtainPairView.as_view(), name='obtain_tokens'),
    path('token/refresh/', TokenRefreshView.as_view(), name='refresh_token'),
    path('api-auth/', include('rest_framework.urls'))
]

你可以看到,我不得不注释掉@authentication_classes装饰器,以使它适用于令牌和登录两种方式。你认为这是一个不错的做法吗?

英文:

I have an DRF api and I have implemented the simplejwt authentication system. It works well. It is usefull when I want to connect my api from external script (I don't need to store credential and just use the token).

However I also want to be able to use the DRF interface login when i reach my api from browser so I have implemented also the Basic and SessionAuthentication. Is it the good way to do that ?

in my settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ]
}

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=1), 
}

in my api views.py

from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.decorators import permission_classes, authentication_classes

# Create your views here.
@api_view(['GET'])
#@authentication_classes([SessionAuthentication, BasicAuthentication])
@permission_classes([IsAuthenticated])
def get_all(request):
    
    # as a token is used, the user with this token is know in the requets
    user = request.user
    # show only mesures of user having the token provided
    mesures = Mesure.objects.filter(user_id=user.id)
    serializer = MesureSerializer(mesures, many=True)
    
    return Response(serializer.data)

In my urls.py

from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView

urlpatterns = [
    path('mesures/', views.get_all),
    path('mesure-add/', views.add_mesure),
    path('token/', TokenObtainPairView.as_view(), name='obtain_tokens'),
    path('token/refresh/', TokenRefreshView.as_view(), name='refresh_token'),
    path('api-auth/', include('rest_framework.urls'))
]

As you can see I had to comment the @authentication_classes decorator to make it work for both with token and login. Do you believe this is a good way to proceed ?

答案1

得分: 1

因为根据DRF文档 -

由于我们现在在API上有一组权限,如果我们想要编辑任何片段,我们需要对其进行身份验证。 我们尚未设置任何身份验证类,因此当前应用的是默认值,即SessionAuthenticationBasicAuthentication

来源: 与API进行身份验证

参考: 第109行:rest_framework/views.py第40行:rest_framework/settings.py

英文:

You should be fine with this because as per the DRF documentation -

> Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets. We haven't set up any authentication classes, so the defaults are currently applied, which are SessionAuthentication and BasicAuthentication.

Source: Authenticating with the API

Ref: Line 109: rest_framework/views.py and Line 40: rest_framework/settings.py

huangapple
  • 本文由 发表于 2023年2月9日 02:29:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75390241.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定