I trying to make login page and home page with django and angular, it logged in well, but once i try to retrieve the logged in user from angular it shows me 403 (Forbidden)

but it works fine in postman, it'll retrieve the logged in information

I tried this below code, i expected to show me the logged in user, but it shows 403 error message. and it doesnt show the jwt on my web browser developer tool Application, it looks like it has not been stored. it logged in successfully from frontend and will show the token(JWT) with console.log , but when i try to use the jwt for another page it shows me 403 error.

my server side - django:

this what im trying to retrieve, but shows the error

class UserView(APIView):
    def get(self,request):
        token = request.COOKIES.get('jwt')
        print(token) # this will retrieve null when i send request from angular, but retrieve the token when i send the request with postman

        if not token:
            raise AuthenticationFailed('UnAuthorized user!')        
        try:
            payload = jwt.decode(token,'secret',algorithms=['HS256'])
        except jwt.ExpiredSignatureError:
            raise AuthenticationFailed('Expired Session')        
        user = User.objects.get(id=payload['id'])
        serializer = UserSerializer(user)
        return Response(serializer.data)

my urls.py

urlpatterns = [
    path('api/login/',LoginView.as_view(),name='login'),
    path('api/users/',UserView.as_view(),name='user'),
]

and my settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders',    
    'project'
]

CORS_ALLOW_CREDENTIALS = True

CORS_ORIGIN_WHITELIST = [
    'http://localhost:4200',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',    
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True

i'm using pyjwt==2.8, djangorestframework==3.14, django-cors-headers==4.3.1, and django==4.2

here is my client side-angular, version =17.0.7 home.component.ts

  message = ''

  constructor(
    private http:HttpClient
  ){

  }
  ngOnInit(): void {
    this.http.get('http://localhost:8000/api/users/', {withCredentials: true}).subscribe(
      (res: any) => {
        this.message = `Hi ${res.name}`;
      },
      err => {
        this.message = 'You are not logged in';
      }
    );
  }}

and when i try use localStorage.getItem('jwt') it shows me

ERROR ReferenceError: localStorage is not defined

Thank you for your help

0

There are 0 answers