Node

Via JWT

$ npm init
$ npm install express --save
$ npm install express-jwt --save
$ npm install ejs --save
/** * To get started install * express bodyparser jsonwebtoken express-jwt * via npm * command :- * npm install express body-parser jsonwebtoken express-jwt --save */ //use express const express = require('express'); const port = 3000; const bodyParser = require('body-parser'); const jwt = require('jsonwebtoken'); const exjwt = require('express-jwt'); // Instantiating the express app const app = express(); // See the react auth blog in which cors is required for access app.use((req, res, next) => { res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000'); res.setHeader('Access-Control-Allow-Headers', 'Content-type,Authorization'); next(); }); // Setting up bodyParser to use json and set it to req.body app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); // Instantiating the express-jwt middleware const jwtMW = exjwt({ secret: 'keyboard cat 4 ever' }); // MOCKING DB just for test let users = [ { id: 1, username: 'test', password: 'asdf123' }, { id: 2, username: 'test2', password: 'asdf12345' } ]; // LOGIN ROUTE app.post('/login', (req, res) => { let accum = 0; const { username, password } = req.body; // Use your DB ORM logic here to find user and compare password let found = false; for (let user of users) { // I am using a simple array users which i made above if (username == user.username && password == user.password /* Use your password hash checking logic here !*/) { //If all credentials are correct do this let token = jwt.sign({ id: user.id, username: user.username }, 'keyboard cat 4 ever', { expiresIn: 129600 }); // Sigining the token res.json({ sucess: true, err: null, token }); found = true; break; } } if(!found) { res.status(401).json({ sucess: false, token: null, err: 'Username or password is incorrect' }); } }); app.get('/', jwtMW /* Using the express jwt MW here */, (req, res) => { res.send('You are authenticated'); //Sending some response when authenticated }); // Error handling app.use(function (err, req, res, next) { if (err.name === 'UnauthorizedError') { // Send the error rather than to show it on the console res.status(401).send(err); } else { next(err); } }); //define routes app.get('/', (req, res) => res.send('Hello World!')); app.get('/blah', (req, res) => res.send('Blah Blah')); app.get('/cat', (req, res) => res.send('Miau')); app.get('/cat/:name', (req, res) => { res.send('Pattern! Name: ' + req.params['name']); console.log(req.params); }); //make it a pattern app.get('/cat/:name/:comment', (req, res) => res.send('Comment!')); //make it a pattern app.get('*', (req, res) => res.send('Everything else')); //catch all other get requests //tell app where to listen app.listen(port, () => console.log(`Example app listening on port ${port}!`));

Via Passport

https://www.passportjs.org/ - Simple, unobtrusive authentication for Node.js
 

Leave a comment