0

I've been struggling for over a week with this issue. This is definitely an authentication problem. I implemented social google login with dj-rest-autj, all-auth and simple JWT. Credential flow is, first, getting access_token from google which is done in frontend. Second, sendind a request to an endpoint 'api/user-google' with the access_token, which returns JWT access_token and refresh_token, which is working fine. Finally sending a request to get user detail, but returned the error message.

Here is the request to get user detail.

await axios.get( `/api/user/${UID}`,{
                    withCredentials: true,
                    headers: {
                    "Authorization": 'JWT ' + `${access_token}`,
                    "Content-Type":"aplication/json"
                    }
                })

below are relevant source codes.

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'user',

    'rest_framework.authtoken',
    'django.contrib.sites',
    'dj_rest_auth',
    'dj_rest_auth.registration',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',


    'rest_framework',
    'rest_framework.authtoken'
]

# allauth google provisder config
SOCIALACCOUNT_PROVIDER = {
    'google': {
        'SCOPE': [
            'profile',
            'email'
        ],
        'AUTH_PARAMS': {
            'access_type': 'online'
        },
    }
}
SOCIALACCOUNT_EMAIL_VARIFICATION = 'none'
SOCIALACCOUNT_EMAIL_REQUIRED = False

# dj-rest-auth config
SITE_ID = 1
JWT_AUTH_SECURE = True
REST_USE_JWT = True
REST_AUTH_SERIALIZER = {
    'USER_DETAILS_SERIALIZER' :'user.serializers.UserSerializer',
}

JWT_AUTH_COOKIE = 'access_token'
JWT_AUTH_REFRESH_COOKIE = 'refresh-token'

# auth user model confi
AUTH_USER_MODEL = 'user.User'

# simple_JWT config
SIMPLE_JWT = {
    'AUTH_HEADER_TYPES': ('JWT'),
    'ACCESS_TOKEN_LIFETIME': timedelta(days=7),
    'ROTATE_REFRESH_TOKENS' : True,
    'BLACKLIST_AFTER_ROTATION': True,
    'UPDATE_LAST_LOGIN': True,
    'USER_ID_FIELD': 'UID',
    'USER_ID_CLAIM': 'user_id'
}

# rest framework config
REST_FRAMEWORK = {
    'DEFAULT_AUTENTICATION_CLASSES' : (
        'dj_rest_auth.jwt_auth.JWTCookieAuthentication',
    ),
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],
    'DATETIME_FORMAT': "%Y-%m-%d %H:%M",
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE':8,
}

user/urls.py

from django.urls import path
from user.apis import UserList, GoogleLogin, UserDetail


urlpatterns = [
  path('user/', UserList.as_view()),
  path('user-google/', GoogleLogin.as_view()),
  path('user/<UID>', UserDetail.as_view()),
]

user/views.py

class GoogleLogin(SocialLoginView):
    adapter_class = GoogleOAuth2Adapter
    client_class = OAuth2Client


class UserDetail(generics.RetrieveUpdateAPIView ):
    pagination_class = None
    queryset = User.objects.all()
    serializer_class = UserStrageSerializer
    lookup_field = 'UID'

user/serializers.py

class UserSerializer(serializers.ModelSerializer):


    class Meta:
        model = User
        fields = "__all__"

    def create(self, validated_data):
        user = User.objects.create_user(
            validated_data["username"],
            validated_data['email'],
            validated_data['password']
        )
        return user

core.urls.py

from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls), 
    path('api/',include('user.urls')),
    path('api/auth/',include('dj_rest_auth.urls')),
    path('api/auth/registration/',include('dj_rest_auth.registration.urls')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        path('__debug__/', include(debug_toolbar.urls)),
    ] + urlpatterns

My understanding is that

'DEFAULT_AUTENTICATION_CLASSES' : (
        'dj_rest_auth.jwt_auth.JWTCookieAuthentication',
    ),

the above in settings means if request headers include access_token, the user will be isAuthenticated which trigger the 'rest_framework.permissions.IsAuthenticated' like below

'DEFAULT_PERMISSION_CLASSES' : [
        'rest_framework.permissions.IsAuthenticated'
    ],

So hitting endpoint without access_token returns error "Authentication credentials were not provided", but with access_token should return values from DB, but it is not like this in my case.

any suggestion, please?

** If I set authentication_classes into UserDetail view directory, returns the expected data.

from dj_rest_auth.jwt_auth import JWTCookieAuthentication as JWT

class UserDetail(generics.RetrieveUpdateAPIView ):
    pagination_class = None
    queryset = User.objects.all()
    authentication_classes = ([JWT])  #added
    serializer_class = UserStrageSerializer
    lookup_field = 'UID'

but this doesn't solve the isAthenticated problem.

Tw1682
  • 1
  • 1

0 Answers0