как сделать аутентификацию @ loopback / cli
версия: 1.24.0 с @ loopback / authentication: ^ 3.2.1, потому что, если я делаю показ этой ошибки после хеттинга аутентифицированного API Необработанная ошибка в GET / users /count: 500 Ошибка: стратегия BearerStrategy недоступна. в этом коде все очень хорошо, но только декоратор аутентификации не работает, если я специфичен для аутентификации API с @authenication (), это означает, что он работает, но не работает в коде, просто получая Respose без требования токенафайл
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',
content: { 'application/json': { schema: CountSchema } },
},
},
})
async updateAll(
@requestBody({
content: {
'application/json': {
schema: getModelSchemaRef(User, { partial: true }),
},
},
})
user: User,
@param.query.object('where', getWhereSchemaFor(User)) where?: Where<User>,
): Promise<Count> {
return this.userRepository.updateAll(user, where);
}
@get('/users/{id}', {
responses: {
'200': {
description: 'User model instance',
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, { partial: true }),
},
},
})
user: 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);
}
}