我正在使用登录构建应用程序 .
用户可以登录并将令牌返回到前端 .
当我将令牌发送回服务器进行验证时,问题就出现了 .
我正在使用 HttpInterceptor
将Authorization标头发送到服务器 .
当我登录控制台时:
console.log(cloned.headers.get("Authorization"))
但是,当登录快速中间件时, Headers 显示正常
console.log(req.headers.authorization);
我得 undefined
以下是来自网络选项卡的请求标头,如您所见,没有授权
拦截器:
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor() { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const id_token = localStorage.getItem("id_token");
if (id_token) {
const cloned = req.clone({
headers: req.headers.set("Authorization", "Bearer " + id_token)
});
// console.log(cloned)
console.log(cloned.headers.get("Authorization"))
return next.handle(cloned);
}
else {
return next.handle(req);
}
}
}
表达:
router.use('/edit', function(req, res, next) {
console.log(req.headers.authorization);
const checkIfAuthenticated = expressJwt({
secret: RSA_PUBLIC_KEY
});
if (checkIfAuthenticated) {
return res.status(401).json({
title: 'Not Authorised',
error: 'You are not authorised'
});
}
})
3 回答
默认情况下隐藏Authorization-header . 在你的后端你需要公开 Headers :
请参阅此主题作为参考:
Angular 2: Get Authorization header
@Update:对不起,误解了你的问题 . 请重新检查你的第二个console.log() . 你正在记录:
不应该这样
代替?
以下是有关如何实施可能有助于您的案例的拦截器的一些评论:
1) Interceptors require angular version 4.3 || >
2) Remember to provide the interceptor in our main app.module:
3) In your service that reaches the endpoint, make sure to add the new http client:
4) Also, edit your interceptor code and add setHeaders :
如果您已按照此步骤操作但未显示 Headers ,请粘贴服务和模块代码
使用tymon / jwt laravel包进行角度5和laravel 5后端处理令牌认证时也会遇到同样的问题 .
我的问题来自后端 . 在我的api路线中,我使用:Route :: any(...)
当我将任何一个改为正确的http动词(get,post ...)时,问题就消失了:Route :: get(...)
当我在chrome中检查网络面板时,后端请求被发送两次,第一次没有令牌而另一次没有令牌