node.js - Node - Passport-http 如果失败如何返回 json 响应

标签 node.js express passport.js

我正在使用 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/

相关文章:

node.js - Express.js 如何自动处理 Cache-Control?

javascript - 将查询结果传递到另一个node.js页面

node.js - 在使用 Docker 的 Jenkins Pipeline 的构建后操作中似乎无法触发 "failure"事件

node.js - 我是否实现了 NodesJS + Passport + RedisStore 的序列化和反序列化?

javascript - 在 Electron 生产模式下将SQLITE db文件存储在哪里?

node.js - 如何在 Node js 中从服务返回两个以上的值

jquery - 第二次刷新后 Passportjs 忘记登录用户

javascript - 如何正确等待 JavaScript 中异步函数的返回?

javascript - 如何为 passport.authenticate 创建可重复使用的代码?

cordova - 如何通过 Facebook 登录和 Passport.js 使用 PhoneGap