Git Product home page Git Product logo

express-jwt's Introduction

Express JWT Auth

Last edit at: May 30, 2021 4:34 PM Status: Learning Tag: API, Auth

Goal

  1. Learn how to run a express api server
  2. Learn JWT
  3. Know how authentication work by JWT

Notes

Express Basic


Run express server

  • import express
  • add route → app.get / app.post ...
  • mount server on port → app.listen(3000)
  • apply middleware → app.use

Express route

  • get request body → req.body
  • return text → res.send('hello world')
  • return json → res.json(obj)
  • invalid request → res.status(400).send("error message") | res.sendStatus(401)

Authentication


Encrypt password

Use bcrypt to encrypt user password when user register

Due to security concerns, it is a good practice to hash the password with a strong hashing algorithm like SHA256

JWT

A JSON Web Token is a based-64 encoded hash

consists of three parts: Header, Payload and Signature

  • sign in user → jwt.sign(payload, secretKey)
  • authenticate token → jwt.verify(accessToken, secretKey)

Project

Build a simple express api server to allow user to register/login and display user info

Dev tools


Milestone


Run express server

use nodemon to run index.js

and test the api:

image

This extension Rest Client, can use along with a requests.rest file will be clearer to show how to use the app

Register API

api to receive email, password and name

Validation:

  1. request body format
  2. whether user already exist

if invalid → return error messages

if valid → Encrypt password → create a new user

image

Login API

Get the email and password, check whether user registered

return JWT token when user login successfully

  • ⚠️ blocker: encrypted password not matched

    when we encrypt the identical string with this encrypt function, it return different hash

    image

    Solution:

    we can't hash the same string and compare it by bcrypt, it'll generate a different hash even the input is identical.

    there is a bcrypt.compare to check user password according to official website

    image

once we create an access token for the user, he can pass the token through the header inside each API request: Authorization: Bearer <accessToken>

Best practice: Do not add sensitive data to the payload

Here we only put { username: [user.name](http://user.name) } as payload for demo purpose

Authenticate API

Just gonna add a simple user_info api to return user object

Before that, we need to add a authenticate token middleware for all apis need to be authorized

use jwt.verify to check the authorization is the correct token

if it's authorized, we can attach the payload into our request and go to next step

here the payload will be { username: <user.name> }

image

Reference

https://www.youtube.com/watch?v=mbsmsi7l3r4&ab_channel=WebDevSimplified

Handling Authentication in Express.js

Token Based Authentication Made Easy - Auth0

express-jwt's People

Contributors

baimao8437 avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.