Skip to content

Commit

Permalink
by default throw an error if an auth bearer token is present but it i…
Browse files Browse the repository at this point in the history
…s not a valid app or jwt
  • Loading branch information
macno committed Oct 4, 2024
1 parent ff12394 commit ea3849e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 15 deletions.
5 changes: 4 additions & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ export interface MicroServiceOptions {
appDefaultRoles?: string[];
key?: string;
cert?: string;
forwardUnknownBearer?: boolean;
}

export interface MicroServiceConfig {
Expand All @@ -65,6 +66,7 @@ export interface MicroServiceConfig {
appDefaultRoles: string[];
key?: string;
cert?: string;
forwardUnknownBearer?: boolean;
}

export const Config: MicroServiceConfig = {
Expand Down Expand Up @@ -120,5 +122,6 @@ export const Config: MicroServiceConfig = {
}
}
return ret;
}, {})
}, {}),
forwardUnknownBearer: EnvParse.envBool('FW_MS_FORWARD_UNKNOWN_BEARER', false)
};
28 changes: 14 additions & 14 deletions src/microservice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,19 @@ export class Microservice {
if (this.config.jwtPublicKey) {
this.express.use(this.jwtMiddleware(this.config.jwtPublicKey));
}
if (!this.config.forwardUnknownBearer) {
// at this point, if a bearer token is present, we should have a consumer in the context, otherwise it's an invalid token
this.express.use((req: Request, res: Response, next: NextFunction) => {
if (
Microservice.getBearerToken(req) &&
!getAsyncLocalStorageProp<ConsumerDef>(MicroServiceStoreSymbols.CONSUMER)
) {
res.status(401).json({ status: 401, reason: 'Unauthorized' });
return;
}
next();
});
}
this.setupPreLoggerMiddlewares();
this.express.use(this.requestLogger);

Expand Down Expand Up @@ -309,20 +322,7 @@ export class Microservice {
next();
return;
}

function getToken() {
const authorization = req.get('authorization');
if (authorization) {
const m = /^[Bb]earer\s+(\S+)$/.exec(authorization);
if (m) {
const [, tokenString] = m;
return tokenString;
}
}
return null;
}

const token = getToken();
const token = Microservice.getBearerToken(req);
if (token) {
const consumerJwt = verify(token, publicKey, { algorithms: ['RS512'], complete: true });
const consumer = (consumerJwt.payload as JwtPayload).consumer as ConsumerDef;
Expand Down

0 comments on commit ea3849e

Please sign in to comment.