[英]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
在LinkedinStrategy
的validate
方法中,您需要查找或創建用戶(可能存儲在您的數據庫中),例如:
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.