gpt4 book ai didi

javascript - 在 NestJS 中获取 Auth0 用户信息

转载 作者:搜寻专家 更新时间:2023-10-30 21:11:47 27 4
gpt4 key购买 nike

我正在尝试在 NestJS 中进行 Auth0 授权,但我不确定如何在回调 url 处理程序上获取用户数据。

在正常的 express 函数中,这可以通过下面的代码解决。我调用带有回调函数的 passport.authenticate('auth0', function (err, user, info) { }) 函数并在其中接收用户日期。

// Perform the final stage of authentication and redirect to previously requested URL or '/user'
router.get('/callback', function (req, res, next) {
passport.authenticate('auth0', function (err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function (err) {
if (err) { return next(err); }
const returnTo = req.session.returnTo;
delete req.session.returnTo;
res.redirect(returnTo || '/user');
});
})(req, res, next);
});

但我不确定这应该如何以 NestJS 风格完成。带有装饰器和守卫。在 NestJS 中,我添加了下一个函数。但是我应该如何获取用户的数据呢?

  @Get('cb')
async callback(): Promise<any> {
// WHAT SHOULD I CALL HERE?
}

auth.controller.ts

@Controller('auth')
export class AuthController {
constructor(
private readonly authService: AuthService,
) {}

@Get('login')
@UseGuards(AuthGuard('auth0'))
async login(): Promise<any> {
const v = this.configService.get('TEST');
return { r: 'ok1', v };
}

@Get('cb')
// @UseGuards(AuthGuard('auth0'))
async callback(): Promise<any> {
// WHAT SHOULD I CALL HERE?
}

}

auth0.strategy.ts

@Injectable()
export class Auth0Strategy extends PassportStrategy(Strategy) {
constructor(
private readonly authService: AuthService,
private readonly configService: ConfigService,
) {
super({
domain: 'zzzz',
clientID: 'zzzz',
clientSecret: 'zzzz',
callbackURL: '/auth/cb',
});
}

async validate(payload) {
console.log('Auth0Strategy payload', payload);
return payload;
}
}

最佳答案

好像有example在 github 上如何将 Nest.js 与 Auth0 一起使用。

如果你检查给定的例子,你会发现你需要做接下来的事情:

AuthController 中定义空回调端点:

@Get('/callback')
public callback() {}

定义中间件

@Injectable()
class Auth0CallbackMiddleware implements NestMiddleware {
resolve() {
return authenticate('auth0', {
successRedirect: '/user',
failureRedirect: '/'
}, (req, res) => {
if (!req.user) {
throw new Error('user null');
}
res.redirect("/");
}
);
}
}

使用那个中间件:

@Module({
providers: [Auth0Strategy, Auth0LoginMiddleware, Auth0CallbackMiddleware],
controllers: [AppController]
})
export class ApplicationModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer


.apply(Auth0LoginMiddleware)
.forRoutes({path: '/login', method: RequestMethod.ALL})

.apply(Auth0CallbackMiddleware)
.forRoutes({path: '/callback', method: RequestMethod.ALL})

.apply(EnsureLoggedIn)
.forRoutes({path: '/user', method: RequestMethod.ALL});

}
}

检查 Auth0Strategy 中的验证函数。在示例中,它看起来有点不同:

async (accessToken, refreshToken, extraParams, profile, done) => {
return done(null, profile);
}

关于javascript - 在 NestJS 中获取 Auth0 用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53655523/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com