jsonwebtoken#verify TypeScript Examples
The following examples show how to use
jsonwebtoken#verify.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ensureAuthenticated.ts From gobarber-api with MIT License | 8 votes |
export default function ensureAuthenticated(
req: Request,
res: Response,
next: NextFunction,
): void {
const authHeader = req.headers.authorization;
if (!authHeader) {
throw new AppError('JWT token is missing', 401);
}
const [, token] = authHeader.split(' ');
try {
const decoded = verify(token, authConfig.jwt.secret);
const { sub } = decoded as ITokenPayload;
req.user = {
id: sub,
};
return next();
} catch {
throw new AppError('Invalid JWT token', 401);
}
}
Example #2
Source File: facades-bearer-token-verify.provider.ts From loopback4-microservice-catalog with MIT License | 7 votes |
value(): VerifyFunction.BearerFn {
return async (token: string, req?: Request) => {
try {
const isRevoked = await this.revokedTokenRepository.get(token);
if (isRevoked?.token) {
throw new HttpErrors.Unauthorized('TokenRevoked');
}
} catch (error) {
if (HttpErrors.HttpError.prototype.isPrototypeOf(error)) {
throw error;
}
this.logger.error('Revoked token repository not available !');
}
let user: IAuthUserWithPermissions;
try {
user = verify(token, process.env.JWT_SECRET as string, {
issuer: process.env.JWT_ISSUER,
algorithms: ['HS256'],
}) as IAuthUserWithPermissions;
} catch (error) {
this.logger.error(JSON.stringify(error));
throw new HttpErrors.Unauthorized('TokenExpired');
}
if (
user.passwordExpiryTime &&
moment().isSameOrAfter(moment(user.passwordExpiryTime))
) {
throw new HttpErrors.Unauthorized('PasswordExpiryError');
}
return user;
};
}
Example #3
Source File: bearer-token-verifier.provider.ts From loopback4-microservice-catalog with MIT License | 6 votes |
value(): VerifyFunction.BearerFn {
return async (token: string) => {
/*
Implementing a basic JWT token decryption here
Leaving the additional security to the consumer of this application
Suggestion: to revoke these tokens put them in redis or some in-memory
database.
Use global interceptor over this to apply that check on each api.
*/
return verify(token, 'kdskssdkdfs', {
issuer: 'sf',
}) as IAuthUserWithPermissions;
};
}
Example #4
Source File: bearer-token-verifier.provider.ts From loopback4-microservice-catalog with MIT License | 6 votes |
value(): VerifyFunction.BearerFn {
return async (token: string) => {
/*
Implementing a basic JWT token decryption here
Leaving the additional security to the consumer of this application
Suggestion: to revoke these tokens put them in redis or some in-memory
database.
Use global interceptor over this to apply that check on each api.
*/
return verify(token, 'kdskssdkdfs', {
issuer: 'sf',
}) as IAuthUserWithPermissions;
};
}
Example #5
Source File: bearer-verify.provider.ts From loopback4-microservice-catalog with MIT License | 6 votes |
value(): VerifyFunction.BearerFn<SignupRequest> {
return async (token: string, req?: Request) => {
let result: SignupRequest;
try {
result = verify(token, process.env.JWT_SECRET as string, {
issuer: process.env.JWT_ISSUER,
algorithms: ['HS256'],
}) as SignupRequest;
} catch (error) {
this.logger.error(JSON.stringify(error));
throw new HttpErrors.Unauthorized('TokenExpired');
}
return result;
};
}
Example #6
Source File: bearer-token-verify.provider.ts From loopback4-microservice-catalog with MIT License | 6 votes |
value(): VerifyFunction.BearerFn {
return async (token: string, req?: Request) => {
const isRevoked = await this.revokedTokenRepository.get(token);
if (isRevoked?.token) {
throw new HttpErrors.Unauthorized(AuthenticateErrorKeys.TokenRevoked);
}
let user: AuthUser;
try {
user = verify(token, process.env.JWT_SECRET as string, {
issuer: process.env.JWT_ISSUER,
algorithms: ['HS256'],
}) as AuthUser;
} catch (error) {
this.logger.error(JSON.stringify(error));
throw new HttpErrors.Unauthorized('TokenExpired');
}
if (
user.passwordExpiryTime &&
moment().isSameOrAfter(moment(user.passwordExpiryTime))
) {
throw new HttpErrors.Unauthorized(
AuthenticateErrorKeys.PasswordExpiryError,
);
}
return user;
};
}
Example #7
Source File: bearer-token-verifier.provider.ts From loopback4-microservice-catalog with MIT License | 6 votes |
value(): VerifyFunction.BearerFn {
return async (token: string) => {
/*
Implementing a basic JWT token decryption here
Leaving the additional security to the consumer of this application
Suggestion: to revoke these tokens put them in redis or some in-memory
database.
Use global interceptor over this to apply that check on each api.
*/
return verify(token, 'test', {
issuer: 'test',
}) as IAuthUserWithPermissions;
};
}
Example #8
Source File: services-bearer-token-verify.provider.ts From loopback4-microservice-catalog with MIT License | 6 votes |
value(): VerifyFunction.BearerFn {
return async (token: string) => {
let user: IAuthUserWithPermissions;
try {
user = verify(token, process.env.JWT_SECRET as string, {
issuer: process.env.JWT_ISSUER,
algorithms: ['HS256'],
}) as IAuthUserWithPermissions;
} catch (error) {
this.logger.error(JSON.stringify(error));
throw new HttpErrors.Unauthorized('TokenExpired');
}
if (
user.passwordExpiryTime &&
moment().isSameOrAfter(moment(user.passwordExpiryTime))
) {
throw new HttpErrors.Unauthorized('PasswordExpiryError');
}
return user;
};
}
Example #9
Source File: JWT.ts From ZenTS with MIT License | 6 votes |
public static async verify(token: string): Promise<boolean> {
return new Promise((resolve) => {
const options = Object.assign({}, this.getOptions(), {
ignoreExpiration: true,
ignoreNotBefore: true,
})
verify(token, config.security.secretKey, options, (err) => {
if (err) {
return resolve(false)
}
return resolve(true)
})
})
}
Example #10
Source File: ensureAuthenticated.ts From nlw-heat-node with MIT License | 6 votes |
export function ensureAuthenticated(
request: Request,
response: Response,
next: NextFunction
) {
const authToken = request.headers.authorization;
if (!authToken) {
return response.status(401).json({
errorCode: "token.invalid",
});
}
//Bearer 8934589345djisdjfk834u25ndsfksdkf
// [0] Bearer
// [1] 8934589345djisdjfk834u25ndsfksdkf
const [, token] = authToken.split(" ");
try {
const { sub } = verify(token, process.env.JWT_SECRET) as IPayload;
request.user_id = sub;
return next();
} catch (err) {
return response.status(401).json({ errorCode: "token.expired" });
}
}
Example #11
Source File: auth.guard.ts From postgres-nest-react-typescript-boilerplate with GNU General Public License v3.0 | 6 votes |
private verifyToken = async (auth: string) => {
const authHeader = auth.split(' ');
if (authHeader[0] !== 'Bearer') {
throw new HttpException('Unauthorized token', HttpStatus.UNAUTHORIZED);
}
try {
const token = authHeader[1];
const decode = await verify(token, process.env.SECRET);
return decode;
} catch (err) {
const message = 'Token error: ' + (err.message || err.name);
throw new HttpException(message, HttpStatus.UNAUTHORIZED);
}
};
Example #12
Source File: EnsureAuthentication.ts From GoBarber with MIT License | 6 votes |
export default function ensureAuthentication(
request: Request,
response: Response,
next: NextFunction,
): void {
const authHeader = request.headers.authorization;
if (!authHeader) {
throw new AppError('JWT token is missing.', 401);
}
const [, token] = authHeader.split(' ');
try {
const decoded = verify(token, authConfig.secret);
const { sub } = decoded as ITokenPayload;
request.user = {
id: sub,
};
return next();
} catch (error) {
throw new AppError('Invalid token.', 401);
}
}
Example #13
Source File: auth.ts From gobarber-project with MIT License | 6 votes |
export default function auth(
request: Request,
response: Response,
next: NextFunction,
): void {
const authHeader = request.headers.authorization;
if (!authHeader) {
throw new AppError('JWT token is missing', 401);
}
const [, token] = authHeader.split(' ');
try {
const decoded = verify(token, authConfig.jwt.secret);
const { sub } = decoded as ITokenPayload;
request.user = {
id: sub,
};
return next();
} catch (err) {
throw new AppError('Invalid JWT token', 401);
}
}
Example #14
Source File: auth.ts From hakka with MIT License | 6 votes |
export async function parseSecureToken(
token?: string,
): Promise<CookieUserPayload | null> {
if (!token) return null
try {
return verify(token, process.env.ENCRYPT_SECRET) as any
} catch (error) {
console.error('auth error', error)
return null
}
}
Example #15
Source File: jwt.ts From umbriel with MIT License | 6 votes |
// public getUserId(): Either<InvalidJWTTokenError, string> {
// const jwtPayloadOrError = JWT.decodeToken(this.token)
// if (jwtPayloadOrError.isLeft()) {
// return left(jwtPayloadOrError.value)
// }
// const userId = jwtPayloadOrError.value.sub
// return right(userId)
// }
static decodeToken(
token: string
): Either<InvalidJWTTokenError, JWTTokenPayload> {
try {
const decoded = verify(token, auth.secretKey) as JWTTokenPayload
return right(decoded)
} catch (err) {
return left(new InvalidJWTTokenError())
}
}
Example #16
Source File: admin-gateway-service.ts From cards-against-formality-services with BSD 2-Clause "Simplified" License | 6 votes |
/**
* Verify and Decode the JWT token using the Seret.
*
* @private
* @param {string} token
* @returns {Promise<any>}
* @memberof AdminGatewayService
*/
private verifyAndDecode(token: string): Promise<any> {
return new Promise((resolve, reject) => {
verify(token, process.env.JWT_SECRET, (err, decoded) => {
if (err) {
reject(err);
return;
}
resolve(decoded);
return;
});
});
}
Example #17
Source File: auth.ts From hotseat-api with MIT License | 6 votes |
authMiddleware = (
request: Request,
_response: Response,
next: NextFunction,
): void => {
try {
const { authorization } = request.headers;
if (!authorization) {
throw new AppError('Authorization token not provided', 403);
}
const [, token] = authorization?.split(' ');
verify(token, authConfig.jwt.tokenSecret, (err, decoded) => {
if (err) {
throw new AppError(err.message, 403);
}
if (!decoded) {
throw new AppError('Invalid JWT token', 400);
}
const payload = decoded as IJWTPayload;
request.user = {
id: payload.sub,
};
});
return next();
} catch (error) {
// eslint-disable-next-line no-console
console.log(error);
throw new AppError(error.message);
}
}
Example #18
Source File: middleware.ts From your_spotify with GNU General Public License v3.0 | 6 votes |
baselogged = async (req: Request, useQueryToken = false) => {
const auth = req.cookies.token;
if (!auth && useQueryToken) {
const { token } = req.query;
if (!token) {
return null;
}
const user = await getUserFromField('publicToken', token, false);
if (!user) {
return null;
}
return user;
}
if (!auth) return null;
if (auth) {
try {
const userId = verify(auth, 'MyPrivateKey') as { userId: string };
const user = await getUserFromField('_id', new Types.ObjectId(userId.userId), false);
if (!user) {
return null;
}
return user;
} catch (e) {
return null;
}
}
return null;
}
Example #19
Source File: JWT.ts From nodejs-backend-architecture-typescript with Apache License 2.0 | 6 votes |
/**
* This method checks the token and returns the decoded data when token is valid in all respect
*/
public static async validate(token: string): Promise<JwtPayload> {
const cert = await this.readPublicKey();
try {
// @ts-ignore
return (await promisify(verify)(token, cert)) as JwtPayload;
} catch (e) {
Logger.debug(e);
if (e && e.name === 'TokenExpiredError') throw new TokenExpiredError();
// throws error if the token has not been encrypted by the private key
throw new BadTokenError();
}
}
Example #20
Source File: JWT.ts From nodejs-backend-architecture-typescript with Apache License 2.0 | 6 votes |
/**
* Returns the decoded payload if the signature is valid even if it is expired
*/
public static async decode(token: string): Promise<JwtPayload> {
const cert = await this.readPublicKey();
try {
// @ts-ignore
return (await promisify(verify)(token, cert, { ignoreExpiration: true })) as JwtPayload;
} catch (e) {
Logger.debug(e);
throw new BadTokenError();
}
}
Example #21
Source File: verifyJwtToken.ts From one-platform with MIT License | 5 votes |
/**
* Verifies the JWT Token
*/
export function verifyJwtToken(token: string, callback: any) {
return verify(token, getPublicKey(), callback);
}
Example #22
Source File: Auth.provider.ts From nodetskeleton with MIT License | 5 votes |
verifyJwt(jwt: string): ISession {
return verify(jwt, AppSettings.JWTEncryptionKey) as ISession;
}
Example #23
Source File: bearer-token-verifier.provider.ts From loopback4-microservice-catalog with MIT License | 5 votes |
value(): VerifyFunction.BearerFn {
return async (token: string) => {
return verify(token, 'kdskssdkdfs', {
issuer: 'sf',
}) as IAuthUserWithPermissions;
};
}
Example #24
Source File: bearer-token-verify.provider.ts From loopback4-microservice-catalog with MIT License | 5 votes |
value(): VerifyFunction.BearerFn {
return async (token: string) => {
return verify(token, 'kdskssdkdfs', {
issuer: 'sf',
}) as IAuthUserWithPermissions;
};
}
Example #25
Source File: isAuth.ts From vsinder with Apache License 2.0 | 5 votes |
isAuth: (st?: boolean) => RequestHandler<{}, any, any, {}> = (
shouldThrow = true
) => async (req: Request, res: Response, next: NextFunction): Promise<void> => {
const accessToken = req.headers["access-token"];
if (typeof accessToken !== "string") {
return next(
shouldThrow && createError(401, "not authenticated")
);
}
try {
const data = <AccessTokenData>verify(accessToken, process.env.ACCESS_TOKEN_SECRET);
req.userId = data.userId;
return next();
} catch {}
const refreshToken = req.headers["refresh-token"];
if (typeof refreshToken !== "string") {
return next(
shouldThrow && createError(401, "not authenticated")
);
}
let data;
try {
data = <RefreshTokenData>verify(refreshToken, process.env.REFRESH_TOKEN_SECRET);
} catch {
return next(
shouldThrow && createError(401, "not authenticated")
);
}
const user = await User.findOne(data.userId);
// token has been invalidated or user deleted
if (!user || user.tokenVersion !== data.tokenVersion) {
return next(
shouldThrow && createError(401, "not authenticated")
);
}
const tokens = createTokens(user);
res.setHeader("refresh-token", tokens.refreshToken);
res.setHeader("access-token", tokens.accessToken);
req.userId = data.userId;
next();
}
Example #26
Source File: isAuth.ts From vsinder-api with Apache License 2.0 | 5 votes |
isAuth: (st?: boolean) => RequestHandler<{}, any, any, {}> = (
shouldThrow = true
) => async (req, res, next) => {
const accessToken = req.headers["access-token"];
if (!accessToken || typeof accessToken !== "string") {
return next(
!shouldThrow ? undefined : createError(401, "not authenticated")
);
}
try {
const data = verify(accessToken, process.env.ACCESS_TOKEN_SECRET) as any;
(req as any).userId = data.userId;
return next();
} catch {}
const refreshToken = req.headers["refresh-token"];
if (!refreshToken || typeof refreshToken !== "string") {
return next(
!shouldThrow ? undefined : createError(401, "not authenticated")
);
}
let data;
try {
data = verify(refreshToken, process.env.REFRESH_TOKEN_SECRET) as any;
} catch {
return next(
!shouldThrow ? undefined : createError(401, "not authenticated")
);
}
const user = await User.findOne(data.userId);
// token has been invalidated or user deleted
if (!user || user.tokenVersion !== data.tokenVersion) {
return next(
!shouldThrow ? undefined : createError(401, "not authenticated")
);
}
const tokens = createTokens(user);
res.setHeader("refresh-token", tokens.refreshToken);
res.setHeader("access-token", tokens.accessToken);
(req as any).userId = data.userId;
next();
}
Example #27
Source File: jwt-token-handler.ts From advanced-node with GNU General Public License v3.0 | 5 votes |
async validate ({ token }: TokenValidator.Input): Promise<TokenValidator.Output> {
const payload = verify(token, this.secret) as JwtPayload
return payload.key
}
Example #28
Source File: Auth.spec.ts From typescript-clean-architecture with MIT License | 5 votes |
describe('Auth', () => {
let testServer: TestServer;
let userFixture: UserFixture;
beforeAll(async () => {
testServer = await TestServer.new();
userFixture = UserFixture.new(testServer.testingModule);
await testServer.serverApplication.init();
});
afterAll(async () => {
if (testServer) {
await testServer.serverApplication.close();
}
});
describe('POST /auth/login', () => {
test('When credentials are correct, expect user successfully log in', async () => {
const role: UserRole = UserRole.AUTHOR;
const email: string = `${v4()}@email.com`;
const password: string = v4();
const user: User = await userFixture.insertUser({role, email, password});
const response: supertest.Response = await supertest(testServer.serverApplication.getHttpServer())
.post('/auth/login')
.send({email, password})
.expect(HttpStatus.OK);
const tokenPayload: HttpJwtPayload = await verify(response.body.data.accessToken, ApiServerConfig.ACCESS_TOKEN_SECRET) as HttpJwtPayload;
ResponseExpect.codeAndMessage(response.body, {code: Code.SUCCESS.code, message: Code.SUCCESS.message});
ResponseExpect.data({response: response.body, passFields: ['id']}, {id: user.getId()});
expect(tokenPayload.id).toBe(user.getId());
});
test('When email is not correct, expect it returns "WRONG_CREDENTIALS_ERROR" response', async () => {
const email: string = `${v4()}@email.com`;
const password: string = v4();
await expectWrongCredentialsOnLogin(
{email: email, password: password},
{email: `${v4()}@email.com`, password: password},
testServer,
userFixture,
);
});
test('When password is not correct, expect it returns "WRONG_CREDENTIALS_ERROR" response', async () => {
const email: string = `${v4()}@email.com`;
const password: string = v4();
await expectWrongCredentialsOnLogin(
{email: email, password: password},
{email: email, password: v4()},
testServer,
userFixture,
);
});
});
});
Example #29
Source File: jsonWebToken.service.ts From rest-api.ts with MIT License | 5 votes |
decode(token: string): any {
return verify(token, this.JWT_PRIVATE_KEY);
}