Lecture07 JWT
Lecture07 JWT
- JWT is very popular for handling authentication and authorization via HTTP.
- HTTP is a stateless protocol, which means that an HTTP request does not maintain state. The
server does not know about any previous requests that were sent by the same client.
Session-based authentication
JWT
When the client sends an authentication request to the server, it
will send a JSON token back to the client, which includes all the
information about the user with the response.
Structure of a JWT
- The first section of the JWT is the header, which is a Base64-encoded string
- The second section is the payload that contains the JSON object that was
- The final section is the signature of the token. This is generated by hashing the string
same client.
Advantage of Using JWT over Traditional Methods
- JWT can contain all of the information about the user itself, unlike the
session-based authentication.
JWT with Express
npm init –y
npm i express
npm i –d nodemon
npm i jsonwebtoken
JWT with Express
const jwt = require('jsonwebtoken’);
const accessTokenSecret = 'youraccesstokensecret’;
app.post('/login', (req, res) => { // Read username and password from request body
const { username, password } = req.body; // Filter user from the users array by
username and password
const user = users.find(u => { return u.username === username && u.password ===
password });
if (user) { // Generate an access token
const accessToken = jwt.sign({ username: user.username, role: user.role },
accessTokenSecret);
res.json({ accessToken });
} else {
res.send('Username or password incorrect’);
}
});
JWT with Express
const authenticateJWT = (req, res, next) => {
const authHeader = req.headers.authorization;
if (authHeader) {
const token = authHeader.split(' ')[1]; jwt.verify(token,
accessTokenSecret, (err, user) => {
if (err) {
return res.sendStatus(403);
}
req.user = user;
next();
});
} else { res.sendStatus(401); } };
JWT with Express
app.get('/books', authenticateJWT, (req, res) => {
res.json(books);
});