jazzband / django-rest-knox

Authentication Module for django rest auth
MIT License
1.17k stars 213 forks source link

When I get the token for a user, that particular user is getting logged in. #211

Closed Akshay-Prakash closed 4 months ago

Akshay-Prakash commented 4 years ago

I have the following structure where a single project has an api app which serves RestAPIs, and a web app which makes HTTP requests to those RestAPIs. The problem is if I get the token of a particular user, that user is logged in the app while I just want to get the token after the user fills login form, and include that in header for each request. The user is not logged out even if I restart browser, restart app, clear cookie/cache or open a new incognito window

Project structure Project ├── project │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── api │ ..... │ ├── models.py │ ├── urls.py------>contains url for knox auth │ └── views.py ---->uses default authentication_classes, override LoginView as mentioned here ├── templates │ └── base.html └── web_app ├── ............ ├── migrations ├── models.py ├── urls.py └── views.py---->all views authentication_classes=([SessionAuthentication])

settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'knox.auth.TokenAuthentication',
    ],
}

api>views.py overriding the login view as mentioned here

from knox.views import LoginView as KnoxLoginView

class LoginView(KnoxLoginView):
    permission_classes = (permissions.AllowAny,)

    def post(self, request, format=None):
        serializer = AuthTokenSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        login(request, user)
        return super(LoginView, self).post(request, format=None)

api>urls.py

from api.views import LoginView

urlpatterns = [
    url(r'api/auth/login', LoginView.as_view(), name='knox_login'),
    ....
]

web_app>views

@authentication_classes([SessionAuthentication])
@permission_classes([IsAuthenticated])
def home(request):
    return render(request, 'base.html')

base.html

{% if user.is_authenticated %}
 <li class="nav-item" role="presentation"><a class="nav-link" href="#">{{ user.username }}</a></li>
{% else %}
 <li class="nav-item" role="presentation"><a class="nav-link" href="#">Register</a></li>
 <li class="nav-item" role="presentation"><a class="nav-link" href="#">Log in</a></li>
 {% endif %}

I'am not storing the token anywhere in session/cookies Any ideas how to solve this issue?

Akashutreja commented 4 years ago

Hi @Akshay-Prakash To log out a user after login you can use its built-in logout method.

url(r'logout/', knox_views.LogoutView.as_view(), name='knox_logout'),

By hitting the above URL your token will get deleted. and by hitting login you must get a token in response which you can use to authentication another request.