nestjs passport-local


こんにちは、今期のテーマはpassport-localをnestjsに貼り付ける操作についてです.
この文章に挿入された部分
🧗‍♀️
@UseGuards(AuthGuard('local'))
で説明します.
nestjsドキュメント-passportに関連するセクションを表示できます.(注:https://docs.nestjs.com/security/authentication)
nestjsでpassport-localを使用するには、いくつかのステップが必要です.
ステップ1、
$ nest g module auth
$ nest g service auth
適切なファイルを作成します.
作成したファイルを紹介します.
auth.module.ts
import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Users } from 'src/entities/Users.entity';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { LocalStrategy } from './local.strategy';

@Module({
  imports: [PassportModule],
  providers: [AuthService, LocalStrategy],
})
export class AuthModule {}
似ている.
auth.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Users } from 'src/entities/Users.entity';
import { Repository } from 'typeorm';
import bcrypt from 'bcrypt';

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(Users) private userRepository: Repository<Users>,
  ) {}

  async validateUser(email: string, password: string): Promise<any> {
    const user = await this.userRepository.findOne({
      where: { email },
      select: ['email', 'password', 'nickname'],
    });

    if (!user) {
      return null;
    }

    const result = await bcrypt.compare(password, user.password);
    console.log('reuslt: ', result);

    if (result) {
      const { password, ...userWithoutPassword } = user;
      return userWithoutPassword;
    }
    return null;
  }
}
に表示されます.
2つの書類を整理した.
作成したlocalをnestjs公式ファイルにプロンプトします.次のようにポリシーファイルが作成されました.
auth/local.strategy.ts
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from './auth.service';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super();
  }

  async validate(username: string, password: string): Promise<any> {
    const user = await this.authService.validateUser(username, password);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}
ファイルを作成し、コードを入力するとpassportStrategyが使用されます.
そして今はpassportを使えばいいです
import { Controller, Request, Post, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Controller()
export class AppController {
  @UseGuards(AuthGuard('local'))
  @Post('auth/login')
  async login(@Request() req) {
    return req.user;
  }
}
上のコードに示すように.しかし、私にとって、一つの問題と一つの問題があります.
🤔質問:
どうしよう.
@UseGuards(AuthGuard('local'))
これを書いただけでauthGuardは働けますか?もちろん、nestjsが提供する装飾機能を使用しているからです.
AutheGuard(「local」)をどのように認識しますか?私はこのことに悩んでいる.
答えは
@UserGuard("local")と入力すると、nestjsの@UserGuardで作成したAuthGuardは@nestjs/passportから取得した情報であり、nestjsではlocalである.strategy.tsファイルで
export class LocalStrategy extends PassportStrategy(Strategy)
コードとして宣言してロードして使用することを確認します.
🤔質問:
なぜコードが完了しただけで、認証エラーが発生したのですか?
理由は.
http://www.passportjs.org/docs/username-password/
で参照できます.
デフォルトでは、およびLocalStrategyというパラメータに認証情報が表示されます.サイトがこれらのフィールドに異なる名前を指定する場合は、オプションを使用してデフォルト値を変更できます.ユーザー名のパスワード.
したがって、私の場合はusername->emailをパラメータとして使用する必要があるので、変更する必要があります.
local.strategy.ts

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super({ <- PassportStrategy의 객체의 매개변수를 아래와 같이 변경해야합니다.
      usernameField: 'email',
      password: 'password',
    });
  }