Js: Refresh and Acess Token logic [closed]

42
November 26, 2020, at 06:40 AM
Closed. This question needs to be more focused. It is not currently accepting answers.

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed yesterday.

Improve this question

I am trying to make an authentication system with refresh token, auth token and put the tokens in a blacklist when expired and / or when it is logged out.

I have a login route, where I will generate the access token, and check if there is a refresh token with a certain sub, if not, I will create this token and add it to the redis:

helpers functions:

export const getRedisKey = async(key) => {
  return new Promise((resolve,reject) => {
    redis.get(refreshToken.matricula, (err, data) => {
      if (err) reject(err);
      if (data !== refreshToken) reject(new Error(`Invalid Token`));
      resolve(data);
    });
  })
}
export const encode = (args, secret, options) => {
  return jwt.sign(args, secret, options);
};
export const decode = (args, secret) => {
  const decoded = jwt.verify(args, secret);
  if (!decoded) {
      throw new Error("Invalid Token");
  }
  return decoded;
};
export const isTokenExpired = (decodedToken) => {
  if (typeof decodedToken.exp !== 'undefined' && decodedToken.exp < now) {
    throw new Error(`token expired: ${JSON.stringify(decodedToken)}`);
  }
  if (typeof decodedToken.nbf !== 'undefined' && decodedToken.nbf > now) {
    throw new Error(`token expired: ${JSON.stringify(decodedToken)}`);
  }
  return decodedToken;
};
export const getAcessToken = (
  props,
  payload,
) => {
  if (!authConfig.secret) throw new Error(`Invalid public key`);
  const token = encode(payload, authConfig.Authsecret, {
    subject: props.sub,
    expiresIn: authConfig.tokenExpiryTimeInSeconds,
  });
  return token;
};
export const getRefreshToken = async (matricula) => {
  if (!authConfig.secret) throw new Error(`Invalid public key`);
  const hasValidRefresh = await this.getRedisKey(matricula)
  if(isTokenExpired(hasValidRefresh)) return hasValidRefresh
  const refreshToken = encode({}, authConfig.Refreshsecret, { expiresIn: '30d' });
  const redis = container
    .resolve('bootstrap')
    .getRedisServer()
    .getClient();
  return new Promise((resolve,reject) => {
    redis.set(matricula, refreshToken, 'EX', 720 * 60 * 60, (err,result) => {
      if(err) reject (err)
      resolve(refreshToken)
    })
  })
};

endpoint:

app.post('/login', function (req, res) {
  const user = { matricula: 1 }
  const accessToken = await getAcessToken(user.matricula)
  const refreshToken = await getRefreshToken(user.matricula)
  if(!acessToken) return res.status(403).json({message:'Invalid Acess Token'})
  if(!refreshToken) return res.status(403).json({message:'Invalid Acess Token'})
  return res.status(200).json({acessToken,refreshToken,user})
})

I would like to know if doing this at login compromises security, or is it a logical failure? Why I thought: if a refresh token already exists and it is valid, there is no reason to create another one. Or when logging in should I create a new refresh token, and remove the old token to a blacklist? Could anyone help me with this? I have doubts about how my blacklist could be.

READ ALSO
How to format data to correctly decrypt hex strings in CryptoJS

How to format data to correctly decrypt hex strings in CryptoJS

I have a TCP server that is receiving information via direct IPI am receiving this information encrypted in AES-128-CBC

50
How cancel Timeout inside object

How cancel Timeout inside object

I have the following code:

32
Google Drive API can not upload file into specific folder

Google Drive API can not upload file into specific folder

I have a unlimited storage google drive account from my school account, so I shared drive with my main google account, I want to use apis of google drive to upload video to that shared drive by an file input formThis is where i want to store the file:

27
How to insert json object inside nested object in a document based on nested object UUID

How to insert json object inside nested object in a document based on nested object UUID

I am working on a small project and I am stuck from last month and looking for an exact query to update my document at the exact location

31