我在后端使用 djoser 的身份验证。当我通过具有内容类型和授权标头的邮递员在“/account/me/”发出获取请求时,我得到了正确的响应。但是当我尝试从我的角度客户端执行相同的请求时,我得到401 Unauthorized("detail":"未提供身份验证凭据。")错误。
这是我的角度服务
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.
![enter image description here](https://i.stack.imgur.com/e94ZL.png)
有什么解决办法吗?
在执行预检请求时,自定义标头例如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',
)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)