@nestjs/passport#PassportStrategy TypeScript Examples

The following examples show how to use @nestjs/passport#PassportStrategy. 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 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 #2
Source File: ft.strategy.ts    From 42_checkIn with GNU General Public License v3.0 6 votes vote down vote up
@Injectable()
export class FtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly configService: ConfigService,
    private readonly logger: MyLogger,
  ) {
    super({
      clientID: configService.get('client.id'),
      clientSecret: configService.get('client.secret'),
      callbackURL: configService.get('client.callback'),
    });
  }
  async validate(token: string, rt: string, profile: any) {
    try {
      this.logger.debug('oauth validation start');
      const user = new User(
        profile.id,
        profile.username,
        profile.emails[0].value,
      );
      this.logger.debug('authroized info : ', profile.id, profile.username);
      if (profile._json.cursus_users.length < 2)
        throw new NotAcceptableException();
      return user;
    } catch (e) {
      this.logger.info(e);
      throw e;
    }
  }
}
Example #3
Source File: local.strategy.ts    From nestjs-rest-sample with GNU General Public License v3.0 6 votes vote down vote up
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super({
      usernameField: 'username',
      passwordField: 'password',
    });
  }

  // When using Observable as return type, the exeption in the pipeline is ignored.
  // In our case, the `UnauthorizedException` is **NOT** caught and handled as expected.
  // The flow is NOT prevented by the exception and continue to send a `Observable` to
  // the next step aka calling `this.authService.login` in `AppController#login` method.
  // Then the jwt token is generated in any case(eg. wrong username or wrong password),
  // the authenticatoin worflow does not work as expected.
  //
  // The solution is customizing `PassportSerializer`.
  // Example: https://github.com/jmcdo29/zeldaPlay/blob/master/apps/api/src/app/auth/session.serializer.ts
  //
  // validate(username: string, password: string): Observable<any> {
  //   return this.authService
  //     .validateUser(username, password)
  //     .pipe(throwIfEmpty(() => new UnauthorizedException()));
  // }

  async validate(username: string, password: string): Promise<UserPrincipal> {
    const user: UserPrincipal = await lastValueFrom(
      this.authService.validateUser(username, password),
    );

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

    return user;
  }
}
Example #4
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 #5
Source File: api-key.strategy.ts    From ironfish-api with Mozilla Public License 2.0 6 votes vote down vote up
@Injectable()
export class ApiKeyStrategy extends PassportStrategy(Strategy, 'api-key') {
  constructor(private readonly config: ApiConfigService) {
    super();
  }

  authenticate(request: Request): void {
    const { headers } = request;
    const apiKey = headers.authorization;
    const ironfishApiKey = this.config.get<string>('IRONFISH_API_KEY');
    if (apiKey !== `Bearer ${ironfishApiKey}`) {
      throw new UnauthorizedException();
    }
    return this.pass();
  }
}
Example #6
Source File: apikey.strategy.ts    From coronatest with GNU Affero General Public License v3.0 6 votes vote down vote up
@Injectable()
export class APIKeyStrategy extends PassportStrategy(Strategy) {
    constructor(private readonly authService: AuthService) {
        super(
            {
                header: 'Authorization',
                prefix: ''
            },
            null,
            async (apiKey, done) => {
                return await this.validate(apiKey, done);
            }
        );
    }

