[英]NodeJs :Error 401(Unauthorized), passport, jwt. MEAN stack, node, express, angular, mongoose
我是 Node 的新手,所以我希望對你有所幫助......我在MEAN stack app 工作,並試圖通過passport-jwt 實現身份驗證系統。 注冊/登錄 forms 和頁面正常工作,我可以訪問令牌並將其存儲在本地存儲中但是當我嘗試在登錄后訪問用戶配置文件時出現以下錯誤:401(未授權) 。
似乎我沒有通過 postman 將令牌正確發送到服務器,因為使用本地存儲的令牌一切正常。
這是我的代碼..
錯誤
HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: 'Unauthorized', url: 'http://localhost:3000/users/profile', ok: false, …}
error: "Unauthorized"
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message: "Http failure response for http://localhost:3000/users/profile: 401 Unauthorized"
name: "HttpErrorResponse"
ok: false
status: 401
statusText: "Unauthorized"
url: "http://localhost:3000/users/profile"
護照.js
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../models/user');
const config = require('./db.config');
module.exports = function(passport) {
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme("jwt")
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
User.getUserById(jwt_payload._id, (err, user) => {
if(err) {
return done(err, false);
}
if(user) {
return done(null, user);
}
else{
return done(null, false);
}
})
}))
}
節點路由.js
router.get('/profile', passport.authenticate('jwt', {session: false}), (req, res, next) => {
res.json({user: req.user})
});
授權服務
getProfile() {
let headers = new HttpHeaders();
this.loadToken();
headers.append('Authorization', this.authToken);
headers.append('Content-Type', 'application/json');
return this.http.get('http://localhost:3000/users/profile', {headers: headers})
.pipe(map((res: any) => res));
}
loadToken() {
const token = localStorage.getItem('id_token');
this.authToken = token;
}
Profile.ts在這里我調用 auth 服務然后得到錯誤
constructor(private auth: AuthService) { }
ngOnInit() {
this.auth.getProfile().subscribe(profile => {
this.user = profile.user;
},
err => {
console.log(err);
return false;
});
}
提前致謝:)
找到了解決方案。我在發布這個問題之前花了很多時間,所以對於遇到同樣問題的人來說,最好的方法是創建一個攔截器:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const idToken = localStorage.getItem('id_token');
if(idToken) {
const cloned = req.clone({
headers: req.headers.set('Authorization', idToken)
});
return next.handle(cloned)
} else {
return next.handle(req);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.