我正在我的Loopback 4应用上设置Bearer Token身份验证,并且遵循以下常规实现:https://github.com/strongloop/loopback-next/tree/master/packages/authentication。
在我的src/providers/auth-strategy.provider.ts
中,我需要对存储库对象的引用才能查询我的数据源。我希望通过在正在使用的类的构造函数中使用@repository
装饰器进行依赖项注入来实现此目标。
但是,当我在由findOne()
装饰器创建的存储库引用中调用@repository
时,会产生以下错误:
TypeError: Cannot read property 'findOne' of undefined
这是我的auth-strategy.provider.ts
版本:
import {Provider, inject, ValueOrPromise} from '@loopback/context';
import {Strategy} from 'passport';
import {
AuthenticationBindings,
AuthenticationMetadata,
} from '@loopback/authentication';
import {IVerifyOptions} from 'passport-http-bearer';
import {ApiClient} from '../models';
import {ApiClientRepository} from '../repositories';
import {Strategy as BearerStrategy} from 'passport-http-bearer';
import {repository} from '@loopback/repository';
export class BearerStrategyProvider implements Provider<Strategy | undefined> {
constructor(
@inject(AuthenticationBindings.METADATA)
private metadata: AuthenticationMetadata,
@repository(ApiClientRepository)
private apiClientRepository: ApiClientRepository,
) {}
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);
} else {
return Promise.reject(`The strategy ${name} is not available.`);
}
}
async verify(
token: string,
done: (error: any, user?: any, options?: IVerifyOptions | string) => void,
) {
// call cb(null, false) when user not found
// call cb(null, user) when user is authenticated
let apiClient: ApiClient | null;
try {
apiClient = await this.apiClientRepository.findOne({
where: {Token: token},
});
if (apiClient) {
console.log("Found CLIENT!!! Here: " + apiClient.Email);
done(null, {user: apiClient});
} else {
// if token not found in DB:
done('Authentication Error.', false);
}
} catch (e) {
console.log(e);
}
}
}
答案 0 :(得分:3)
实际上,我认为在您的情况下,问题与此相同: https://github.com/strongloop/loopback-next/issues/1835
您应该将您的verify函数的上下文绑定到您的类,否则this
不是BearerStrategyProvider
而是BearerStrategy
,则this.apiClientRepository
在该类中不存在。您可以这样绑定它:
return new BearerStrategy(this.verify.bind(this));