如何在基于GraphQL的nestjs中实现Auth0策略

时间:2019-08-10 03:07:06

标签: graphql auth0 nestjs

我正在尝试在Nestjs应用中实施passport-auth0策略,并且我将GraphQl用于api,最后我还是选择了其中一个

  

TypeError:res.setHeader不是Auth0 Strategy.strategy.redirect的函数   要么   使用状态时,OAuth 2.0身份验证需要会话支持。您忘了使用快速会话中间件吗?

我已经按照nestjs文档中的说明进行操作,但问题仍然存在,并且我仍然检查github存储库仍然没有成功

    import { use, serializeUser, deserializeUser } from 'passport';
    import { Strategy } from 'passport-auth0';
    import { Injectable } from '@nestjs/common';
    import { environment } from '../../environments/environment';
    import { PassportStrategy } from '@nestjs/passport';

    @Injectable()
    export class Auth0Strategy extends PassportStrategy(Strategy) {
    constructor() {
    super(
      {
        domain: environment.auth0.domain,
        clientID: environment.auth0.clientID,
        clientSecret: environment.auth0.clientSecret,
        callbackURL: environment.auth0.callbackURL,
        state: false // or true
      },
      async (accessToken, refreshToken, extraParams, profile, done) => {
        return done(null, profile);
      }
    );
    use(this);

    serializeUser((user, done) => {
      done(null, user);
    });

    deserializeUser((user, done) => {
      done(null, user);
    });
    }
    }

    import { Injectable, ExecutionContext } from '@nestjs/common';

    import { AuthGuard } from '@nestjs/passport';

    import { GqlExecutionContext } from '@nestjs/graphql';

    @Injectable()
    export class Auth0Guard extends AuthGuard('auth0') {
    getRequest(context: ExecutionContext) {
    const ctx = GqlExecutionContext.create(context);
    return ctx.getContext().req;
    }
    }

1 个答案:

答案 0 :(得分:0)

我设法使用passport-jwtjwks-rsa通过auth0进行身份验证。

import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt';
import { passportJwtSecret } from 'jwks-rsa';

import { JwtPayload } from './interfaces/jwt-payload.interface';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      secretOrKeyProvider: passportJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`,
      }),

      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      audience: process.env.AUTH0_AUDIENCE,
      issuer: `https://${process.env.AUTH0_DOMAIN}`,
    });
  }

  validate(payload: JwtPayload): JwtPayload {
    const minimumScope = ['openid', 'profile', 'email'];

    if (
      payload.scope.split(' ').filter(scope => minimumScope.indexOf(scope) > -1)
        .length !== 3
    ) {
      throw new UnauthorizedException(
        'JWT does not possess the requires scope (`openid profile email`).',
      );
    }

    return payload;
  }
}

可以在https://github.com/jajaperson/nestjs-auth0上找到完整的模板存储库