目前,我在LoopBack4应用程序内部遇到问题。我们有一些控制器。我们正在使用JWT进行授权。在令牌有效负载内部,我们存储了为请求用户授予的权限列表。另外,我们添加了AuthorizationInterceptor来检查权限。
我犯了一个错误,将令牌数据写入一个静态变量,并从我的应用程序中的服务和其他位置请求它。如果有并发请求传入,则一个请求将覆盖另一个请求的令牌。现在,请求A拥有请求B的权限。
问题:
应用程序:
每个控制器:
export class MiscController
{
constructor(@inject(AServiceBindings.VALUE) public aService: AService) {}
@get('/hasright', {})
@authenticate('jwt', {"required":[1,2,3]}) // this gets checked by AuthorizationInterceptor
async getVersion(): Promise<object>
{
return {hasRight: JWTService.checkRight(4)};
}
}
jwt-service:
export class JWTService implements TokenService
{
static AuthToken: Authtoken|null;
static rights: number[];
// constructor ...
/** A method to check rights */
static hasRight(rightId: number): boolean
{
return inArray(rightId, JWTService.rights);
}
async verifyToken(token: string): Promise<UserProfile>
{
// verify the token ...
// write the Tokendata to static variables
JWTService.AuthToken = authtoken;
JWTService.rights = rightIds;
return userProfile;
}
}
export const JWTServiceBindings = {
VALUE: BindingKey.create<JWTService>("services.JWTService")
};
AuthorizeInterceptor.ts
@globalInterceptor('', {tags: {name: 'authorize'}})
export class AuthorizationInterceptor implements Provider<Interceptor>
{
constructor(
@inject(AuthenticationBindings.METADATA) public metadata: AuthenticationMetadata,
@inject(TokenServiceBindings.USER_PERMISSIONS) protected checkPermissions: UserPermissionsFn,
@inject.getter(AuthenticationBindings.CURRENT_USER) public getCurrentUser: Getter<MyUserProfile>
) {}
/**
* This method is used by LoopBack context to produce an interceptor function
* for the binding.
*
* @returns An interceptor function
*/
value()
{
return this.intercept.bind(this);
}
/**
* The logic to intercept an invocation
* @param invocationCtx - Invocation context
* @param next - A function to invoke next interceptor or the target method
*/
async intercept(invocationCtx: InvocationContext, next: () => ValueOrPromise<InvocationResult>)
{
if(!this.metadata)
{
return next();
}
const requiredPermissions = this.metadata.options as RequiredPermissions;
const user = await this.getCurrentUser();
if(!this.checkPermissions(user.permissions, requiredPermissions))
{
throw new HttpErrors.Forbidden('Permission denied! You do not have the needed right to request this function.');
}
return next();
}
}
JWTAuthenticationStrategy
export class JWTAuthenticationStrategy implements AuthenticationStrategy
{
name = 'jwt';
constructor(@inject(JWTServiceBindings.VALUE) public tokenService: JWTService) {}
async authenticate(request: Request): Promise<UserProfile | undefined>
{
const token: string = this.extractCredentials(request);
return this.tokenService.verifyToken(token);
}
// extract credentials etc ...
}
application.ts
export class MyApplication extends BootMixin(ServiceMixin(RepositoryMixin(RestApplication)))
{
constructor(options: ApplicationConfig = {})
{
super(options);
// Bind authentication component related elements
this.component(AuthenticationComponent);
registerAuthenticationStrategy(this, JWTAuthenticationStrategy);
this.bind(JWTServiceBindings.VALUE).toClass(JWTService);
this.bind(TokenServiceBindings.USER_PERMISSIONS).toProvider(UserPermissionsProvider);
this.bind(TokenServiceBindings.TOKEN_SECRET).to(TokenServiceConstants.TOKEN_SECRET_VALUE);
// Set up the custom sequence
this.sequence(MySequence);
// many more bindings and other stuff to do ...
}
}
sequence.ts
export class MySequence implements SequenceHandler
{
// constructor ...
async handle(context: RequestContext)
{
// const session = this.restoreSession(context); // restoreSession is not a function.
try
{
const {request, response} = context;
const route = this.findRoute(request);
// call authentication action
await this.authenticateRequest(request);
userId = getMyUserId(); // using helper method
// Authentication successful, proceed to invoke controller
const args = await this.parseParams(request, route);
const result = await this.invoke(route, args);
this.send(response, result);
}
catch(err)
{
this.reject(context, err);
}
finally
{
// some action using userId p.e. ...
}
}
}
helper.ts //一个包含小功能的简单文件
export function getMyUserId(): number
{
return ((JWTService.AuthToken && JWTService.AuthToken.UserId) || 0);
}
最重要的是,我们已经实施了一些服务来处理大事。我现在需要的是一种在服务和应用程序其他部分中访问用户数据的解决方案,例如授权用户的令牌。我必须在哪里以及如何放置令牌?
我在StackOverflow和GitHub上找到了参考:How to use stateful requests in Loopback 4?-> https://github.com/strongloop/loopback-next/issues/1863
两者都是解释,我必须将const session = this.restoreSession(context);
添加到自己的sequence.ts中。我已经做到了,但是restoreSession不是一个函数。
我还发现了使用Express-Session软件包的建议。这无济于事,因为我们的客户端无法存储cookie。
根据此文档,我找到了一个解决方案:https://github.com/strongloop/loopback-next/blob/607dc0a3550880437568a36f3049e1de66ec73ae/docs/site/Context.md#request-level-context-request
我做了什么?
export class MySequence implements SequenceHandler
{
// constructor ...
async handle(context: RequestContext)
{
try
{
const {request, response} = context;
const route = this.findRoute(request);
// call authentication action
const userProfile = await this.authenticateRequest(request);
// userId = getMyUserId(); is removed, due to the fact, that we now store the value in a bind method, see next lines
context.bind('MY_USER_ID').to(userProfile.id); // this is the essential part. "MY_USER_ID" is a key and we bind a value to that key based on the context (request)
// Authentication successful, proceed to invoke controller
const args = await this.parseParams(request, route);
const result = await this.invoke(route, args);
this.send(response, result);
}
catch(err)
{
this.reject(context, err);
}
finally
{
// some action using userId p.e. ...
}
}
}
export class JWTService implements TokenService
{
// static AuthToken: Authtoken|null; // not needed anymore
// static rights: number[]; // not needed anymore
// constructor ...
/** A method to check rights */
/* this is not possible anymore
static hasRight(rightId: number): boolean
{
return inArray(rightId, JWTService.rights);
}
*/
async verifyToken(token: string): Promise<UserProfile>
{
// verify the token ...
// do not write the Tokendata to static variables
// JWTService.AuthToken = authtoken;
// JWTService.rights = rightIds;
return userProfile;
}
}
export class aController
{
constructor(
@inject('MY_USER_ID') public authorizedUserId: number
// here comes the injection of the bound value from the context
) {}
@get('/myuserid', {})
@authenticate('jwt', {})
async getVersion(): Promise<object>
{
return this.authorizedUserId;
// authorizedUserId is a variable instantiated with the constructors dependency injection
}
}
每个控制器和每个在序列之后加载的服务(jwt-service除外)都可以注入绑定值并可以使用它。
这有点棘手,因为链接的文档并未完全涵盖此方法,但毕竟对我而言它现在可以使用。如果有人有更好的解决方案,请现在让我解决!