【问题标题】:401 Unatuhorized("detail":"Authentication credentials were not provided.")401 Unauthorized("detail":"未提供身份验证凭据。")
【发布时间】:2018-08-27 21:27:28
【问题描述】:

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

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());
        });
  }

这是我的网络选项卡的标题窗口的屏幕截图。

有什么解决办法吗?

【问题讨论】:

  • 您是否在请求标头中添加了必要的身份验证凭据,例如令牌?
  • 可能是您没有正确配置您的服务器。您显示的屏幕截图是用于预检请求,它不会传递自定义标头。正确响应取决于您的服务器
  • @JerinPeterGeorge 是的,我已经添加了这些标题,正如您在上面的代码中看到的那样
  • @David 你能具体说一下吗?有哪些配置?
  • 这也发生在我的情况下,原因基本上是在 tue 前端的路径末尾缺少一个正斜杠。Djanho 期望这个和角度路径在发送请求之前有这个。

标签: django angular authentication angularjs-directive django-rest-framework


【解决方案1】:

在进行预检请求时,不会包含 Authorization 等自定义标头。

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

现在,我根本不了解 django,但从这里的这个帖子来看,它看起来像是一个已知问题

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

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

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

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

【讨论】:

    猜你喜欢
    • 2018-11-28
    • 2015-02-05
    • 1970-01-01
    • 2021-10-04
    • 2023-02-03
    • 2019-04-07
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多