NestJS:Auth 保护流程

NestJS : Auth guard flow

我正在 nestJS 中使用 passport 实现 linkedin 登录策略。 我现在拥有的是我有一个按钮“使用 linkedin 登录”指向 auth/linkedin

@Get('auth/linkedin')
@UseGuards(AuthGuard('linkedin'))
async linkedinAuth(@Req() req) {
    
}

效果很好,将我带到 linkedin 登录页面并返回我的回调 URL,它是 auth/linkedin/callbackcode 令牌查询字符串 和这个是我无法弄清楚要做什么以及如何 return linkedin user

的地方
@Get('auth/linkedin/callback')
@UseGuards(AuthGuard('linkedin'))
linkedinCallBack(@Req() req) {
  console.log(req)
  return 'handle callback!';
}

领英护照攻略:

import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
const LinkedInAuthStrategy = require('passport-linkedin-oauth2').Strategy;

@Injectable()
export class LinkedinStrategy extends PassportStrategy(LinkedInAuthStrategy) {
  constructor(
  ) {
    super({
      clientID: 'abcd123',
      clientSecret: 'abcd123',
      callbackURL: 'http://localhost:5000/auth/linkedin/callback',
      scope: ['r_emailaddress', 'r_liteprofile'],
    }, function(accessToken, refreshToken, profile, done) {
      process.nextTick(function () {
        console.log(profile);
        return done(null, profile);
      });
    })
  }
}

注意:我正在使用此 package 用于 linkedin 护照策略

Question : How can I handle callback further with @UseGuards, and return LinkedIn user?

您应该稍微调整一下 LinkedinStrategy class。您不能直接使用 done 函数。它将被嵌套调用。您应该有一个 validate 方法和 return 一个来自它的用户对象。该对象将被设置为请求对象,因此在控制器中您将能够使用 req.user 访问它。这大概是您的 class 应该看起来的样子:

import { Strategy } from 'passport-linkedin-oauth2';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from './auth.service';

@Injectable()
export class LinkedinStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super({
        clientID: 'abcd123',
        clientSecret: 'abcd123',
        callbackURL: 'http://localhost:5000/auth/linkedin/callback',
        scope: ['r_emailaddress', 'r_liteprofile'],
      });
  }

  async validate(accessToken: string, refreshToken: string, profile: object): Promise<any> {
    const user = await this.authService.validateUser(profile);

    return user;
  }
}

查看这篇文章:OAuth2 in NestJS for Social Login (Google, Facebook, Twitter, etc) and this repo: https://github.com/thisismydesign/nestjs-starter

LinkedinStrategyvalidate方法中,您需要查找或创建用户(可能存储在您的数据库中),例如:

export class LinkedinStrategy extends PassportStrategy(Strategy) {
  // constructor...

  async validate(accessToken, refreshToken, profile) {
    let user = await this.usersService.findOneByProvider('linkedin', profile.id);
    if (!user) {
      user = await this.usersService.create({
        provider: 'linkedin',
        providerId: id,
        name: profile.name,
        username: profile.email,
      });
    }

    return user;
  }
}

在控制器的回调端点中,您可以发出 JWT 令牌来处理应用内的用户会话:

@Get('auth/linkedin/callback')
@UseGuards(AuthGuard('linkedin'))
linkedinCallBack(@Req() req) {
  const { accessToken } = this.jwtAuthService.login(req.user);
  res.cookie('jwt', accessToken);
  return res.redirect('/profile');
}