    async validate(apiKey: any, done: any) {
        let result = await this.authService.validateAPIKey(apiKey);
        if (result) return done(null, { apiKey });
        else return done(null, false);
    }
}
Example #7
Source File: firebase-admin-user-login.strategy.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Injectable()
export class FirebaseAdminUserLoginStrategy extends PassportStrategy(
  Strategy,
  'firebase-admin-user-login'
) {
  async validate(req: Request, done: VerifiedCallback): Promise<any> {
    const extractorFunction = ExtractJwt.fromAuthHeaderAsBearerToken()
    const token = extractorFunction(req)
    if (!token) {
      throw new UnauthorizedException('No bearer token found in the header')
    }

    let userDecodedToken: firebaseAdmin.auth.DecodedIdToken
    try {
      userDecodedToken = await firebaseAdmin.auth().verifyIdToken(token)
    } catch (error) {
      throw new UnauthorizedException(error.message)
    }

    // Expect all admin access tokens to have email and email_verified data.
    validateAdminTokenEmailPayload(userDecodedToken)

    const requestAdminUser: RequestAdminUser = {
      isAdminUser: userDecodedToken.isAdminUser,
      userAdminRole: userDecodedToken.userAdminRole,
      userAccessKey: userDecodedToken.userAccessKey,
      uid: userDecodedToken.uid,
      email: userDecodedToken.email,
    }

    // NOTE : Passport automatically creates a user object, based on the value we return here.
    done(null, requestAdminUser)
  }
}
Example #8
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 #9
Source File: google.strategy.ts    From Phantom with MIT License 6 votes vote down vote up
@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
  constructor() {
    super({
      clientID: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_SECRET,
      callbackURL: `${process.env.BASE_URL}/api/google/redirect`,
      scope: ['email', 'profile'],
    });
  }

  async validate(
    accessToken: string,
    refreshToken: string,
    profile: any,
    done: VerifyCallback,
  ): Promise<any> {
    const { name, emails, photos } = profile;
    const user = {
      email: emails[0].value,
      firstName: name.givenName,
      lastName: name.familyName,
      picture: photos[0].value,

      accessToken,
    };
    done(null, user);
  }
}
Example #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
Source File: access-token.strategy.ts    From nestjs-oauth2-server-module with MIT License 6 votes vote down vote up
@Injectable()
export class AccessTokenStrategy extends PassportStrategy(Strategy, 'access-token') {
    constructor(
        @Inject('AccessTokenRepositoryInterface')
        private readonly accessTokenRepository: AccessTokenRepositoryInterface,
        @Inject('UserLoaderInterface')
        private readonly userLoader: UserLoaderInterface
    ) {
        super();
    }

    /**
     * Validate the bearer (accessToken) using the HTTP Bearer Header strategy
     *
     * @param bearer
     */
    async validate(bearer: string): Promise<Oauth2PayloadInterface> {
        const accessToken = await this.accessTokenRepository.findByAccessToken(bearer);
        if (!accessToken || accessToken.accessTokenExpiresAt < new Date(Date.now())) {
            throw new UnauthorizedException();
        }

        if (accessToken.userId) {
            const user = await this.userLoader.load(accessToken.userId);
            return new UserPayload(
                accessToken,
                accessToken.userId,
                user.username,
                user.email);
        }

        return new ClientPayload(
            accessToken,
            accessToken.client.id,
            accessToken.client.clientId,
            accessToken.client.name);
    }
}
Example #19
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 #20
Source File: local.strategy.ts    From knests with MIT License 6 votes vote down vote up
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly authService: AuthService) {
    super({
      usernameField: 'email',
      passwordField: 'password',
    });

  }

  async validate(credentials: LoginDTO): Promise<any> {
    const user = await this.authService.validateUser(credentials);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}
Example #21
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 #22
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 #23
Source File: jwt.strategy.ts    From NestJs-youtube with MIT License 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) {
    return { id: payload.id, email: payload.email, role: payload.role };
  }
}
Example #24
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: UserDocument): Promise<JwtStrategyValidate> {
    return {
      _id: payload._id,
      email: payload.email,
      role: payload.role,
    };
  }
}
Example #25
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 #26
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 #27
Source File: jwt.strategy.ts    From whispr with MIT License 6 votes vote down vote up
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private configService: ConfigService) {
    super(configService.getAuthConfig());
  }

  validate(payload: any) {
    return payload;
  }
}
Example #28
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 #29
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}
  }
}