我正在执行领英登录策略与护照在nestJS。我现在拥有的是,我有一个按钮“登录和领英”指向auth/linkedin
。
@Get('auth/linkedin')
@UseGuards(AuthGuard('linkedin'))
async linkedinAuth(@Req() req) {
}
它工作得很好,并带我访问linkedin登录页面,并回击我的回调URL,它是auth/linkedin/callback
,带有令牌的code
查询字符串,这是我无法确定该做什么以及如何返回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);
});
})
}
}
注意:我使用这个https://github.com/auth0/passport-linkedin-oauth2作为领英护照策略
@UseGuards
**,问题:如何使用进一步处理回调并返回LinkedIn用户?**
发布于 2021-06-18 14:31:39
查看本文:OAuth2 in NestJS for Social Login (Google、Facebook、Twitter等)和这个回购:https://github.com/thisismydesign/nestjs-starter
在validate
的LinkedinStrategy
方法中,您需要找到或创建用户(可能存储在DB中),例如:
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');
}
发布于 2021-03-02 11:22:02
您应该稍微修改一下LinkedinStrategy
类。不能直接使用done
函数。它将被鸟巢所调用。您应该有一个validate
方法并从它返回一个用户对象。该对象将被设置为request对象,因此在控制器中,您将能够使用req.user
访问它。这大概是您的班级应该看到的样子:
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;
}
}
https://stackoverflow.com/questions/66435392
复制相似问题