Aug*_*sto 6 http-headers jwt passport.js angular angular7
我无法在7号角中发送正确的标题!我在后端使用护照:
"app.get('/api/users', passport.authenticate('jwt', {session: false}), (req, res, next) => {... bla bla bla...}."
Run Code Online (Sandbox Code Playgroud)
当我尝试将有效的令牌从邮递员发送到我的路径/ api /用户时,一切正常,但是当我从角度不这样做时。(*角度不显示错误!)假设“ Bearer validToken”是一个有效的令牌,这样我就发送了标头:
getAll() {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer validToke.'
});
};
return this.http.get<user[]>(`http://localhost:3000/api/users`, httpOptions);
}
Run Code Online (Sandbox Code Playgroud)
我可以从angular进行身份验证并获取Bearer令牌,一切正常,如果删除了password.authenticate('jwt',{session:false}),我可以获取用户列表。
感谢您的阅读!
我能够通过创建拦截器来解决这个问题:
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthenticationService } from '../_services/authentication.service';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add authorization header with jwt token if available
let currentUser = this.authenticationService.currentUserValue;
if (currentUser && currentUser.token) {
request = request.clone({
setHeaders: {
Authorization: `${currentUser.token}`
}
});
}
return next.handle(request);
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢
| 归档时间: |
|
| 查看次数: |
8520 次 |
| 最近记录: |