0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2025-01-13 21:30:30 -05:00
logto/packages/core/src/middleware/koa-auth.ts

29 lines
748 B
TypeScript
Raw Normal View History

2021-08-14 21:39:37 +08:00
import assert from 'assert';
import RequestError from '@/errors/RequestError';
import { RequestErrorBody } from '@logto/schemas';
import { Middleware } from 'koa';
const bearerToken = 'Bearer';
export default function koaAuth<StateT, ContextT>(): Middleware<
StateT,
ContextT,
RequestErrorBody
> {
return async (ctx, next) => {
const { authorization } = ctx.request.headers;
assert(
authorization,
new RequestError({ code: 'auth.authorization_header_missing', status: 401 })
);
assert(
authorization.startsWith(bearerToken),
new RequestError(
{ code: 'auth.authorization_type_not_supported', status: 401 },
{ supportedTypes: [bearerToken] }
)
);
return next();
};
}