How to use the @nestjs/passport.PassportStrategy function in @nestjs/passport

To help you get started, we’ve selected a few @nestjs/passport 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 danielwii / asuna-node-server / src / modules / core / auth / strategy / jwt.strategy.ts View on Github external
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { AsunaErrorCode, AsunaException } from '../../../common';
import { LoggerFactory } from '../../../common/logger';
import { ConfigKeys, configLoader } from '../../../config';
import { JwtPayload } from '../auth.interfaces';
import { AuthService } from '../auth.service';

const logger = LoggerFactory.getLogger('JwtStrategy');

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor(private readonly authService: AuthService) {
    super(
      {
        jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
        // passReqToCallback: true,
        secretOrKey: configLoader.loadConfig(ConfigKeys.SECRET_KEY, 'secret'),
      },
      // async (req, payload, next) => await this.verify(req, payload, next),
    );
  }

  async validate(payload: JwtPayload): Promise {
    // logger.log(`validate ${r(payload)}`);
    const isValid = await this.authService.validateUser(payload);
    if (!isValid) {
      throw new AsunaException(AsunaErrorCode.InsufficientPermissions, 'jwt auth strategy failed');
github JamesCoonce / angular-nest-todo / server / todo-api / src / auth / passport / jwt.strategy.ts View on Github external
import { ExtractJwt, Strategy } from 'passport-jwt';
import { AuthService } from '../auth.service';
import { PassportStrategy } from '@nestjs/passport';
import { Request } from 'express';
import { use } from 'passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtPayload } from '../interfaces/jwt-payload.interface';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
    constructor(private readonly authService: AuthService) {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            secretOrKey: 'ILovePokemon',
        });
    }

    // tslint:disable-next-line:ban-types
    async validate(req: Request, payload: JwtPayload, done: Function) {
        const user = await this.authService.validateUser(payload);
        if (!user) {
            return done(new UnauthorizedException(), false);
        }
        done(null, user);
    }
}
github rucken / core-nestjs / libs / rucken / auth-nestjs / src / passport / local.strategy.ts View on Github external
constructor(private readonly authService: AuthService) {
    super({
      usernameField: 'email',
      passwordField: 'password',
      passReqToCallback: true
    });
  }

  public async validate(req, email: string, password: string) {
    const { user }: { user: User } = await this.authService.signIn({ email, password });
    return user;
  }
}
// tslint:disable-next-line:max-classes-per-file
@Injectable()
export class LocalStrategySignUp extends PassportStrategy(Strategy, 'signup') {
  constructor(private readonly authService: AuthService) {
    super({
      usernameField: 'email',
      passwordField: 'password',
      passReqToCallback: true
    });
  }

  public async validate(req, email: string, password: string) {
    if (req.user) {
      return req.user;
    }
    const { user } = await this.authService.signUp({
      email,
      password,
      username: req.body.username
github xmlking / ngx-starter-kit / apps / api / src / app / auth / passport / jwt.strategy.ts View on Github external
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { passportJwtSecret, SigningKeyNotFoundError } from '@xmlking/jwks-rsa';

import { AuthService } from '../auth.service';
import { JwtToken } from '../interfaces/jwt-token.interface';
import { environment as env } from '@env-api/environment';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly authService: AuthService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      // secretOrKey: env.auth.publicKey,
      secretOrKeyProvider: passportJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        strictSsl: false,
        jwksUri: env.auth.jwksUri || `${env.auth.issuer}/protocol/openid-connect/certs`,
      }),
      handleSigningKeyError: (err, cb) => {
        if (err instanceof SigningKeyNotFoundError) {
          return cb(new UnauthorizedException('This is bad: SigningKeyNotFoundError'));
        }
        return cb(err);
github jiayisheji / nest-cnode / src / feature / auth / passport / github.strategy.ts View on Github external
'location': null;
        'email': string;
        'hireable': null;
        'bio': null;
        'public_repos': number;
        'public_gists': number;
        'followers': number;
        'following': number;
        'created_at': string;
        'updated_at': string;
    };
    accessToken: string;
}

@Injectable()
export class GithubStrategy extends PassportStrategy(Strategy) {
    constructor(private readonly config: ConfigService) {
        super({
            ...config.get('github'),
        });
    }

