passport-jwt#Strategy TypeScript Examples

The following examples show how to use passport-jwt#Strategy. 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: jwt.strategy.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configuration().jwtSecret
    });
  }

  async validate(
    payload: JwtPayload | PromiseLike<JwtPayload>
  ): Promise<JwtPayload> {
    return payload;
  }
}
Example #2
Source File: jwt.strategy.ts    From pknote-backend with GNU General Public License v3.0 6 votes vote down vote up
@Injectable()
export class JwtStragegy extends PassportStrategy(Strategy) {
  constructor(
    @InjectRepository(UserRepository)
    private userRepository: UserRepository,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: process.env.JWT_SECRET || config.get('jwt.secret'),
    });
  }

  async validate(payload: JwtPayload): Promise<UserInfo> {
    const { userId } = payload;
    const user = await this.userRepository.findOne({ userId });
    if (!user) {
      throw new UnauthorizedException();
    }
    // user 将会放入 Request 中
    return user;
  }
}
Example #3
Source File: jwt.strategy.ts    From nestjs-angular-starter with MIT License 6 votes vote down vote up
/**
 * This service is reponsible of implementing the local passport authentication strategy which is based
 * on JWT and being provided using the 'Bearer' header.
 */
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: config.JWT.SECRET,
    });
  }

  validate(payload: UserProfile): Promise<UserProfile> {
    return this.authService.getUserFromDB(payload.email).exec();
  }
}
Example #4
Source File: jwt.strategy.ts    From office-hours with GNU General Public License v3.0 6 votes vote down vote up
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(configService: ConfigService) {
    super({
      jwtFromRequest: (req: Request) => req.cookies['auth_token'],
      ignoreExpiration: false,
      secretOrKey: configService.get('JWT_SECRET'),
    });
  }

  validate(payload: { userId: number }): any {
    return { ...payload };
  }
}
Example #5
Source File: jwt.strategy.ts    From nestjs-starter with MIT License 6 votes vote down vote up
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly configService: ConfigService, private readonly userService: UsersService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get<string>(CONFIG_SERVER_JWT_SECRET),
    });
  }

  async validate(payload: JwtPayload) {
    return this.userService.getOneById(payload.sub);
  }
}
Example #6
Source File: HttpJwtStrategy.ts    From typescript-clean-architecture with MIT License 6 votes vote down vote up
@Injectable()
export class HttpJwtStrategy extends PassportStrategy(Strategy) {
  
  constructor(private authService: HttpAuthService) {
    super({
      jwtFromRequest: ExtractJwt.fromHeader(ApiServerConfig.ACCESS_TOKEN_HEADER),
      ignoreExpiration: false,
      secretOrKey: ApiServerConfig.ACCESS_TOKEN_SECRET,
    });
  }
  
