我試圖使用express-jwt來保護我的apis。我正在使用MEAN(Angular 4)堆棧。我已經嘗試了以下代碼的很多變體,並且無法弄清楚爲什麼我無法驗證令牌。無法使用Express-jwt與MEAN堆棧驗證服務器端的令牌
下面列出的代碼返回401 Unauthorized to the client
。其他變化返回UnauthorizedError: Format is Authorization: Bearer [token]
。有沒有人看到下面的代碼有什麼問題?
服務器端代碼
在我app.ts文件我有以下幾點:
app.use('/api/volunteers/', jwt({
secret: 'test',
credentialsRequired: false,
getToken: function fromHeaderOrQuerystring (req) {
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
// console.log(req.headers.authorization.split(' ')[0] === 'Bearer')
return req.headers.authorization.split(' ')[1];
} else if (req.query && req.query.token) {
return req.query.token;
}
return null;
}
}));
問題:
- 請問這套req.user如果令牌標題是否有效?
- 我是否需要明確調用getToken()?
在我routes.ts文件我有:
app.get('/api/volunteers',
function(req, res) {
console.log('req user ' + req.user);
// auth
if (!req.user) {
return res.sendStatus(401);
}
// logic
Volunteer.find({}, (err, docs) => {
if (err) {
res.status(400).send(err);
return console.error(err);
}
res.json(docs);
});
});
注:在代碼中直接返回上方的UnauthorizedError: Format is Authorization: Bearer [token]
第一行後添加jwt({secret: 'test'}),
。
用戶模型:
import * as bcrypt from 'bcryptjs';
import * as mongoose from 'mongoose';
const userSchema = new mongoose.Schema({
username: String,
email: { type: String, unique: true, lowercase: true, trim: true },
password: String,
role: String
});
const User = mongoose.model('User', userSchema);
export default User;
用戶處理程序:
import BaseHandler from './base';
import User from '../models/user';
import * as jwt from 'jsonwebtoken';
import * as dotenv from 'dotenv';
import 'zone.js';
import 'reflect-metadata';
export default class UserHandler extends BaseHandler {
model = User;
login = (req, res) => {
this.model.findOne({ email: req.body.email }, (err, user) => {
if (!user) { return res.sendStatus(403); }
user.comparePassword(req.body.password, (error, isMatch) => {
if (!isMatch) { return res.sendStatus(403); }
// why sign with user
// why do I need test
const token = jwt.sign({user: user}, 'test');
res.status(200).json({ token: token });
});
});
};
}
客戶端代碼
我服務的一個部分:
constructor(private http: Http) {
this.headers = new Headers({ 'Content-Type': 'application/json' });
this.headers.append('authorization', localStorage.token);
this.options = new RequestOptions({ headers: this.headers });
}
getVolunteers(): Observable<Volunteer[]> {
return this.http.get('/api/volunteers', this.options)
.map((res: Response) => res.json())
.catch(handleError);
}
請問這套req.user如果頭中的令牌是有效的? 答:您需要通過userself設置req.user UnauthorizedError:格式爲授權:承載[令牌] 這個錯誤是因爲在app.ts以下行 回報req.headers.authorization.split的( '')[1]; 您必須返回包括'持票人'的整個令牌 – umar