1// index.js
2
3const express = require('express');
4const jwt = require('jsonwebtoken');
5
6const app = express();
7
8// generate token for another API to use in req.header
9app.post('/login', (req, res) => {
10 const user = {
11 id: 1,
12 username: 'abhishek',
13 email: "abhishek@gmail.com"
14 }
15 let token = jwt.sign({ user: user }, 'shhhhh');
16 res.send(token);
17})
18
19// verifyToken is a function that is used for check in API that token exist or not
20// it can be put in between n number of API to check that authoriZed user loggedin or not.
21app.get('/api', verifyToken, (req, res) => {
22 try {
23 jwt.verify(req.token, 'shhhhh', (error, authData) => {
24 if (error) {
25 res.send("not logged in")
26 }
27 res.json({
28 message: "post Created",
29 authData
30 })
31 })
32 } catch (error) {
33 res.send(error)
34 }
35})
36
37// This funtion is middleware.
38function verifyToken(req, res, next) {
39 try {
40 const bearerHeader = req.headers['authorization'];
41 if (typeof bearerHeader !== 'undefined') {
42 const bearerToken = bearerHeader.split(' ')[1];
43 req.token = bearerToken;
44 next();
45 }
46 else {
47 res.send("Not logged-in")
48 }
49 }
50 catch {
51 res.send("something went wrong")
52 }
53}
54
55app.listen(3000, () => {
56 console.log("server is runing")
57})
58
1const jwt = require("jsonwebtoken")
2
3const jwtKey = "my_secret_key"
4const jwtExpirySeconds = 300
5
6const users = {
7 user1: "password1",
8 user2: "password2",
9}
10
11const signIn = (req, res) => {
12 // Get credentials from JSON body
13 const { username, password } = req.body
14 if (!username || !password || users[username] !== password) {
15 // return 401 error is username or password doesn't exist, or if password does
16 // not match the password in our records
17 return res.status(401).end()
18 }
19
20 // Create a new token with the username in the payload
21 // and which expires 300 seconds after issue
22 const token = jwt.sign({ username }, jwtKey, {
23 algorithm: "HS256",
24 expiresIn: jwtExpirySeconds,
25 })
26 console.log("token:", token)
27
28 // set the cookie as the token string, with a similar max age as the token
29 // here, the max age is in milliseconds, so we multiply by 1000
30 res.cookie("token", token, { maxAge: jwtExpirySeconds * 1000 })
31 res.end()
32}
1function authenticateToken(req, res, next) {
2 // Gather the jwt access token from the request header
3 const authHeader = req.headers['authorization']
4 const token = authHeader && authHeader.split(' ')[1]
5 if (token == null) return res.sendStatus(401) // if there isn't any token
6
7 jwt.verify(token, process.env.ACCESS_TOKEN_SECRET as string, (err: any, user: any) => {
8 console.log(err)
9 if (err) return res.sendStatus(403)
10 req.user = user
11 next() // pass the execution off to whatever request the client intended
12 })
13}