在NestJS中获取Auth0用户信息

时间:2018-12-06 16:16:50

标签: javascript node.js typescript auth0 nestjs

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

在常规表达功能下,可以通过以下代码解决。我使用回调函数调用passport.authenticate('auth0',函数(err,用户,信息){})函数,并在其中接收用户日期。

// 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;
  }
}

1 个答案:

答案 0 :(得分:1)

似乎github上有example,如何将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);
}