Search code examples
javascriptpythondjangohttpaxios

Django Rest Framework: HTTP 401 Unauthorized error


I am django rest framework jwt token package. For some reason, it is not receiving the token credentials. I am sure I am using axios in the correct format to store a token. I am unsure if the error is frontend or backend. I am using pythonanywhere in the backend.

Settings.py

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}

Frontend

handleFormSubmit(e) {
    e.preventDefault();

    if (this.getValidationState() == 'error') {
      this.setState({invalidFormSubmit: true})
      return;
    }

    axios.defaults.headers.common['Authorization'] = 'Token ' + this.props.auth.getToken();
    console.log(this.props.auth.getToken());

    var capsule = new MyForm();
    capsule.append("user", this.state.userUrl);
    capsule.append("dateToPost", this.state.dateToPost.format());
    capsule.append("image", this.state.image);
    capsule.append("caption", this.state.caption);
    capsule.append("dateToDelete", this.state.dateToPost.add(1, "d").format());

    axios.post(this.props.auth.domain + "/snapcapsule/", capsule)
    .then(() => {
       this.setState({redirect: true})
    }).catch(err =>{
        alert(err);
    })
  }

Error

{"detail":"Authentication credentials were not provided."}


Solution

  • token auth in settings.py

    JWT_AUTH = {
        # Authorization:Token xxx
        'JWT_AUTH_HEADER_PREFIX': 'Token',
    }
    

    the default JWT_AUTH_HEADER_PREFIX is JWT.

    JWT_AUTH_HEADER_PREFIX You can modify the Authorization header value prefix that is required to be sent together with the token. The default value is JWT. This decision was introduced in PR #4 to allow using both this package and OAuth2 in DRF.

    Another common value used for tokens and Authorization headers is Bearer.

    Default is JWT.

    Doc is here.