【问题标题】:Node JS API Authentication节点 JS API 身份验证
【发布时间】:2018-07-27 10:13:33
【问题描述】:

我是 NodeJS 的新手并使用它开发 API, 我希望使用 API 令牌方法对 API 进行身份验证(只有通过特定加密创建的具有存储在 DB 中的令牌的人才能访问 API 资源。)

我正在使用 SQL 服务器、NodeJS 和 Express 框架。

请指导我应该使用什么来验证 API 请求。

提前致谢。

【问题讨论】:

标签: node.js authentication


【解决方案1】:

您可以将passport.jsJwtStrategy 一起使用。思路是这样的:

mypassport.js

const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;

const opts = {
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: 'yourSecret'
};

passport.use(new JwtStrategy(opts, (payload, done) => {
    const user = findUserById(payload.id);
    if (!user) {
        return done('user not exists', null);
    }
    return done(null, user);
}));

server.js(使用 express)

require('./mypassport'); // <- initialize passport strategies

//you could also use passport with local strategy for this
app.post('login', (req, res) => {
    const username = req.query.username;
    const password = req.query.password;
    if (validLogin(username, password)) {
        const user = findUserByUsername(username);
        const jwt = createTokenWithSecret(user, 'yourSecret'); // You can use jwt-simple for this
        res.json({ token: jwt });
    } else {
        //send unauthorized
    }
});

const requireLogin = passport.authenticate('jwt');
app.get('/something', requireLogin, (req, res) => {

    //here, user is authenticated and available in 'req.user'

});

首先,您必须使用POST /login { username: 'john', password: '1234' } 登录。这将返回一个带有 jwt 令牌的 JSON,如下所示:

{ token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c' }

在后续请求中,您必须发送标头Authorization,其值为:Bearer {token},以便passportjsJwtStrategy 可以授权请求。

希望对你有帮助!

注意:我没有测试上面的代码,它只是展示了方法。

【讨论】:

    【解决方案2】:

    对于 API 身份验证,请使用 Passport JS

    【讨论】:

      【解决方案3】:

      您可以使用 json web token (jwt) 进行 API 授权。有可用的节点模块提供身份验证功能,您可以简单地使用。

      请看这篇文章:https://medium.freecodecamp.org/securing-node-js-restful-apis-with-json-web-tokens-9f811a92bb52?gi=89f3f4d89dfd

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-17
        • 1970-01-01
        • 1970-01-01
        • 2013-08-02
        • 2020-10-11
        • 1970-01-01
        • 2020-09-26
        • 2018-12-02
        相关资源
        最近更新 更多