0

I am using Django REST framework, with Simple JWT. I am trying to create a user registration page. Currently, I am getting this error

Forbidden (403) CSRF verification failed. Request aborted.

Reason given for failure: CSRF token missing or incorrect.

Full error message here:Error message

Under settings.py, I have added this:

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

}

My project urls folder:

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

And this is my app's view for my registration endpoint.

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")
2
  • Did you add the token to your html form? {% csrf_token %} docs.djangoproject.com/en/3.1/ref/csrf Commented Aug 29, 2020 at 9:10
  • 1
    Ok that seems to have solved it... Closing this for now thank you. Commented Aug 29, 2020 at 9:26

1 Answer 1

0

What is causing the error in case of me is that I tried to get the user with http://localhost:8000/jwt/create while my endpoints started with auth/ so it should be http://localhost:8000/auth/jwt/create or in your case it should be

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

I wrote it thinking that some other user might have the same issue.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.