yierstem
yierstem

Reputation: 2067

Handling django rest framework + vue SPA auth

How could I get the same functionality as django provides for authenticated user (an user global object to retrieve data for user profile etc.) into vue, for a single page application (using Vue Router, of course).

My point is that I do not know how could I create a middleware for vue equivalently to django middleware for keeping an user logged in once he provided username and password.

I know that I can use django rest framework jwt to implement an endpoint /api-token-auth/ to get the token needed (storing it into localStorge, so I could get it into axios headers) to be able to retrieve information from the api, but I don't have any user session besides the token, I don't have any information about the user passed to templates, of course.

How could I pass an user global object to every template? Is there an easy way to do that?

Thanks in advance.

Upvotes: 3

Views: 2353

Answers (1)

Ganesh
Ganesh

Reputation: 3484

Session Authentication can be implemented with Django REST Frameworks by adding SessionAuthentication class to settings.py as follows.

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

This will use Django's default session backend for Authentication. The catch, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls - PUT, PATCH, POST, DELETE.

For accessing current user, you can create API endpoint /users/current with

class CurrentUserView(APIView):
    def get(self, request):
        serializer = UserSerializer(request.user)
        return Response(serializer.data)

Upvotes: 3

Related Questions