Issue with Database Queries in Authenticated Django API Calls despite JWT Verification
anusreesoumya opened this issue · 3 comments
Each time an authorized API call is made using a bearer token (specifically a simple JWT), a database query is executed to retrieve user details, even though JWT Authentication is supposed to eliminate the need for database validation. Could someone help me understand the reason behind these database queries and suggest a solution to avoid them while still ensuring proper authentication through JWT? Your insights would be greatly appreciated!
When making a request to a Django API with a JWT bearer token, an extra database call is initiated to retrieve user details associated with the user ID specified in the token payload. SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = 2 LIMIT 21; args=(2,); alias=default . The execution of this database query is unexpected, and I am unsure about the reason for its occurrence. Can anyone assist me in determining the cause of this DB Query?
The sample API view I tried is below:
class TestView(ViewSet):
permission_classes = (IsAuthenticated,)
def list(self, request):
return Response({'Key': 'Test '})
I didn't include any user details in the API view. However, I've noticed that the database query for user information is being generated in all API calls.
In anticipation, I appreciate your assistance.
Are you using the stateless version of the authentication? https://django-rest-framework-simplejwt.readthedocs.io/en/latest/stateless_user_authentication.html
@billpull ,No, I'm not utilizing the stateless version of authentication. Specifically, I've configured the REST_FRAMEWORK settings with the following:, REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication', )
}.
Can I use JWTStatelessUserAuthentication instead of JWTAuthentication in my project, even though I don't have multiple applications? I saw in the Simple-JWT documentation that 'JWTStatelessUserAuthentication' helps with single sign-on between separate Django apps that share the same token secret key. Is there are any specific considerations, or limitations associated with using JWTStatelessUserAuthentication in my project?
Yes, the stateless version will not perform the backend call. The backend call is simply to retrieve the User object. Django's default authentication method also does this with its session-state-backend cookie approach. Instead, the stateless approach will not make that call and utilize a custom User class that we define to return user attribute values. Please see the setting for how to override it.