Sunday, 26 August 2018

JWT authentication

get token from JWT.sign

if token is not included in authorization, post request is denied

if token is validated by JWT.verify, post request gets data back

toke expires after the period in JWT.sign expireIn, post request is rejected.



1. install postman https://www.getpostman.com/
2. npm init, entry point app.js
3. npm install express jsonwebtoken
4. npm install -g nodemon
5. create app.js
6. send post request to localhost:5000/api/login with postman to get token
7. send post request to localhost:5000/api/posts with token in authorization header

app.js

const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();

app.get('/api', (req, res) => {
    res.json({
        message: 'welcome to the api'
    });
});

app.post('/api/posts', verifyToken, (req, res) => {
    jwt.verify(req.token, 'secretkey', (err, authData) => {
        if (err) {
            res.sendStatus(403);
        } else {
            res.json({
                message: 'post created.',
                authData
            });
        }
    });
    res.json({
        message: 'post created.'
    });
});

app.post('/api/login', (req, res) => {
    //mock user
    const user = {
        id: 1,
        username: 'brad',
        email: 'brad@gmail.com'
    }

    jwt.sign({ user }, 'secretkey', { expiresIn:'30s' }, (err, token) => {
        res.json({ token });
    });
});

//format of token
//authorization: bearer <access_token>

function verifyToken(req, res, next) {
//get auth header value
    const bearerHeader = req.headers['authorization'];

    //check if bearer is undefined
    if (typeof bearerHeader !== 'undefined') {
        //split at the space
        const bearer = bearerHeader.split(' ');
        //get token from array
        const bearerToken = bearer[1];
        //set the token
        req.token = bearerToken;
        //next middleware
        next();
    }
    else {
        //forbidden
        res.sendStatus(403);
    }
}

app.listen(5000, () => console.log('server started on port 5000'));


reference:
https://www.youtube.com/watch?v=7nafaH9SddU
https://jwt.io/introduction/

No comments:

Post a Comment