Backend geeft nu een 401 ipv. een 500 terug voor de 'expired jwt' fout

This commit is contained in:
Gerald Schmittinger 2025-04-19 10:03:54 +02:00
parent 61c751c343
commit c2f3a6169a
7 changed files with 132 additions and 5 deletions

View file

@ -1,7 +1,9 @@
import { HasStatusCode } from "./has-status-code";
/**
* Exceptions which are associated with a HTTP error code.
*/
export abstract class ExceptionWithHttpState extends Error {
export abstract class ExceptionWithHttpState extends Error implements HasStatusCode {
constructor(
public status: number,
public error: string

View file

@ -0,0 +1,6 @@
export interface HasStatusCode {
status: number
}
export function hasStatusCode(err: unknown): err is HasStatusCode {
return typeof err === 'object' && err !== null && 'status' in err && typeof (err as HasStatusCode)?.status === 'number';
}

View file

@ -48,14 +48,14 @@ const idpConfigs = {
const verifyJwtToken = expressjwt({
secret: async (_: express.Request, token: jwt.Jwt | undefined) => {
if (!token?.payload || !(token.payload as JwtPayload).iss) {
throw new Error('Invalid token');
throw new UnauthorizedException("Invalid token.")
}
const issuer = (token.payload as JwtPayload).iss;
const idpConfig = Object.values(idpConfigs).find((config) => config.issuer === issuer);
if (!idpConfig) {
throw new Error('Issuer not accepted.');
throw new UnauthorizedException('Issuer not accepted.');
}
const signingKey = await idpConfig.jwksClient.getSigningKey(token.header.kid);

View file

@ -1,11 +1,11 @@
import { NextFunction, Request, Response } from 'express';
import { getLogger, Logger } from '../../logging/initalize.js';
import { ExceptionWithHttpState } from '../../exceptions/exception-with-http-state.js';
import { hasStatusCode } from '../../exceptions/has-status-code.js';
const logger: Logger = getLogger();
export function errorHandler(err: unknown, _req: Request, res: Response, _: NextFunction): void {
if (err instanceof ExceptionWithHttpState) {
if (hasStatusCode(err)) {
logger.warn(`An error occurred while handling a request: ${err} (-> HTTP ${err.status})`);
res.status(err.status).json(err);
} else {