【问题标题】:Create new user with Django Rest Framework JSON Web Token使用 Django Rest Framework JSON Web Token 创建新用户
【发布时间】:2020-08-29 08:59:06
【问题描述】:

我正在使用带有 Simple JWT 的 Django REST 框架。我正在尝试创建一个用户注册页面。目前,我收到此错误

禁止 (403) CSRF 验证失败。请求中止。

失败的原因: CSRF 令牌丢失或不正确。

这里有完整的错误信息:

在settings.py下,我添加了这个:

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

}

我的项目 urls 文件夹:

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()),
]

这是我的注册端点的应用视图。

def register(request):
    if request.method == "POST":
        email = request.POST["email"]

        # Ensure password matches confirmation
        password = request.POST["password"]
        confirmation = request.POST["confirmation"]
        if password != confirmation:
            return render(request, "my_api/register.html", {
                "message": "Passwords must match."
            })

        # Attempt to create new user
        try:
            # Creates a hashed password. 
            #password = make_password(password)
            user = User.objects.create_user(username=email, email=email, password=password)
            user.save()
        except IntegrityError as e:
            print(e)
            return render(request, "my_api/register.html", {
                "message": "Email address already taken."
            })
        login(request, user)
        return HttpResponse("Successfully created account.")
    else:
        return render(request, "my_api/register.html")

【问题讨论】:

标签: django django-rest-framework django-rest-framework-simplejwt


【解决方案1】:

在我的情况下导致错误的原因是我试图让用户使用 http://localhost:8000/jwt/create 而我的端点以 auth/ 开头所以它应该是 http://localhost:8000/auth/jwt/create 或者在你的情况下它应该是

http://localhost:8000api/token/jwt/create

我写它是因为其他一些用户可能有同样的问题。

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 2023-03-24
    • 2017-08-22
    • 1970-01-01
    • 2013-11-15
    • 2020-06-22
    • 2015-05-21
    • 2016-11-28
    • 1970-01-01
    相关资源
    最近更新 更多