我在后端使用djoser的身份验证。当我在" / account / me /"通过post-person with content-type和Authorization header我得到了正确的回复。但是当我尝试从我的角度客户端做同样的请求时,我得到 401 Unatuhorized("详细信息":"未提供身份验证凭据。")错误。 这是我的角色服务
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());
});
}
任何解决方案?
答案 0 :(得分: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',
)
}