【问题标题】:issues with loopback4 jwt authenticationloopback4 jwt 身份验证问题
【发布时间】:2021-02-11 01:24:16
【问题描述】:

每当我使用 /login 或 /signup api 端点时,我都会遇到验证 jwt 令牌的问题。 这是我的用户控制器:

import {authenticate, TokenService} from '@loopback/authentication';
import {
  Credentials, MyUserService,
  TokenServiceBindings,
  User,
  UserRepository,
  UserServiceBindings
} from '@loopback/authentication-jwt';
import {inject} from '@loopback/core';
import {
  repository
} from '@loopback/repository';
import {
  get, getModelSchemaRef, post,

  requestBody
} from '@loopback/rest';
import {SecurityBindings, securityId, UserProfile} from '@loopback/security';
import {genSalt, hash} from 'bcryptjs';
import _ from 'lodash';
import {Users} from '../models';

const CredentialsRequestBody = {
  description: 'Input of login function',
  required: true,
  content: {
    'application/json': {schema: Users}
  }
}

export class UserController {
  constructor(
    @inject(TokenServiceBindings.TOKEN_SERVICE) public jwtService: TokenService,
    @inject(UserServiceBindings.USER_SERVICE) public userService: MyUserService,
    @inject(SecurityBindings.USER, {optional: true}) public user: UserProfile,
    @repository(UserServiceBindings.USER_REPOSITORY) protected userRepository: UserRepository,
  ) { }
  @post('/login', {
    responses: {
      '200': {
        description: 'Token',
        content: {
          'application/json': {
            schema: {
              type: 'object',
              properties: {
                token: {
                  type: 'string'
                }
              }
            }
          }
        }
      }
    }
  })
  async login(
    @requestBody(CredentialsRequestBody) creditionals: Credentials
  ): Promise<{token: string}> {
    console.log('hekkkkk')
    const user = await this.userService.verifyCredentials(creditionals);
    console.log('kayyy', user)
    const userProfile = this.userService.convertToUserProfile(user);
    console.log('break')
    const token = await this.jwtService.generateToken(userProfile);
    console.log('break 1')
    return {token};
  }

  @authenticate('jwt')
  @get('/whoami', {
    responses: {
      '200': {
        description: '',
        schema: {
          type: 'string'
        }
      }
    }
  })

  async whoAmI(
    @inject(SecurityBindings.USER) currentUserProfile: UserProfile
  ): Promise<string> {
    console.log('here')
    return currentUserProfile[securityId];
  }

  @post('/signup', {
    responses: {
      '200': {
        description: 'User',
        content: {
          'application/json': {
            schema: {
              'x-ts-type': User
            }
          }
        }
      }
    }
  })

  async signUp(
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(Users, {
            title: 'NewUser'
          })
        }
      }
    })
    newUserRequest: Users
  ): Promise<User> {
    const password = await hash(newUserRequest.password, await genSalt());
    const savedUser = await this.userRepository.create(
      _.omit(newUserRequest, 'password')
    );
    console.log('break 1')
    await this.userRepository.userCredentials(savedUser.id).create({password});
    console.log('break 2')

    return savedUser;
  }
}

这是我的 sequence.ts 文件:

import {
  AuthenticateFn,
  AuthenticationBindings,
  AUTHENTICATION_STRATEGY_NOT_FOUND,
  USER_PROFILE_NOT_FOUND
} from '@loopback/authentication';
import {
  Context
} from '@loopback/context';
import {inject} from '@loopback/core';
// import {MiddlewareSequence} from '@loopback/rest';
import {
  FindRoute,
  InvokeMethod,
  ParseParams,
  Reject, RequestContext,
  RestBindings,
  Send,
  SequenceActions,
  SequenceHandler
} from '@loopback/rest';

// export class MySequence extends MiddlewareSequence { }
export class MySequence implements SequenceHandler {
  constructor(
    @inject(RestBindings.Http.CONTEXT) public ctx: Context,
    @inject(SequenceActions.FIND_ROUTE) protected findRoute: FindRoute,
    @inject(SequenceActions.PARSE_PARAMS) protected parseParams: ParseParams,
    @inject(SequenceActions.INVOKE_METHOD) protected invoke: InvokeMethod,
    @inject(SequenceActions.SEND) public send: Send,
    @inject(SequenceActions.REJECT) public reject: Reject,
    @inject(AuthenticationBindings.AUTH_ACTION)
    protected authenticateRequest: AuthenticateFn
  ) { }
  async handle(context: RequestContext) {
    try {
      const {request, response} = context;
      const route = this.findRoute(request);
      console.log('jau', route)
      await this.authenticateRequest(request);
      const args = await this.parseParams(request, route);
      console.log('kel', args, response, await this.invoke(route, args))
      const result = await this.invoke(route, args);
      console.log('pop', result, response)
      this.send(response, result);
      console.log('done1')
    }
    catch (err) {
      console.log('may', err.code)
      if (
        err.code === AUTHENTICATION_STRATEGY_NOT_FOUND ||
        err.code === USER_PROFILE_NOT_FOUND
      ) {
        Object.assign(err, {statusCode: 401});
      }
      this.reject(context, err)
      console.log('done2')
    }
  }
}

如果您想了解 db.我已经连接到 mongodb 并且没有连接问题。

我收到 statusCode 500 和以下问题:

Request POST /login failed with status code 500. ResolutionError: The key 'repositories.repositories.UserRepository' is not bound to any value in context RequestContext-nP8Bsm4XRqSs9_f7D1VuEQ-3 (context: RequestContext-nP8Bsm4XRqSs9_f7D1VuEQ-3, binding: repositories.repositories.UserRepository, resolutionPath: controllers.UserController --> @UserController.constructor[3])

如果您需要访问整个代码库,请查看: https://github.com/compressionmonkey/dummyloopbackserver

我已经在谷歌上搜索了一周的问题(我观看了多个教程,包括来自 IBM 的教程,并与 IBM github 代码库进行了交叉检查)所以最后我在 stackoverflow 上提出了这个问题。

感谢您提出建设性的反馈。谢谢!

【问题讨论】:

  • 看起来您的问题已在 github.com/strongloop/loopback-next/issues/6964 中得到解答。如果您有其他问题,请随时 ping 那里或打开一个新问题。谢谢。
  • 我在遇到这个问题后再次更新了我的问题

标签: javascript typescript jwt loopbackjs loopback4


【解决方案1】:

以下更改可以帮助解决问题:

user.controller.ts中更改这一行:

@repository(UserServiceBindings.USER_REPOSITORY) protected userRepository: UserRepository,

@repository(UserRepository) protected userRepository: UserRepository,

问题原因: UserServiceBindings.USER_REPOSITORY 在运行时转换为 repositories.repositories.UserRepository,然后应用程序试图用它找到存储库。由于存储库实际上存在于应用程序上下文中,键为 repositories.UserRepository,因此无法找到存储库并因此引发异常。

以下调试画面有助于更好理解,请查看:

Check VSCode debug screenshot by clicking here

在图片中,我稍微修改了代码以实时展示问题:

  • 1 显示预期的代码行。
  • 2使用isBound方法检查键是否绑定到应用上下文中的某个东西。
  • 3 显示了两个绑定键的 isBound 方法的布尔结果。

希望这个回答对你有帮助。

【讨论】:

    猜你喜欢
    • 2021-02-11
    • 2019-08-04
    • 1970-01-01
    • 2018-02-06
    • 2020-04-10
    • 2018-08-20
    • 2020-09-03
    • 2019-12-04
    • 2015-06-20
    相关资源
    最近更新 更多