繁体   English   中英

NestJS:身份验证保护流程

[英]NestJS : Auth guard flow

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

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

效果很好,将我带到linkedin登录页面并回击我的回调URL,这是带有令牌code查询字符串的auth/linkedin/callback这就是我无法弄清楚要做什么以及如何返回linkedin用户的地方

@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 护照策略

问题:如何使用@UseGuards进一步处理回调,并返回 LinkedIn 用户?

您应该稍微调整一下LinkedinStrategy class。 您不能直接使用已done的 function。 它将被嵌套调用。 您应该有一个validate方法并从中返回一个用户 object。 object 将被设置为请求 object 因此在 controller 中,您将能够使用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;
  }
}

检查这篇文章: NestJS 中的 OAuth2 用于社交登录(Google、Facebook、Twitter 等)和这个仓库: https-js://github.com/thisism

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 令牌来处理应用内用户的 session:

@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');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM