loopback 4为什么loopback4身份验证错误

如何进行身份验证@ loopback / cli

版本:1.24.0,带有@ loopback /身份验证:^ 3.2.1 因为如果我在验证身份验证的API后显示此错误, GET / users / count中未处理的错误:500错误:策略“ BearerStrategy”不可用。 在这段代码中,一切都很好,但是如果我使用@authenication()对特定的API进行身份验证,则只有身份验证装饰器无法正常工作,这意味着可以工作,但在没有任何令牌要求的情况下只是简单地重新放置代码就无法工作

这是我的application.ts文件

import { BootMixin } from '@loopback/boot';
import { Applicationconfig } from '@loopback/core';
import {
  RestExplorerBindings,RestExplorerComponent,} from '@loopback/rest-explorer';
import { RepositoryMixin } from '@loopback/repository';
import { RestApplication } from '@loopback/rest';
import { ServiceMixin } from '@loopback/service-proxy';
import * as path from 'path';
import { MySequence } from './sequence';
//
import {
  AuthenticationComponent,AuthenticationBindings,} from '@loopback/authentication';
import { AuthStrategyProvider } from './providers/auth-strategy.provider';

// avobe these two line added


export class TestApiapplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),) {
  constructor(options: Applicationconfig = {}) {
    super(options);

    // Set up the custom sequence
    this.sequence(MySequence);

    // Set up default home page
    this.static('/',path.join(__dirname,'../public'));

    // Customize @loopback/rest-explorer configuration here
    this.bind(RestExplorerBindings.CONFIG).to({
      path: '/explorer',});
    this.component(RestExplorerComponent);



    // [NEW CODE]  here added
    this.component(AuthenticationComponent);
    this.bind(AuthenticationBindings.AUTHENTICATION_STRATEGY_EXTENSION_POINT_NAME).toProvider(
      AuthStrategyProvider,);
    // [Until here] //

    this.projectRoot = __dirname;
    // Customize @loopback/boot Booter Conventions here
    this.bootOptions = {
      controllers: {
        // Customize ControllerBooter Conventions here
        dirs: ['controllers'],extensions: ['.controller.js'],nested: true,},};
  }
}

`**和这里** auth-strategy.provider.ts

import { Provider,inject,ValueOrPromise } from '@loopback/context';
import { Strategy } from 'passport';
import {
  AuthenticationBindings,Authenticationmetadata,} from '@loopback/authentication';
import { Strategy as BearerStrategy } from 'passport-http-bearer';
import { repository } from '@loopback/repository';
import { UserRepository } from '../repositories';
import { verify } from 'jsonwebtoken';

import { IVerifyOptions } from 'passport-http-bearer';
//import {BasicStrategy} from "passport-http";
export class AuthStrategyProvider implements Provider<Strategy | undefined> {

  constructor(
    @repository(UserRepository) public userRepository: UserRepository,@inject(AuthenticationBindings.MetaDATA) private metadata: Authenticationmetadata,) { }

  value(): ValueOrPromise<Strategy | undefined> {
    // The function was not decorated,so we shouldn't attempt authentication
    if (!this.metadata) {
      return undefined;
    }
    const name = this.metadata.strategy;
    if (name === "BearerStrategy") {
      return new BearerStrategy(this.verify.bind(this));
    } else {
      return Promise.reject(`The strategy ${name} is not available.`);
    }
  }

  async verify(
    token: string,cb: (err: Error | null,user?: object | false) => void,) {
    try {
      const user = verify(token,'PrivateKey');
      cb(null,Object);
    } catch (ex) {
      cb(null,false);
    }
  }
} 

此处为控制器文件 user-controllter.ts

import { Count,CountSchema,Filter,repository,Where,} from '@loopback/repository';
import { post,param,get,getFilterSchemaFor,getModelSchemaRef,getWhereSchemaFor,patch,put,del,requestBody,} from '@loopback/rest';
import { User } from '../models';
import { UserRepository } from '../repositories';

//
import * as bcrypt from 'bcrypt';
import { pick } from 'lodash';
import { globalConfig } from '../global-config/global-config';
import { authenticate } from '@loopback/authentication';
class credentialsClass {
  email: string;
  password: string;
}

export class UserController {
  constructor(@repository(UserRepository) public userRepository: UserRepository) { }
  @post('/users',{
    responses: {
      '200': {
        description: 'User model instance',content: { 'application/json': { schema: { 'x-ts-type': User } } },})
  async create(@requestBody() user: User): Promise<User> {
    let hashed = await bcrypt.hash(user.password,globalConfig.salt);
    user.password = hashed;
    user = await this.userRepository.create(user);
    return pick(user,['id','username','email']) as any;
  }
  @authenticate('BearerStrategy')
  @get('/users/count',{
    responses: {
      '200': {
        description: 'User model count',content: { 'application/json': { schema: CountSchema } },})
  async count(
    @param.query.object('where',getWhereSchemaFor(User)) where?: Where<User>,): Promise<Count> {
    return this.userRepository.count(where);
  }

  @get('/users',{
    responses: {
      '200': {
        description: 'Array of User model instances',content: {
          'application/json': {
            schema: { type: 'array',items: getModelSchemaRef(User) },})
  async find(
    @param.query.object('filter',getFilterSchemaFor(User)) filter?: Filter<User>,): Promise<User[]> {
    return this.userRepository.find(filter);
  }

  @patch('/users',{
    responses: {
      '200': {
        description: 'User PATCH success count',})

  async updateAll(
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(User,{ partial: true }),})
    user: User,@param.query.object('where',): Promise<Count> {
    return this.userRepository.updateAll(user,where);
  }

  @get('/users/{id}',content: { 'application/json': { schema: getModelSchemaRef(User) } },})
  async findById(@param.path.string('id') id: string): Promise<User> {
    return this.userRepository.findById(id);
  }

  @patch('/users/{id}',{
    responses: {
      '204': {
        description: 'User PATCH success',})
  async updateById(
    @param.path.string('id') id: string,@requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(User,): Promise<void> {
    await this.userRepository.updateById(id,user);
  }

  @put('/users/{id}',{
    responses: {
      '204': {
        description: 'User PUT success',})
  async replaceById(
    @param.path.string('id') id: string,@requestBody() user: User,): Promise<void> {
    await this.userRepository.replaceById(id,user);
  }
  @authenticate('BearerStrategy')
  @del('/users/{id}',{
    responses: {
      '204': {
        description: 'User DELETE success',})
  async deleteById(@param.path.string('id') id: string): Promise<void> {
    await this.userRepository.deleteById(id);
  }
}
yellowmin 回答:loopback 4为什么loopback4身份验证错误

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3138108.html

大家都在问