'How to check if a request consists of session id and csref token in the cookie in Django rest framework?
my rest_framework authentication and permission classes
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions.IsAuthenticated",
"rest_framework.permissions.IsAdminUser",
"rest_framework.permissions.AllowAny",
],
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework_simplejwt.authentication.JWTAuthentication",
"rest_framework.authentication.SessionAuthentication",
"rest_framework.authentication.BasicAuthentication"
),
login view
class UserLoginView(generics.RetrieveAPIView):
"""
View for a user to login through 1FA.
The view provides a post request that accepts a email and password.
Returns a jwt token as a response to authenticated user.
"""
throttle_scope = "login"
permission_classes = (permissions.AllowAny,)
serializer_class = UserLoginSerializer
def post(self, request):
"""
POST request to login a user.
"""
#if session key is not present then create a session for the user
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
if not request.session.session_key:
request.session.save()
return Response("logged in")
In my login view if user credentials are valid i am creating a user session if not created yet. For all other requests i need to ensure that user has a active session i.e. a session id in the cookie and csrf token to secure the application , is there method provided by rest framework to do that or i need to write my own permission classes for the views
Solution 1:[1]
Documentation url:
https://www.django-rest-framework.org/api-guide/authentication/#setting-the-authentication-scheme
- Add this:
authentication_classes = [SessionAuthentication, BasicAuthentication]
DRF behind the scene uses authentication backend in (authentication_classes list) one after another and try to call a method authenticate with provided credentials
- remove this part
if not request.session.session_key:
request.session.save()
SessionAuthentication backend does that for you
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | user13277854 |