  public async validate(payload: HttpJwtPayload): Promise<HttpUserPayload> {
    const user: User = CoreAssert.notEmpty(
      await this.authService.getUser({id: payload.id}),
      Exception.new({code: Code.UNAUTHORIZED_ERROR})
    );
  
    return {id: user.getId(), email: user.getEmail(), role: user.getRole()};
  }
  
}
Example #7
Source File: jwt.strategy.ts    From MyAPI with MIT License 6 votes vote down vote up
/**
 * JwtStrategy is passport JWT strategy.
 * 
 * @export
 * @class JwtStrategy
 * @extends {PassportStrategy(Strategy)}
 */
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: AUTH_SECRET_TOKEN,
    })
  }

  /**
   * validate returns jwt payload.
   * @param payload - Payload with the info of the user
   * 
   * @returns
   * @memberof JwtStrategy
   */
  validate(payload: AuthPayload): AuthPayload {
    return payload
  }
}
Example #8
Source File: jwt.strategy.ts    From bank-server with MIT License 6 votes vote down vote up
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly _configService: ConfigService,
    private readonly _userService: UserService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: _configService.get('JWT_SECRET_KEY'),
    });
  }

  async validate({ iat, exp, uuid }): Promise<UserEntity> {
    const timeDiff = exp - iat;

    if (timeDiff <= 0) {
      throw new UnauthorizedException();
    }

    const user = await this._userService.getUser({ uuid });

    if (!user) {
      throw new UnauthorizedException();
    }

    return user;
  }
}
Example #9
Source File: jwt.strategy.ts    From api with GNU Affero General Public License v3.0 6 votes vote down vote up
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    configService: ConfigService,
    private readonly userService: UserService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get<string>('SECRET_KEY'),
    });
  }

  async validate(payload: any): Promise<UserEntity> {
    try {
      return await this.userService.findById(payload.sub)
    } catch (e) {
      // log error
    }

    return null
  }
}
Example #10
Source File: jwt.strategy.ts    From Phantom with MIT License 6 votes vote down vote up
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {

  constructor(private authService: AuthService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: process.env.SECRET_KEY,
    });
  }

  /**
   * @author Aya Abohadima
   * @description validate function to check correct object com from token
   * @param payload the object created from token
   * @param done 
   * return token object 
   */
  async validate(payload: any, done: VerifiedCallback) {
    return payload;
  }
}
Example #11
Source File: jwt-refresh.strategy.ts    From nestjs-starter-rest-api with MIT License 6 votes vote down vote up
@Injectable()
export class JwtRefreshStrategy extends PassportStrategy(
  Strategy,
  STRATEGY_JWT_REFRESH,
) {
  constructor(private readonly configService: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromBodyField('refreshToken'),
      secretOrKey: configService.get<string>('jwt.publicKey'),
      algorithms: ['RS256'],
    });
  }

  // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  async validate(payload: any): Promise<UserRefreshTokenClaims> {
    // Passport automatically creates a user object, based on the value we return from the validate() method,
    // and assigns it to the Request object as req.user
    return { id: payload.sub };
  }
}
Example #12
Source File: jwt-auth.strategy.ts    From nestjs-starter-rest-api with MIT License 6 votes vote down vote up
@Injectable()
export class JwtAuthStrategy extends PassportStrategy(
  Strategy,
  STRATEGY_JWT_AUTH,
) {
  constructor(private readonly configService: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: configService.get<string>('jwt.publicKey'),
      algorithms: ['RS256'],
    });
  }

  // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  async validate(payload: any): Promise<UserAccessTokenClaims> {
    // Passport automatically creates a user object, based on the value we return from the validate() method,
    // and assigns it to the Request object as req.user
    return {
      id: payload.sub,
      username: payload.username,
      roles: payload.roles,
    };
  }
}
Example #13
Source File: app.ts    From flood with GNU General Public License v3.0 6 votes vote down vote up
passport.use(
  new Strategy(
    {
      jwtFromRequest: (req: Request) => req?.cookies?.jwt,
      secretOrKey: config.secret,
    },
    (payload, callback) => {
      const parsedResult = authTokenSchema.safeParse(payload);

      if (!parsedResult.success) {
        callback(parsedResult.error, false);
        return;
      }

      Users.lookupUser(parsedResult.data.username).then(
        (user) => {
          if (user?.timestamp <= parsedResult.data.iat + 10) {
            callback(null, user);
          } else {
            callback(new Error(), false);
          }
        },
        (err) => {
          callback(err, false);
        },
      );
    },
  ),
);
Example #14
Source File: jwt.strategy.ts    From pandaid with MIT License 6 votes vote down vote up
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: 'secret'
    })
  }

  validate(payload: User) {
    return payload
  }
}
Example #15
Source File: jwt.strategy.ts    From nestjs-rest-sample with GNU General Public License v3.0 6 votes vote down vote up
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(@Inject(jwtConfig.KEY) config: ConfigType<typeof jwtConfig>) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: config.secretKey,
    });
  }

  //payload is the decoded jwt clmais.
  validate(payload: JwtPayload): UserPrincipal {
    //console.log('jwt payload:' + JSON.stringify(payload));
    return {
      username: payload.upn,
      email: payload.email,
      id: payload.sub,
      roles: payload.roles,
    };
  }
}
Example #16
Source File: jwt.strategy.ts    From 42_checkIn with GNU General Public License v3.0 6 votes vote down vote up
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly configService: ConfigService,
    private readonly logger: MyLogger,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromExtractors([
        (req: Request) => {
          return req?.cookies?.w_auth;
        },
      ]),
      ignoreExpiration: false,
      secretOrKey: configService.get('jwt.secret'),
    });
  }
  async validate(payload: any) {
    this.logger.debug('jwt extracting...');
    this.logger.debug('jwt extracted data : ', payload.sub, payload.username);
    return { _id: payload.sub, name: payload.username };
  }
}
Example #17
Source File: jwt.strategy.ts    From amplication with Apache License 2.0 6 votes vote down vote up
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly authService: AuthService,
    readonly configService: ConfigService
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      passReqToCallback: true,
      secretOrKey: configService.get('JWT_SECRET')
    });
  }

  async validate(req, payload: JwtDto): Promise<AuthUser> {
    if (payload.type === EnumTokenType.ApiToken) {
      const jwt = ExtractJwt.fromAuthHeaderAsBearerToken()(req);

      const isValid = await this.authService.validateApiToken({
        userId: payload.userId,
        tokenId: payload.tokenId,
        token: jwt
      });
      if (!isValid === true) {
        throw new UnauthorizedException();
      }
    }

    const user = await this.authService.getAuthUser({
      id: payload.userId
    });
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}
Example #18
Source File: jwt.strategy.base.ts    From amplication with Apache License 2.0 6 votes vote down vote up
export class JwtStrategyBase
  extends PassportStrategy(Strategy)
  implements IAuthStrategy {
  constructor(
    protected readonly userService: UserService,
    protected readonly secretOrKey: string
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey,
    });
  }

  async validate(payload: UserInfo): Promise<UserInfo> {
    const { username } = payload;
    const user = await this.userService.findOne({
      where: { username },
    });
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}
Example #19
Source File: jwt.strategy.ts    From nest-js-quiz-manager with MIT License 6 votes vote down vote up
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: appConfig().appSecret,
    });
  }

  async validate(payload: any) {
    return {
      id: payload.sub,
      name: payload.name,
      tenant: 'amitav',
    };
  }
}
Example #20
Source File: jwt.strategy.ts    From svvs with MIT License 6 votes vote down vote up
/**
 * Implements interaction with standard passport-jwt methods
 * and return validate data
 */
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  /**
   * provide super
   */
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: environment.jwt.secret,
    })
  }

  /**
   * Return validate data
   * @param payload
   */
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  async validate(payload: any) {
    return {userId: payload.sub, username: payload.username}
  }
}
Example #21
Source File: jwt.stratergy.ts    From uniauth-backend with MIT License 6 votes vote down vote up
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromExtractors([
        (request: Request) => {
          return request?.cookies?.vitAuth;
        },
      ]),
      ignoreExpiration: false,
      secretOrKey: newJWTConstants.secret,
    });
  }

  async validate(payload: any) {
    return { ...payload };
  }
}
Example #22
Source File: cookie.stratergy.ts    From uniauth-backend with MIT License 6 votes vote down vote up
@Injectable()
export class CookieStratergy extends PassportStrategy(Strategy) {
  constructor(private readonly userService: UserService) {
    super({
      jwtFromRequest: ExtractJwt.fromExtractors([
        (request: Request) => {
          return request?.cookies?.Authentication;
        },
      ]),
      secretOrKey: newJWTConstants.secret,
    });
  }

