0

I'm new to NodeJS and developing an API using it, I want the API to be authenticated with an API token method (only people with a token stored in DB, created through a specific encryption should be able to access the API resource.)

I'm using an SQL server, NodeJS, and the Express framework.

Please guide me in what I should use to authenticate the API request.

Thanks in advance.

1

3 Answers 3

2

You could use passport.js with JwtStrategy. This is the idea:

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 (using 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'

});

First, you must login with POST /login { username: 'john', password: '1234' }. That will return a JSON with the jwt token like this:

{ token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c' }

In subsequent requests, you must send a header Authorization with value: Bearer {token} so passportjs and JwtStrategy can authorize the request.

Hope it helps!

NOTE: I have not tested code above, it just shows the approach.

Sign up to request clarification or add additional context in comments.

Comments

0

For API Authenication use Passport JS

Comments

0

You can use json web token (jwt) for API authorization. There are node modules available which provides authentication functionality and you can simply use.

Please have a look at this article: https://medium.freecodecamp.org/securing-node-js-restful-apis-with-json-web-tokens-9f811a92bb52?gi=89f3f4d89dfd

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.