修改登录视图以使用简单的JWT

问题描述

我正在使用带有SimpleJWT的Django REST框架。我试图让我的用户使用simpleJWT身份验证登录。粗略地说,我认为我的登录视图应该:从表单中检索用户名/密码,将POST请求发送到TokenObtainPairView.as_view()视图,收集返回的令牌并将其存储在本地存储中。如何在Django代码中执行此操作?目前,我只有一个不使用JWT的标准登录表单。

Settings.py

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES' : ('rest_framework.permissions.IsAuthenticated',),'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework_simplejwt.authentication.JWTAuthentication',}

我的项目网址:

urlpatterns = [
    path('admin/',admin.site.urls),path("",include("my_api.urls")),path('api-auth/',include('rest_framework.urls')),path('api/token',TokenObtainPairView.as_view()),path('api/token/refresh',TokenRefreshView.as_view()),]

这是用户登录视图。我想我应该以用户名和密码作为有效载荷向“ api / token”发出POST请求,获取返回的令牌,并将其存储在本地存储中,但是我不知道如何在Django中做到这一点。

def login_view(request):
    if request.method == "POST":
        # Attempt to sign user in
        email = request.POST["email"]
        password = request.POST["password"]
        user = User.objects.get(email=email)
        if user.check_password(password):            
            username = user.username
            user = authenticate(username=username,password=password)
            print("Login successful")
            login(request,user)
            return HttpResponseRedirect(reverse("welcome"))```

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)