401 Unatuhorized(“detail”:“Authentication credentials were not provided.”)

蹲街弑〆低调 提交于 2019-12-11 18:16:57

问题


i am using djoser's authentication at backend. when i make a get request at "/account/me/" through post man with content-type and Authorization header i am getting a correct response. But when i try to do same request from my angular client i get 401 Unatuhorized("detail":"Authentication credentials were not provided.") error. here is my angular service

import { Injectable } from '@angular/core';
import {homeUrls} from "../../../utils/urls";
import {Http, RequestOptions, Headers Response} from '@angular/http';
import {HttpHeaders,} from "@angular/common/http";
@Injectable()
export class AdsService {
  private headers = new Headers();
  private token: string;
  constructor(private http: Http) {
    this.token = localStorage.getItem('token');
    console.log("token is " , this.token);
    //this.headers = new Headers({'Content-Type': 'application/json' , 'Authorization': 'Token ' + this.token });
     this.headers.append('Authorization', 'Token ' + this.token);
     this.headers.append('Content-Type', 'application/json');
    console.log(this.headers);
    this.getMe();
  }

  getMe(): Promise<any> {
    let options = new RequestOptions({ headers: this.headers });
      return this.http.get(homeUrls.User, options)
        .toPromise()
        .then(res=> {
          console.log("user is");
          console.log(res.json());
        });
  }

and here is the screenshot of headers window of my network tab.

any solutions?


回答1:


When doing a preflight requests, custom headers such as Authorization will not be included.

So, if your server expects only authenticated users to perform an OPTIONS requests, then you'll end up always getting 401 errors (since the headers will never be passed)

Now, I don't know django at all, but from this thread here it looks like a known issue

https://github.com/encode/django-rest-framework/issues/5616

Maybe try the suggested workaround, which is using a custom permission checker instead of using django rest framework's default

Workaround (from above thread)

# myapp/permissions.py
from rest_framework.permissions import IsAuthenticated

class AllowOptionsAuthentication(IsAuthenticated):
    def has_permission(self, request, view):
        if request.method == 'OPTIONS':
            return True
        return request.user and request.user.is_authenticated

And in settings.py:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication',),
    'DEFAULT_PERMISSION_CLASSES': (
        'myapp.permissions.AllowOptionsAuthentication',
    )
}


来源:https://stackoverflow.com/questions/49360949/401-unatuhorizeddetailauthentication-credentials-were-not-provided

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!