Passport 登录不调用策略文件中的函数

Passport login not calling the function in strategy file

我正在尝试将 Passport 用于 SSO。我的问题是,当我使用任何选项登录时,一切都很好,除了 data saving... 我认为 strategy 文件中的 functions 没有被调用(日志是两者都不工作)。

例如Google strategy:

@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
  constructor(private userService: UserService) {
    super({
      clientID: GOOGLE_CLIENT_ID,
      clientSecret: GOOGLE_CLIENT_SECRET,
      callbackURL: 'http://localhost:4200',
      scope: ['email', 'profile'],
    });
  }

  async validate(
    accessToken: string,
    refreshToken: string,
    profile: any,
    done: VerifyCallback,
  ): Promise<any> {
    try {
      console.log(profile);
      const user = profile;
      this.userService.FindOrCreate(profile);
      done(null, user);
    } catch (err) {
      done(err, null);
    }
  }
}

控制器:

@Get('google')
  @UseGuards(AuthGuard('google'))
  async twitterauth(@Req() req) {
    return await this.authService.login(req.user);
  }

授权服务:

@Injectable()
export class AuthService {
  private readonly logger = new Logger(AuthService.name);
  constructor(
    private userService: UserService,
    private readonly jwtService: JwtService,
  ) {}

  async validateUser(email: string, password: string): Promise<User> {
    const user: User = await this.userService.findOne({
      where: { email },
    });
    if (!user) {
      return null;
    } else {
      if (await bcrypt.compare(password, user.password)) {
        return user;
      } else {
        this.logger.error('Password is incorrect.');
        return null;
      }
    }
  }

  async login(user: any) {
    const payload = { email: user.email, role: user.role };
    return {
      // eslint-disable-next-line @typescript-eslint/camelcase
      access_token: this.jwtService.sign(payload),
    };
  }
}

其他策略(fb, linkedin, instagram, github)都差不多,问题也一样

在聊天中发现的问题是 Google 在 OAuth 流程中调用的回调不是同一服务器的一部分,因此 NestJS 服务器无法做出反应传入数据,因此从未调用 validate

That callback route needs to point to your NestJS server so that it can handle the saving logic for the database,OR the angular applications needs to re-route the return to it back to the NestJS server. Either way, your validations aren't being called because your Nest server never gets the callback with all the sensitive information from Google

More than likely, it will be better to have the callback pointed at your server so that the data is formatted as Passport is expected.