How to use @nestjs/passport - 10 common examples

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 vip-git / react-ssr-advanced-seed / src / server / app / modules / cats / graphql / cats.resolvers.ts View on Github external
Query,
  Mutation,
  Resolver,
  DelegateProperty,
  Subscription,
} from '@nestjs/graphql';
import { PubSub } from 'graphql-subscriptions';

// Internal
import { ICat } from '../shared/cat.model';
import { CatsService } from '../shared/cats.service';
import { CatsGuard } from './cats.guard';

const pubSub = new PubSub();

@UseGuards(AuthGuard('jwt'))
@Resolver('Cat')
export class CatsResolvers {
  constructor(private readonly catsService: CatsService) {}

  @Query()
  @UseGuards(CatsGuard)
  async getCats() {
    return await this.catsService.findAll();
  }

  @Query('cat')
  async findOneById(obj, args, context, info): Promise {
    const { id } = args;
    return await this.catsService.findOneById(+id);
  }
github joe307bad / points / API.Points / src / auth / auth.controller.ts View on Github external
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

import { Roles } from './gaurds/roles';
import { RolesGuard } from './gaurds/roles';

@Controller('auth')
@UseGuards(RolesGuard)
export class AuthController {
  constructor() { }

  @Get('data')
  @UseGuards(AuthGuard('jwt'))
  @Roles('admin')
  findAll() {
    // this route is restricted
  }
}
github nestjs / nest / sample / 19-auth / src / auth / auth.controller.ts View on Github external
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from './auth.service';

@Controller('auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Get('token')
  async createToken(): Promise {
    return await this.authService.createToken();
  }

  @Get('data')
  @UseGuards(AuthGuard())
  findAll() {
    // this route is restricted by AuthGuard
    // JWT strategy
  }
}
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 jiayisheji / jianshu / apps / client / src / app / app.module.ts View on Github external
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AppRoutingModule } from './app-routing.module';


// 解决 DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
mongoose.set('useCreateIndex', true);

@Module({
  imports: [
    MongooseModule.forRoot('mongodb://localhost/jianshu', {
      useNewUrlParser: true,
      useUnifiedTopology: true
    }),
    PassportModule.register({
      defaultStrategy: 'jwt',
      session: true
    }),
    AppRoutingModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule { }
github mythal / boluo / server / src / app.module.ts View on Github external
import { Member } from './members/members.entity';
import { Invitation } from './invitaions/invitaions.entity';
import { MemberService } from './members/members.service';
import { RedisService } from './redis/redis.service';
import { DateScalar } from './scalars';
import { ChannelEventResolver } from './events/events.resolver';
import { EventService } from './events/events.service';
import { MediaService } from './media/media.service';
import { MediaResolver } from './media/media.resolver';
import { Media } from './media/media.entity';
import { MediaController } from './media/media.controller';
import { AuthResolver } from './auth/auth.resolver';
import { RandomService } from './random/random.service';

const imports = [
  PassportModule.register({ defaultStrategy: 'jwt' }),
  TypeOrmModule.forRoot({
    type: 'postgres',
    host: POSTGRES_HOST,
    port: POSTGRES_PORT,
    username: POSTGRES_USERNAME,
    password: POSTGRES_PASSWORD,
    database: POSTGRES_DATABASE,
    entities: [__dirname + '/**/*.entity{.ts,.js}'],
    synchronize: true,
  }),
  GraphQLModule.forRoot({
    autoSchemaFile: '../schema.graphql',
    // GraphQL Subscriptions authentication https://github.com/nestjs/docs.nestjs.com/issues/394
    context: ({ req, connection }) => (connection ? { req: { headers: connection.context } } : { req }),
    installSubscriptionHandlers: true,
    debug: DEBUG,

@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