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



我正在尝试在 Nestjs 应用程序中实现 passport-auth0 策略,并且我正在使用 GraphQl for 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;
}
}

我设法使用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

最新更新