add OAuth 2.0 Bearer Token authentication

This commit is contained in:
Johann150 2022-07-18 17:41:08 +02:00
parent 3b69a563f8
commit 29f7eb4482
No known key found for this signature in database
GPG key ID: 9EE6577A2A06F8F1
3 changed files with 22 additions and 4 deletions

View file

@ -43,7 +43,8 @@ export default (endpoint: IEndpoint, ctx: Koa.Context) => new Promise<void>((res
};
// Authentication
authenticate(body['i']).then(([user, app]) => {
// for GET requests, do not even pass on the body parameter as it is considered unsafe
authenticate(ctx.headers.authorization, ctx.method === 'GET' ? null : body['i']).then(([user, app]) => {
// API invoking
call(endpoint.name, user, app, body, ctx).then((res: any) => {
if (ctx.method === 'GET' && endpoint.meta.cacheSec && !body['i'] && !user) {

View file

@ -15,8 +15,25 @@ export class AuthenticationError extends Error {
}
}
export default async (token: string | null): Promise<[CacheableLocalUser | null | undefined, AccessToken | null | undefined]> => {
if (token == null) {
export default async (authorization: string | null | undefined, bodyToken: string | null): Promise<[CacheableLocalUser | null | undefined, AccessToken | null | undefined]> => {
let token: string | null = null;
// check if there is an authorization header set
if (authorization != null) {
if (bodyToken != null) {
throw new AuthenticationError('using multiple authorization schemes');
}
// check if OAuth 2.0 Bearer tokens are being used
// Authorization schemes are case insensitive
if (authorization.substring(0, 7).toLowerCase() === 'bearer ') {
token = authorization.substring(7);
} else {
throw new AuthenticationError('unsupported authentication scheme');
}
} else if (bodyToken != null) {
token = bodyToken;
} else {
return [null, null];
}

View file

@ -20,7 +20,7 @@ export const initializeStreamingServer = (server: http.Server) => {
// TODO: トークンが間違ってるなどしてauthenticateに失敗したら
// コネクション切断するなりエラーメッセージ返すなりする
// (現状はエラーがキャッチされておらずサーバーのログに流れて邪魔なので)
const [user, app] = await authenticate(q.i as string);
const [user, app] = await authenticate(request.httpRequest.headers.authorization, q.i);
if (user?.isSuspended) {
request.reject(400);