【发布时间】:2018-06-27 01:01:52
【问题描述】:
我正在使用 Node/Express/Typescript/Passport 构建 API
我有一个需要受“基本身份验证”保护的端点,它采用用户名和密码将其转换为 base64 并将其添加到授权标头中。
我已经使用了以下依赖 PassportJS,具体来说。 http://www.passportjs.org/docs/basic-digest/
但是,身份验证失败时的响应并不理想。我已经构建了一个 api,因此如果此身份验证失败,我希望它返回一个 json 响应,而不是它在下面显示的内容。
回应:
<!DOCTYPE html> <html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>error</pre>
</body> </html>
护照
import { Passport } from 'passport';
import { BasicStrategy } from 'passport-http';
import Config from './../config/config';
class PassportMiddleware {
public passport: any;
public config: any;
constructor() {
this.passport = new Passport();
this.config = new Config();
this.basicStrategy();
}
private basicStrategy(): void {
this.passport.use(new BasicStrategy( (username, password, done) => {
const credentials = this.config.hs;
if (credentials.username !== username && credentials.password !== password) {
// Needs to be json response error res.status(400).json('error');
return done("error", false)
}
return done(null, null);
}));
}
}
export default new PassportMiddleware().passport;
路由器
import { Router } from 'express';
import TransactionController from './transaction.controller';
import PassportMiddleware from './../../middleware/passport.middleware';
class TransactionRouter {
router: Router;
controller: any;
guard: any;
constructor() {
this.router = Router();
this.controller = new TransactionController();
this.guard = PassportMiddleware.authenticate('basic', { session: false });
this.router.post('/', this.controller.store.bind(this.controller));
this.router.get('/:id', this.controller.show.bind(this.controller));
this.router.post('/callback', this.guard, this.controller.callback.bind(this.controller));
}
}
export default new TransactionRouter().router;
控制器
import { Request, Response, NextFunction } from 'express';
import Config from './../../config/config';
class TransactionController {
public config: any;
constructor() {
this.config = new Config();
}
public async callback(req: Request, res: Response): Promise<any> {
}
}
export default TransactionController;
【问题讨论】:
标签: node.js express passport.js