我正在使用 Node/Express/Typescript/Passport 构建 API
我有一个端点需要受到“基本身份验证”的保护,该端点需要用户名和密码将其转换为 base64 并将其添加到授权 header 中。
我具体使用了以下依赖项 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>
Passport
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;
Controller
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;
最佳答案
请参阅 http://www.passportjs.org/docs/ 中的自定义回调部分
您可以执行以下操作:(抱歉省略了类型)
// passport -> basicStrategy
// Failed authentication should not be considered as an error,
// therefore, use `null` and false to indicate a failed authentication
// and a third parameter to indicate to reason
return done(null, false, {error : 'Incorrect username or passport'});
// router
this.guard = (req, res, next) => {
PassportMiddleware.authenticate('basic', (err, user, info) => {
if (err) return next(err);
// info -> {error : 'Incorrect username or passport'}
if (!user) return res.status(401).json(info);
req.user = user;
next();
})(req, res, next);
};
关于node.js - Node - Passport-http 如果失败如何返回 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51047798/