我在前端使用 Angular 5。使用 HTTP 拦截器,如果客户端登录,它会发送一个令牌以及向我的服务器发出的任何 http 请求。我可以登录我的系统。所以 JWT 方案工作正常。
拦截器是这样的:我控制台记录令牌以确保它被添加,并且它在我的日志中正常工作。
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import {UserAuthorizationService} from "../userservice/userauthorizationservice/userauthorizationservice";
import { Observable } from 'rxjs/Observable';
@Injectable()
export class TokenInterceptor implements HttpInterceptor{
constructor(private tokenservice: UserAuthorizationService){}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{
let token = this.tokenservice.checklocalfortoken();
if(token == null){
token = this.tokenservice.checksessionfortoken();
}
if(token != null){
console.log('here is the token being sent');
console.log(token);
request = request.clone({
setHeaders: {
Authorization: 'JWT ' + token
}
});
}
return next.handle(request);
}
}
令牌方案有效,我已经测试过了。
设置已正确设置。本指南中需要完成的几乎所有事情都已完成:
http://getblimp.github.io/django-rest-framework-jwt/
转到实际视图:
class CreateSuitsuser(APIView):
permission_classes = (Issuitssuperuser,)
def post(self, request, *args, **kwargs):
serialized = CreateSuitsUserSerializer(data=request.data)
if serialized.is_valid(raise_exception=True):
data = serialized.data
...
权限类:
class Issuitssuperuser(BasePermission):
def has_permission(self, request, view):
if request.user.issuitssuperuser:
return True
return False
错误:
如果 request.user['issuitssuperuser']: TypeError: 'AnonymousUser' 对象没有属性 ' getitem ' [10/May/2018 20:36:51] "OPTIONS /api/user/suits/HTTP/1.1" 500 21855 正在执行系统检查...
但为什么呢?这不酷。我做错了什么没有让这很酷?我希望它很酷。