【问题标题】:Node - passport-http how to return json response if failed节点-passport-http如果失败如何返回json响应
【发布时间】: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


    【解决方案1】:

    请参阅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);
    };
    

    【讨论】:

    • 是的,我的问题是我实现它的方式没有访问 res 和 req。那么你将如何解决这个问题?
    • 我不明白你的意思“确实可以访问 res 和 req”,你已经可以在中间件中访问它们 this.guard = (req, res, next) =&gt; {...}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 2020-02-06
    • 2013-08-22
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    相关资源
    最近更新 更多