Search code examples
djangodjango-rest-frameworksingle-page-applicationdjango-rest-framework-jwt

Login with Django REST JWT


I have Django project with two apps. First app is simple Login/Register app based on default Django auth mechanism. It has two forms and after successful login or register will be redirected to my second app. So, my second app is it the Single Page Application based on Vue.js.

Also I used djangorestframework and djangorestframework-jwt packages.

I understood how JWT works but I can't understand how to implement it to my project. For example this is part of code that executing after POST-request from login form in my views:

...
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, email=username, password=password)
if user is not None:
    login(request, user)
    return redirect('spa')
...

So, I got next questions:

  1. What should I do after successful login (before redirect) in order to make token and will send with response
  2. djangorestframework-jwt provides views to include in urls

    from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token
    

    So, where I should call obtain_jwt_token? In SPA after successful login?

  3. In order to use JWT should I to create serializer for User model?
  4. Is it right to use *rest-jwt without RESTful support?

Solution

  • Beginning your fourth question:

    Is it right to use *rest-jwt without RESTful support?

    Rest JWT is an authentication method for APIs, so mixing it with Django default auth is somewhat of a misuse and I think is why you are running into confusion on this problem. You should use the rest-jwt methods as stand-alone auth procedures rather than tied in with the built-in Django auth methods.

    Considering this, I think the best way to go would be to incorporate your sign-in/sign-up functionality from your first app into your Vue application. Then the auth methods in the Vue app can access API routes from your Django server.

    Here's a brief run through of how that can work:

    In myapp/urls.py:

    from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token
    urlpatterns = [
        url('auth/token$', obtain_jwt_token),
        url('auth/token/refresh', refresh_jwt_token,
        url('auth/token/verify', verify_jwt_token)
    ]
    

    Then in Vue your login functionality can make a POST request to [host]/auth/token with the user's credentials to receive a JWT. For reference DRF JWT docs: https://jpadilla.github.io/django-rest-framework-jwt/#usage

    This way you won't have to worry about redirecting and changing auth processes.