    // tslint:disable-next-line:ban-types
    async validate(
        accessToken: string,
        refreshToken: string,
        profile: GitHubProfile,
        done: (error: null, data: GitHubProfile) => void,
    ) {
        profile.accessToken = accessToken;
        done(null, profile);
    }
github devonfw / my-thai-star / node / src / app / core / auth / strategies / jwt.strategy.ts View on Github external
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigurationService } from '../../configuration/services/configuration.service';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(public readonly configService: ConfigurationService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.jwtConfig.secret,
    });
  }

  async validate(payload: any) {
    return payload;
  }
}
github kelvin-mai / nest-commerce / src / auth / jwt.strategy.ts View on Github external
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy, VerifiedCallback } from 'passport-jwt';

import { AuthService } from './auth.service';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: process.env.SECRET_KEY,
    });
  }

  async validate(payload: any, done: VerifiedCallback) {
    const user = await this.authService.validateUser(payload);
    if (!user) {
      return done(
        new HttpException('Unauthorized access', HttpStatus.UNAUTHORIZED),
        false,
      );
    }
github cdiaz / nest-passport / src / auth / passport / local.strategy.ts View on Github external
import { Strategy } from 'passport-local';
import { AuthService } from '../auth.service';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly authService: AuthService) {
    super({
      usernameField: 'email',
      passReqToCallback: false
    });
  }

  async validate(email, password, done: Function) {
    await this.authService.logIn(email, password)
    .then(user => done(null, user))
    .catch(err => done(err, false))
  }
}

export const callback = (err, user, info) => {
  if (typeof info != 'undefined') {
github lonelyhentai / minellius / server / src / auth / passport / jwt.strategy.ts View on Github external
import { BadRequestException, Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { plainToClass } from 'class-transformer';
import { Strategy } from 'passport-jwt';
import { IJwtPayload } from '../interfaces/jwt-payload.interface';
import { TokenService } from '../services/token.service';
import { GroupsService, User, UsersService } from '../../role';

@Injectable()
export class MinelliusJwtStrategy extends PassportStrategy(Strategy, 'minellius-jwt') {
  constructor(private readonly tokenService: TokenService, private readonly groupsService: GroupsService,
              private readonly userService: UsersService) {
    super({
      passReqToCallback: true,
      jwtFromRequest: req => {
        const token = this.tokenService.extractTokenFromRequest(req);
        return token;
      },
      secretOrKeyProvider: (req, token, done) => {
        let user;
        try {
          user = plainToClass(User, this.tokenService.decode(token));
        } catch (error) {
        } finally {
          const secretKey = this.tokenService.createSecretKey(user);
          done(null, secretKey);
github surmon-china / nodepress / src / modules / auth / jwt.strategy.ts View on Github external
/**
 * Auth jwt.strategy.
 * @file 鉴权器
 * @module module/auth/jwt.strategy
 * @author Surmon 
 */

import * as APP_CONFIG from '@app/app.config';
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { HttpUnauthorizedError } from '@app/errors/unauthorized.error';
import { AuthService } from './auth.service';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {

  constructor(private readonly authService: AuthService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: APP_CONFIG.AUTH.jwtTokenSecret,
    });
  }

  validate(payload: any) {
    const data = this.authService.validateAuthData(payload);
    if (data) {
      return data;
    } else {
      throw new HttpUnauthorizedError();
    }
  }

@nestjs/passport

Nest - modern, fast, powerful node.js web framework (@passport)

MIT
Latest version published 8 months ago

Package Health Score

88 / 100
Full package analysis

Similar packages