'Http authentication from angular to DRF-simple JWT
Im trying to authenticate to a Django backend using Drf-simple-jwt from an angular front. First of all, everything works great in Postman. But I cannot get past HTTP 401 error when using the browser (Safari, Chrome).
I have set up Cord-Headers in Django:
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
'http://localhost:4200',
)
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'backOffice.apps.BackofficeConfig',
'rest_framework',
"corsheaders",
'rest_framework_simplejwt.token_blacklist',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
Here's the login call from angular :
login(user: Users) {
return this.http.post<any>(this.BASE_URL + 'api/token/', user)
.pipe(
catchError((err) => {
console.log('login error: ', err);
return throwError(err);
})
);
}
And how I call it:
authenticate() {
this.api.login(this.user).subscribe(
(data) => {
localStorage.setItem("access", data.access);
localStorage.setItem("refresh", data.refresh);
this.router.navigate(['/accueil']);
});
}
Here's a view im trying to access:
class ProductList(generics.ListCreateAPIView):
permission_classes = (IsAuthenticated,)
queryset = Products.objects.all()
serializer_class = ProductsSerializer
Im using auth0/angular-jwt to automatically append the Authorization header to each request.
I have no issues in Postman, all endpoints work fine.
But in the browser, all I get is HTTP 401.
Ive hardcoded a valid, just emitted access_token, in the headers to no avail.
I can see the Authorization: Bearer <Token> in the request, with a valid token, but still am Unauthorized.
From what I gathered it could be a cors issue, but I've set up cors header.
I would greatly appreciate any insight.
Thanks a lot.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
