Last edit at: May 30, 2021 4:34 PM Status: Learning Tag: API, Auth
- Learn how to run a express api server
- Learn JWT
- Know how authentication work by JWT
- import express
- add route →
app.get
/app.post
... - mount server on port →
app.listen(3000)
- apply middleware →
app.use
- 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)
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
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)
Build a simple express api server to allow user to register/login and display user info
- express: main server
- jsonwebtoken: handle jwt related feature
- bcrypt: hash user password
- express-validator: to validate request body
use nodemon
to run index.js
and test the api:
This extension Rest Client, can use along with a requests.rest
file
will be clearer to show how to use the app
api to receive email
, password
and name
-
⚠️ blocker:req.body undefined
Solution1:
install body-parser reference: https://akhromieiev.com/req-body-undefined-express/
Solution2:
simply use middleware
app.use(express.json())
Validation:
- request body format
- whether user already exist
if invalid → return error messages
if valid → Encrypt password → create a new user
Get the email and password, check whether user registered
return JWT token when user login successfully
-
⚠️ blocker: encrypted password not matchedwhen we encrypt the identical string with this
encrypt
function, it return different hashSolution:
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
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
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> }
https://www.youtube.com/watch?v=mbsmsi7l3r4&ab_channel=WebDevSimplified