Currently i'm stuck with a problem inside our LoopBack4 application. We have some controllers. We are using JWT for Authorization. Inside the tokens payload we store a list of rights, granted for the requesting user. Also, we added an AuthorizationInterceptor to check permissions.
I made the mistake, to write the token-data into a static variable and request it from services and other locations inside my application. If there are concurrent requests incoming, one request overwrites the token of the other request. Request A is now working with the rights of request B.
Problem:
- A client makes a request A to the LB4 application containing a token
- The application stores the token in a static variable
- At the same time an incoming request B transfers a different token
- The application overwrites the token of request A with the token of request B
- Request A works with the rights of request B
Application:
Every Controller:
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 // a simple file including small functions
export function getMyUserId(): number
{
return ((JWTService.AuthToken && JWTService.AuthToken.UserId) || 0);
}
On top of that we have implemented some services to handle the big stuff. What i now need is a solution to access the users data inside services and other parts of the application, for example the token of the authorized user. Where and how do i have to place the token?
I found a reference on StackOverflow and GitHub: How to use stateful requests in Loopback 4? -> https://github.com/strongloop/loopback-next/issues/1863
In both is the explanation, that i have to add const session = this.restoreSession(context);
to an own sequence.ts. I've done that, but restoreSession is not a function.
I also found the suggestion to use the package express-session. That does not help here, because our client is not capable of storing cookies.