jwt

- **fileName**: jwt
- **Created on**: 2024-07-16 14:55:50

installation

npm i jwt

json web token (jwt) is package using for authorization the user by making token for the user .JSON web token (JWT) is JSON Object which is used to securely transfer information over the web(between two parties). It can be used for an authentication system and can also be used for information exchange. The token is mainly composed of header, payload, signature. These three parts are separated by dots(.)

import jwt from 'jsonwebtoken';

/** 
 * description: Generate a token
 * @returns {String} token - the generated token
 * */
export const generateToken = ({
  payload = {},
  signature = process.env.TOKEN_SIGNATURE,
  expiresIn = 60 * 60 * 24 * 30, // 30 days
} = {}) => {
  const token = jwt.sign(payload, signature, {
    expiresIn: parseInt(expiresIn), 
  })
  return token;
};

/**
 * description: Verify the token check if it is valid
 * @return {Object} decoded - the decoded token
 * */
export const verifyToken = ({
  token,
  signature = process.env.TOKEN_SIGNATURE
} = {}) => {
  const decoded = jwt.verify(token, signature);
  return decoded;
};


the main types of token ( header, payload, Signature) :

 {
    "typ":"JWT", // type of hash
    "alg":"HS256" // the algorathom hash name
 }

payload

{
     "userId":"b07f85be-45da",
     "iss": "https://provider.domain.com/",
     "sub": "auth/some-hash-here",
     "exp": 153452683
 }

Signature

This is the third part of JWT and used to verify the authenticity of token. BASE64URL encoded header and payload are joined together with dot(.) and it is then hashed using the hashing algorithm defined in a header with a secret key. This signature is then appended to header and payload using dot(.) which forms our actual token header.payload.signature

for genrate token for user
import genreateToken from "./token.mjs"
const token = generateToken({
  payload: {
	id: user._id,
	name: user.username,
	email: user.email,
	admin:user.isAdmin,
	isLoggedIn: true,
  },
  expiresIn:60*30
});

***give the function the payload for user._id and name, email, admin , isLoggedIn and the expireeseIn time or not there is a default value for it if not give the expiresIn and the signature is have a default value tooo from the .env ***

for verifyToken :

const decoded = verifyToken({ token }); // decoded

and for the signature have a default value from .env file and give the token for it after split the authorization header for Bearer <token> get the token only and give it to the function to check if valid or not and if valid token return and object for the payload data if not valid return null

the auth function for the jwt :

import { verifyToken } from "../utlis/TokenGenerator.mjs";
export const isAuth = async (req, res, done) => {
	const { authorization } = req.headers;
	if (authorization == undefined) {
		return res.status(401).json({ msg: "undefined token" });
	}
	const splitAuthorization = authorization.split(" ");
	// check if the token is provided
	if (!splitAuthorization[0]?.startsWith(process.env.BARER_KEY)) {
		return res.status(401).json({ msg: "not valid barer key" });
	}
	// get the token
	const token = authorization.split(" ")[1];
	try {
		const decoded = verifyToken({ token }); // decoded
		if (decoded === null) {
			return res.status(401).json({ msg: "not valid token" });
		}
	} catch (error) {
		return res.status(400).json({ error: error });
	}
	req.jwt = decoded;
	done();
};

1- first get the authorization from the req.headers
2- check if undefined that mean not authorization token provide
3- get the token from the authorization Bearer <toke>
4- check for the Bearer style like the BARER_KEY .env value
5- check for the token using verifyToken and passing the token after split authorization first ofcourse....
6- adding the payload fromm verifyToken function if success ofcourse to the request ....

check for another way to auth the user passport.md

continue:joi.md
before:bcrypt.md