我已经使用打字稿编写的节点构建了一个后端api。
我正在使用护照实施基本身份验证。但是,我无法在失败时返回json响应。
我知道护照可以创建自定义回叫。 http://www.passportjs.org/docs/authenticate/。我只是在努力使用现有设置来实现它。
passport.middleware.ts
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) {
const error = {
success: false,
message: "Failed To Authenticate",
};
return done(error, false);
}
return done(null, {});
}));
}
}
export default new PassportMiddleware().passport;
transaction.router.ts
import { Router } from "express";
import TransactionController from "./transaction.controller";
import PassportMiddleware from "./../../middleware/passport.middleware";
class TransactionRouter {
public router: Router;
public controller: any;
public 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("/:id/cancel", this.controller.cancel.bind(this.controller));
this.router.post("/callback", this.guard, this.controller.callback.bind(this.controller));
}
}
export default new TransactionRouter().router;
当用户名和密码错误时,我会收到以下响应,并显示500内部错误。
> <!DOCTYPE html> <html lang="en">
> <head>
> <meta charset="utf-8">
> <title>Error</title>
> </head>
> <body>
> <pre>[object Object]</pre>
> </body> </html>
我在这里做什么?有没有办法我可以访问req,res,next来创建自定义回调?