Pawan Kumar
Pawan Kumar

Reputation: 49

Token based authentication using Authentication header giving 403 forbidden error

I have the following code in my react app:

I am sending an update request to rest backed which requires a user to be authenticated to perform PUT/POST/DELETE requests.

const update = (e) => {
  e.preventDefault()
  const formData = new FormData(form.current);
  console.log('Token ' + localStorage.getItem("token")) // valid token
  const requestOptions = {
    method: 'PUT',
    headers : {
      // 'Authorization': 'Basic ' + btoa('user:password') // basic authentication works
      "Authorization": 'Token ' + localStorage.getItem("token"),
    },
    body: formData
  };
    
  fetch(url, requestOptions)
    .then(async response => {
      const data = await response.json();
      if(!response.ok){
        const error = (data && data.message ) || response.status;
        return Promise.reject(error)
      }
      alert('member updated')
      history.push("/members")
    })
    .catch(error => console.error('Some error ', error))
  }

Unfortunately, I'm getting these in console logs:

PUT http://localhost:8000/uskindia/56/ 403 (Forbidden)
Some error  403

And this in backed logs:

Forbidden: /uskindia/56/
[... *:*:*] "PUT /uskindia/56/ HTTP/1.1" 403 58

Trying to solve this for the last 24 hours but not getting it right.

From various tries, it seems like:

Upvotes: 1

Views: 1556

Answers (2)

Pawan Kumar
Pawan Kumar

Reputation: 49

There was a typo in settings.py

# Earlier
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASS': [
        'rest_framework.authentication.TokenAuthentication',
    ],
# ....
}

# Changed to 
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
# ...
}

Thanks to Blog by Vitor Freitas

which made it clear that, if response contains WWW-Authenticaate:Token then it means Token authentication was working.

As this was missing in my case, so I started all over setting REST_FRAMEWORK settings from scratch and found the root cause of issue.

Upvotes: 0

erfanmorsali
erfanmorsali

Reputation: 165

if you are using djangorestframework for backend you must send token with this format :

"Authorization": 'Bearer ' + localStorage.getItem("token"),

use Bearer instead of token.

Upvotes: 1

Related Questions