How to use the jsonwebtoken.verify function in jsonwebtoken

To help you get started, we’ve selected a few jsonwebtoken examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github microsoft / BotFramework-Emulator / packages / app / main / src / server / routes / handlers / botFrameworkAuthentication.ts View on Github external
let issuer;

      if (decoded.payload.ver === '1.0') {
        issuer = usGovernmentAuthentication.tokenIssuerV1;
      } else if (decoded.payload.ver === '2.0') {
        issuer = usGovernmentAuthentication.tokenIssuerV2;
      } else {
        // unknown token format
        res.status(401);
        res.end();

        return;
      }

      try {
        (req as any).jwt = jwt.verify(token, key, {
          audience: usGovernmentAuthentication.botTokenAudience,
          clockTolerance: 300,
          issuer,

          // TODO: "jwtId" is a typo, it should be "jwtid"
          //       But when we enable "jwtid", it will fail the verification
          //       because the payload does not specify "jti"
          //       When we comment out "jwtId", it also works (because it is a typo)

          // jwtId: botId
        });
      } catch (err) {
        res.status(401);
        res.end();

        return;
github mutaimwiti / node-test-wrapper / examples / es5 / token / src / utils.js View on Github external
function decodeAuthToken(req, done) {
  var token = req.headers.authorization || '';

  if (!token) {
    return done(true);
  }

  return jwt.verify(token, SECRET, done);
}
github bleenco / morose / src / api / auth.ts View on Github external
export function decodeToken(token: string): string | object | boolean {
  let config: any = getConfig();
  try {
    let decoded = jwt.verify(token, config.secret);
    return decoded;
  } catch (e) {
    return false;
  }
}
github frandiox / vue-graphql-enterprise-boilerplate / server / src / resolvers / mutation / auth.js View on Github external
jwks.getSigningKey(header.kid, (err, key) => {
      if (err) {
        return reject(
          new AuthenticationError(
            `${invalidTokenMessage} Could not get signing key: ${err.message}`
          )
        )
      }

      jwt.verify(
        idToken,
        key.publicKey,
        { algorithms: ['RS256'] },
        (err, decoded) =>
          err
            ? reject(
                new AuthenticationError(
                  `${invalidTokenMessage} JWT verification error: ${err.message}`
                )
              )
            : resolve(decoded)
      )
    })
  })
github V-Tom / vue-blog / mods / auth / decode.js View on Github external
App.decodeByKey = function (data, keyURL, type) {
  var cert = fs.readFileSync(keyURL);
  if (type) {
    return jwt.verify(data, cert, {algorithm: type})
  } else {
    return jwt.verify(data, cert);
  }
};
github tumobi / nideshop / src / api / service / token.js View on Github external
async parse(token) {
    if (token) {
      try {
        return jwt.verify(token, secret);
      } catch (err) {
        return null;
      }
    }
    return null;
  }
github feathersjs / feathers / packages / authentication / lib / utils.js View on Github external
return new Promise((resolve, reject) => {
    if (!token) {
      return reject(new Error(`token must provided`));
    }

    if (!secret) {
      return reject(new Error(`secret must provided`));
    }

    debug('Verifying token', token);
    jwt.verify(token, secret, pick(settings, VALID_KEYS), (error, payload) => {
      if (error) {
        debug('Error verifying token', error);
        return reject(error);
      }

      debug('Verified token with payload', payload);
      resolve(payload);
    });
  });
};
github CodeCoursez / backend / src / middlewares / authentication.ts View on Github external
export async function authenticate(
  req: any,
  res: Response,
  next: NextFunction
) {
  const token = req.token;

  if (!token)
    return res
      .status(401)
      .json({ message: 'Access denied! No token provided.' });

  try {
    req.user = await jwt.verify(token, process.env.JWT_SECRET_KEY || '');
    next();
  } catch (error) {
    return res.status(400).send(error.message);
  }
}
github grand-stack / graphql-auth-directives / src / index.js View on Github external
(!req.headers.authorization && !req.headers.Authorization)
  ) {
    throw new AuthorizationError({ message: "No authorization token." });
  }

  const token = req.headers.authorization || req.headers.Authorization;
  try {
    const id_token = token.replace("Bearer ", "");
    const JWT_SECRET = process.env.JWT_SECRET;

    if (!JWT_SECRET) {
      throw new Error(
        "No JWT secret set. Set environment variable JWT_SECRET to decode token."
      );
    }
    const decoded = jwt.verify(id_token, JWT_SECRET, {
      algorithms: ["HS256", "RS256"]
    });

    return decoded;
  } catch (err) {
    throw new AuthorizationError({
      message: "You are not authorized for this resource"
    });
  }
};
github guildspeak / guildspeak-backend / server / src / utils.ts View on Github external
export async function getUserId(ctx: Context) {
  const authorization = ctx.request.get('Authorization')
  if (authorization) {
    const token = authorization.replace('Bearer ', '')
    try {
      const { userId } = jwt.verify(token, process.env.JWT_SECRET) as {
        userId: string
      }
      const exist = await ctx.prisma.$exists.user({ id: userId })
      if (!exist) throw new Error('User not found!')
      return userId
    } catch (e) {
      throw new Error(`Session error: ${e}`)
    }
  }

  throw new Error('Not authorized')
}