401 Unatuhorized(“详细信息":“未提供身份验证凭据.") [英] 401 Unatuhorized("detail":"Authentication credentials were not provided.")

查看:35
本文介绍了401 Unatuhorized(“详细信息":“未提供身份验证凭据.")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在后端使用 djoser 的身份验证.当我通过带有内容类型和授权标头的邮递员在/account/me/"处发出获取请求时,我得到了正确的响应.但是,当我尝试从我的 Angular 客户端执行相同的请求时,我收到 401 Unatuhorized("detail":"Authentication credentials are not provided.") 错误.这是我的角度服务

import { Injectable } from '@angular/core';从../../../utils/urls"导入{homeUrls};从@angular/http"导入 {Http, RequestOptions, Headers Response};从@angular/common/http"导入 {HttpHeaders,};@Injectable()导出类 AdsService {私有标题 = 新标题();私人令牌:字符串;构造函数(私有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('授权', '令牌' + this.token);this.headers.append('Content-Type', 'application/json');控制台日志(this.headers);this.getMe();}getMe(): Promise

有什么解决办法吗?

解决方案

在执行预检请求时,将不包含诸如 Authorization 之类的自定义标头.

因此,如果您的服务器只希望经过身份验证的用户执行 OPTIONS 请求,那么您最终总是会收到 401 错误(因为标头永远不会被传递)

现在,我根本不知道 django,但从这里的线程来看,它看起来像是一个已知问题

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

也许尝试建议的解决方法,即使用自定义权限检查器而不是使用 django rest 框架的默认值

解决方法(来自上面的线程)

# myapp/permissions.py从 rest_framework.permissions 导入 IsAuthenticated类 AllowOptionsAuthentication(IsAuthenticated):def has_permission(self, request, view):如果 request.method == 'OPTIONS':返回真返回 request.user 和 request.user.is_authenticated在 settings.py 中:REST_FRAMEWORK = {'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework.authentication.TokenAuthentication',),'DEFAULT_PERMISSION_CLASSES':('myapp.permissions.AllowOptionsAuthentication',)}

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?

解决方案

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',
    )
}

这篇关于401 Unatuhorized(“详细信息":“未提供身份验证凭据.")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