Skip to content

Commit

Permalink
fix: evaluate async conditions in the custom bearer token interceptor
Browse files Browse the repository at this point in the history
  • Loading branch information
Tlepel committed Jan 28, 2025
1 parent 1355170 commit fa5a2dc
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -92,4 +92,30 @@ describe('customBearerTokenInterceptor', () => {
});
});
});

it('should evaluate multiple async conditions and apply the correct one', (done) => {
TestBed.overrideProvider(CUSTOM_BEARER_TOKEN_INTERCEPTOR_CONFIG, {
useValue: [
{
shouldAddToken: async (req, next, keycloak) => false
},
{
shouldAddToken: async (req, next, keycloak) => req.url.startsWith('/api') && keycloak.authenticated,
authorizationHeaderName: 'DifferentAuthorization'
}
] as CustomBearerTokenCondition[]
});

TestBed.runInInjectionContext(() => {
const result = customBearerTokenInterceptor(request, handlerFn);

result.subscribe(() => {
expect(handlerFn).toHaveBeenCalled();
const forwardedRequest = handlerFn.calls.mostRecent().args[0] as HttpRequest<unknown>;
expect(forwardedRequest.headers.get('DifferentAuthorization')).toBe('Bearer mockToken');
done();
});
});

})
});
Original file line number Diff line number Diff line change
Expand Up @@ -109,14 +109,22 @@ export const customBearerTokenInterceptor = (

const keycloak = inject(Keycloak);

const matchingCondition = conditions.find(async (condition) => await condition.shouldAddToken(req, next, keycloak));
if (!matchingCondition) {
return next(req);
}
return from(
Promise.all(conditions.map(async (condition) => await condition.shouldAddToken(req, next, keycloak)))
).pipe(
mergeMap((evaluatedConditions) => {
const matchingConditionIndex = evaluatedConditions.findIndex(Boolean);
const matchingCondition = conditions[matchingConditionIndex];

return from(conditionallyUpdateToken(req, keycloak, matchingCondition)).pipe(
mergeMap(() =>
keycloak.authenticated ? addAuthorizationHeader(req, next, keycloak, matchingCondition) : next(req)
)
if (!matchingCondition) {
return next(req);
}

return from(conditionallyUpdateToken(req, keycloak, matchingCondition)).pipe(
mergeMap(() =>
keycloak.authenticated ? addAuthorizationHeader(req, next, keycloak, matchingCondition) : next(req)
)
);
})
);
};

0 comments on commit fa5a2dc

Please sign in to comment.