首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >NestJS : Auth保护流程

NestJS : Auth保护流程
EN

Stack Overflow用户
提问于 2021-03-02 07:56:18
回答 2查看 3.3K关注 0票数 2

我正在执行领英登录策略与护照在nestJS。我现在拥有的是,我有一个按钮“登录和领英”指向auth/linkedin

代码语言:javascript
运行
复制
@Get('auth/linkedin')
@UseGuards(AuthGuard('linkedin'))
async linkedinAuth(@Req() req) {
    
}

它工作得很好,并带我访问linkedin登录页面,并回击我的回调URL,它是auth/linkedin/callback,带有令牌code查询字符串,这是我无法确定该做什么以及如何返回linkedin用户的地方。

代码语言:javascript
运行
复制
@Get('auth/linkedin/callback')
@UseGuards(AuthGuard('linkedin'))
linkedinCallBack(@Req() req) {
  console.log(req)
  return 'handle callback!';
}

领英护照策略:

代码语言:javascript
运行
复制
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);
      });
    })
  }
}

注意:我使用这个https://github.com/auth0/passport-linkedin-oauth2作为领英护照策略

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-06-18 14:31:39

查看本文:OAuth2 in NestJS for Social Login (Google、Facebook、Twitter等)和这个回购:https://github.com/thisismydesign/nestjs-starter

validateLinkedinStrategy方法中,您需要找到或创建用户(可能存储在DB中),例如:

代码语言:javascript
运行
复制
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令牌来处理应用程序中的用户会话:

代码语言:javascript
运行
复制
@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');
}
票数 1
EN

Stack Overflow用户

发布于 2021-03-02 11:22:02

您应该稍微修改一下LinkedinStrategy类。不能直接使用done函数。它将被鸟巢所调用。您应该有一个validate方法并从它返回一个用户对象。该对象将被设置为request对象,因此在控制器中,您将能够使用req.user访问它。这大概是您的班级应该看到的样子:

代码语言:javascript
运行
复制
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;
  }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66435392

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档