问题描述
我尝试使用有角的注入器添加不记名令牌
有很多不同的代码,我尝试了其中的一些,它们都导致相同的问题
没有发送承载与请求
在下图中,我在 clone / headers.set 处停了下来,但是即使经过这一步,标题映射仍然为空
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(
private appService: AppService
) { }
intercept(request: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {
// add auth header with jwt if user is logged in and request is to the api url
let authentication: Authentication = this.appService.getUserSession();
const isLoggedIn = authentication && authentication.token;
const isApiUrl = request.url.startsWith(environment.apiUrl);
//------------------------------------- add id's
let body = request.body;
if(!body)
{
body={};
}
body['clientId'] = environment.clientId;
body['clientSecret'] = environment.clientSecret;
request = request.clone({
body: body
});
//--------------------------------------- add jwt
if(authentication)
{
request = request.clone(
{
headers: request.headers.set('Bearer',authentication.token)
}
);
}
return next.handle(request);
}
}
感谢您帮助我完成这一任务
解决方法
根据clone()方法原型,您获得了一个对象属性来设置标头(名为setHeaders)
setHeaders?: {
[name: string]: string | string[];
};
您应该执行以下操作
request = request.clone(
{
setHeaders: {
Authorization: `Bearer ${authentication.token}`
}
}
);