[英]Get Auth0 user info in NestJS
我試圖在NestJS中進行Auth0授權,但我不知道如何在回調url處理程序上獲取用戶的數據。
在正常表達功能下,這可以通過下面的代碼解決。 我使用回調函數調用passport.authenticate('auth0',函數(錯誤,用戶,信息){})函數並在其中接收用戶日期。
// 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?
}
@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?
}
}
@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;
}
}
似乎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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.