gpt4 book ai didi

javascript - 有效的 JWT 对 nestJS 守卫无效

转载 作者:行者123 更新时间:2023-12-04 08:20:27 25 4
gpt4 key购买 nike

我正在通过凭据 header 将 JWT 从我的客户端应用程序(带有 nextAuth 的 nextJS)传递到我的后端 nestJS 应用程序(使用 graphQL)。在我的 nestJS 后端应用程序中,我试图实现一个身份验证保护,所以我在 jwt.strategy.ts 中使用自定义函数提取了 JWT
但是 JwtStrategy 不接受我的有效签名 token 。为了证明 JWT 是有效的,我为 token 放置了一些控制台输出。但是validate()函数永远不会被调用。我不明白为什么,因为可以使用 jwt.verify 验证 token :
这是我的输出 - 它由 jwt.verify() 解码:

JWT: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7InVzZXJJZCI6MTIzLCJ1c2VybmFtZSI6InVzZXJuYW1lIiwiaXNBZG1pbiI6dHJ1ZX0sImlhdCI6MTYwOTY3NTc4Nn0.LQy4QSesxJR91PyGGb_0mGZjpw9hlC4q7elIDs2CkLo
Secret: uGEFpuMDDdDQA3vCtZXPKgBYAriWWGrk
Decoded: {
user: { userId: 123, username: 'username', isAdmin: true },
iat: 1609675786
}
我不明白,我缺少什么,我什至不知道如何调试它,因为我的 jwt.strategy.ts 中没有输出,并且根本没有调用验证函数。
jwt.strategy.ts
import jwt from 'jsonwebtoken'
// import { JwtService } from '@nestjs/jwt'
import { Strategy } from 'passport-jwt'
import { PassportStrategy } from '@nestjs/passport'
import { Injectable } from '@nestjs/common'
import cookie from 'cookie'

import { getConfig } from '@myapp/config'
const { secret } = getConfig()

const parseCookie = (cookies) => cookie.parse(cookies || '')

const cookieExtractor = async (req) => {
let token = null
if (req?.headers?.cookie) {
token = parseCookie(req.headers.cookie)['next-auth.session-token']
}

// output as shown above
console.log('JWT:', token)
console.log('Secret:', secret)
const decoded = await jwt.verify(token, secret, { algorithms: ['HS256'] })
console.log('Decoded: ', decoded)

return token
}

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: cookieExtractor,
ignoreExpiration: true,
secretOrKey: secret
})
}

async validate(payload: any) {
console.log('payload:', payload) // is never called

return { userId: payload.sub, username: payload.username }
}
}
jwt-auth.guard.ts
import { Injectable, ExecutionContext } from '@nestjs/common'
import { AuthGuard } from '@nestjs/passport'
import { GqlExecutionContext } from '@nestjs/graphql'

@Injectable()
export class GqlAuthGuard extends AuthGuard('jwt') {
getRequest(context: GqlExecutionContext) {
const ctx = GqlExecutionContext.create(context)
return ctx.getContext().req
}
}
此解析器中使用了 guard :
editor.resolver.ts
import { Query, Resolver } from '@nestjs/graphql'
import { UseGuards } from '@nestjs/common'
import { GqlAuthGuard } from '../auth/jwt-auth.guard'

@Resolver('Editor')
export class EditorResolvers {
constructor(private readonly editorService: EditorService) {}

@UseGuards(GqlAuthGuard)
@Query(() => [File])
async getFiles() {
return this.editorService.getFiles()
}
}
auth.module.ts
import { Module } from '@nestjs/common'
import { AuthController } from './auth.controller'
import { AuthService } from './auth.service'
import { PassportModule } from '@nestjs/passport'
import { LocalStrategy } from './local.strategy'
import { JwtStrategy } from './jwt.strategy'
import { UsersModule } from '../users/users.module'
import { JwtModule } from '@nestjs/jwt'

import { getConfig } from '@myApp/config'
const { secret } = getConfig()

@Module({
imports: [
UsersModule,
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secret,
verifyOptions: { algorithms: ['HS256'] },
signOptions: { expiresIn: '1d' }
})
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy, LocalStrategy],
exports: [AuthService]
})
export class AuthModule {}
token 是在服务器端(nextJS api 页面)创建的:
const encode = async ({ secret, token }) => jwt.sign(token, secret, { algorithm: 'HS256' })

最佳答案

我从您的 中看到了与 nestJS 文档示例的两个不同之处jwt.strategy.ts 您可以更改的文件并尝试一下..
https://docs.nestjs.com/security/authentication#implementing-passport-jwt

  • 同步提取器而不是异步

  • 默认情况下,passport-jwt 提取器我们可以看到它是同步而不是异步,因此您可以尝试更改提取器并删除异步,或者在调用它时添加等待。
    https://github.com/mikenicholson/passport-jwt/blob/master/lib/extract_jwt.js ,
    寻找 fromAuthHeaderAsBearerToken 功能。
    所以或改变你的
    const cookieExtractor = async (req) => {
    const cookieExtractor = (req) => {
    或者 - 在调用时添加 await
    jwtFromRequest: await cookieExtractor(),
  • 调用提取器而不只是传递它

  • 通过 中的文档示例JwtStrategy 构造函数 他们调用提取器而不是像你一样传递它
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    所以试着在你的 中调用它JwtStrategy 构造函数
    jwtFromRequest: cookieExtractor(),    // (again - take care of sync / async)

    关于javascript - 有效的 JWT 对 nestJS 守卫无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65525976/

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