  async validate(payload: { id: any }) {
    return this.userService.findOneById(payload.id);
  }
}
Example #23
Source File: jwt.strategy.ts    From barista with Apache License 2.0 6 votes vote down vote up
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: jwtConstants.secret,
    });
  }

  async validate(payload: any) {
    const { sub, iat, exp, ...result } = payload;
    return result;
  }
}
Example #24
Source File: jwt-ws-access.strategy.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@Injectable()
export default class JwtWSAccessStrategy extends PassportStrategy(Strategy, 'accessTokenWS') {
  constructor(
    private readonly configService: ConfigService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromExtractors([
        (client: any) => {
          const bearerToken = client?.handshake?.headers?.authorization;
          return bearerToken ? bearerToken.split(' ')[1] : null;
        },
      ]),
      ignoreExpiration: false,
      secretOrKey: configService.get<string>('ACCESS_TOKEN') || '<%= config.accessTokenSecret %>',
    });
  }
  async validate(payload: JwtStrategyValidate): Promise<JwtStrategyValidate> {
    return {
      id: payload.id,
      email: payload.email,
      role: payload.role,
    };
  }
}
Example #25
Source File: jwt-ws-access.strategy.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@Injectable()
export default class JwtWSAccessStrategy extends PassportStrategy(Strategy, 'accessTokenWS') {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromExtractors([
        (client: any) => {
          const bearerToken = client?.handshake?.headers?.authorization;
          return bearerToken ? bearerToken.split(' ')[1] : null;
        },
      ]),
      ignoreExpiration: false,
      secretOrKey: this.configService.get<string>('ACCESS_TOKEN') || '<%= config.accessTokenSecret %>',
    });
  }
  async validate(payload: JwtStrategyValidate): Promise<JwtStrategyValidate> {
    return {
      id: payload.id,
      email: payload.email,
      role: payload.role,
    };
  }
}
Example #26
Source File: jwt-ws-access.strategy.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@Injectable()
export default class JwtWSAccessStrategy extends PassportStrategy(Strategy, 'accessTokenWS') {
  constructor(
    private readonly configService: ConfigService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromExtractors([
        (client: any) => {
          const bearerToken = client?.handshake?.headers?.authorization;
          return bearerToken ? bearerToken.split(' ')[1] : null;
        },
      ]),
      ignoreExpiration: false,
      secretOrKey: configService.get<string>('ACCESS_TOKEN') || '<%= config.accessTokenSecret %>',
    });
  }
  async validate(payload: JwtStrategyValidate): Promise<JwtStrategyValidate> {
    return {
      _id: payload._id,
      email: payload.email,
      role: payload.role,
    };
  }
}
Example #27
Source File: jwt-refresh.strategy.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@Injectable()
export default class JwtRefreshStrategy extends PassportStrategy(Strategy, 'refreshToken') {
  constructor(
    private readonly configService: ConfigService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get<string>('REFRESH_TOKEN') || '<%= config.refreshTokenSecret %>',
    });
  }

  async validate(payload: UserEntity): Promise<JwtStrategyValidate> {
    return {
      id: payload.id,
      email: payload.email,
      role: payload.role,
    };
  }
}
Example #28
Source File: jwt-access.strategy.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@Injectable()
export default class JwtAccessStrategy extends PassportStrategy(Strategy, 'accessToken') {
  constructor(
    private readonly configService: ConfigService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get<string>('ACCESS_TOKEN') || '<%= config.accessTokenSecret %>',
    });
  }

  async validate(payload: UserEntity): Promise<JwtStrategyValidate> {
    return {
      id: payload.id,
      email: payload.email,
      role: payload.role,
    };
  }
}
Example #29
Source File: jwt-refresh.strategy.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
@Injectable()
export default class JwtRefreshStrategy extends PassportStrategy(Strategy, 'refreshToken') {
  constructor(
    private readonly configService: ConfigService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get<string>('REFRESH_TOKEN') || '<%= config.refreshTokenSecret %>',
    });
  }

  async validate(payload: UserDocument): Promise<JwtStrategyValidate> {
    return {
      _id: payload._id,
      email: payload.email,
      role: payload.role,
    };
  }
}