我正在使用登录构建应用。
用户可以登录并将令牌返回到前端。
当我将令牌发送回要验证的服务器时,问题就出现了。
我使用HttpInterceptor
将授权标头发送到服务器。
当我登录控制台时:
console.log(cloned.headers.get("Authorization"))
但是,当登录快速中间件
时,标题显示正常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'
});
}
})
答案 0 :(得分:1)
默认情况下隐藏Authorization-header。 在你的后端,你需要公开标题:
Access-Control-Expose-Headers: Authorization
请参阅此主题作为参考:
Angular 2: Get Authorization header
@Update: 对不起,误解了你的问题。 请重新检查你的第二个console.log()。您正在记录:
console.log(req.headers.authorization);
不应该
console.log(req.headers.get("Authorization"));
代替?
答案 1 :(得分:0)
以下是有关如何实施可能有助于您的案例的拦截器的一些评论:
1)拦截器需要角度版本4.3 || &GT; 强>
2)记得在我们的主app.module中提供拦截器:
/** Interceptors */
import {HttpClientModule, HTTP_INTERCEPTORS} from '@angular/common/http'; <-- notice the common in @angular/common/http
import {TokenInterceptor} from './path/to/TokenInterceptor ';
@NgModule({
imports: [
...
HttpClientModule
],
providers: [
{provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true}
],
bootstrap: [AppComponent]
})
export class AppModule { }
3)在到达端点的服务中,请务必添加新的http客户端:
import {HttpClient} from '@angular/common/http'; <-- Super important to include new HttpClient from @angular/common/http instead of old http from @angular/http...
@Injectable()
export class MyService {
constructor(private http: HttpClient ) { }
// your GET POST and other requests made with http will now have the desired header...
4)此外,编辑您的拦截器代码并添加setHeaders
:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const id_token = localStorage.getItem("id_token");
if (id_token) {
req = req.clone({
setHeaders: {
Authorization: `Bearer ${id_token}`
}
});
return next.handle(req);
}
如果您已按照此步骤操作但未显示标题,请粘贴服务和模块代码
答案 2 :(得分:0)
使用tymon / jwt laravel包来处理角度5和laravel 5后端时遇到同样的问题来处理令牌认证。
我的问题来自后端。在我的api路线中,我使用: 路线::任何(...)
当我将任意改为正确的http动词(获取,发布...)问题消失了: 路线::得到(...)
当我在chrome中检查网络面板时,后端请求被发送两次,第一次没有令牌,另一次带有令牌