FoalTS: return a 401 unauthorized code when bearer auth token is missing
We are using FoalTS as app-server nodeJS framework and are generally quite happy with it. One annoying thing though is that it treats a missing Auth Bearer token (JWT authentication of API routes) as a http 400 error.
While yes, technically a missing auth header is a missing parameter and is therefore definately a "bad request", we feel one should use the most specific error messages possible. From that point of view, a missing auth header is comparable to someone submitting an email/password login-form and leaving the password field empty. In such a case most applications would return a 401 code instead of a 400 which is how we would like Pagerista to behave as well.
So, as above behavior of FoalTS is hardwired into the framework and patching the JWTrequired method just for this use case feels overblown, we resorted to a custom post-hook, which rewrites the http response in case a missing token is detected:
@Hook(() => response => {
if (
response.body &&
response.body.description &&
(response.body.description === 'Authorization header not found.' ||
response.body.description === 'Expected a bearer token. Scheme is Authorization: Bearer <token>.')
) {
response.statusCode = 401;
response.statusMessage = 'UNAUTHORIZED';
}
})
export class ApiController {
public subControllers = [controller('/apidefs', ApidefsController), controller('/auth', AuthController), controller('/users', UsersController)];
}