はじめに
AppStreamの認証でCognitoを利用する方法がAWSハンズオンで公開されています。
ただし、公開されてから時間が経っているため、Lambdaのコードが古くてそのままでは動きません。
そこで、コードを最新化してみました。
AWSハンズオン
AWSハンズオンはこちらです。
aws.amazon.com
修正内容
Lambdaで現在利用できるNode.js v18~となっている
Node.jsで使用しているAWS SDK for JavaScriptのバージョンがv2からv3になるので、それに合わせた修正が必要。
Node.jsのファイル形式がjsからmjsに変更されたので、こちらでも修正が必要。
CognitoのユーザーIDの文字数がAppStreamのユーザー名の文字数制限に抵触
Cognitoでユーザーを作成するとユーザーIDが自動で生成されます。
CognitoのユーザーIDは40文字ぐらいあるのですが、AppStreamでストリーミングする際、ユーザー名は32文字以下にする必要があります。
そのため、LambdaでユーザーIDをハッシュ化し、文字数を減らしています。
コード
修正したコードは以下の通りです!
import { AppStream } from '@aws-sdk/client-appstream'; import crypto from 'crypto'; const appstream = new AppStream(); export const handler = async (event, context, callback) => { if (!event.requestContext.authorizer) { errorResponse('Authorization has not been configured, please configure an authorizer in API Gateway', context.awsRequestId, callback); return; } const username = event.requestContext.authorizer.claims['cognito:username']; const hashedUsername = crypto .createHash('md5') .update(username) .digest('hex'); const params = { FleetName: '<Fleet-Name>', StackName: '<Stack-Name>', UserId: hashedUsername, Validity: 5 }; await createas2streamingurl(params, context.awsRequestId, callback); }; function errorResponse(errorMessage, awsRequestId, callback) { callback(null, { statusCode: 500, body: JSON.stringify({ Error: errorMessage, Reference: awsRequestId, }), headers: { 'Access-Control-Allow-Origin': '<origin-domain>', }, }); } async function createas2streamingurl(params, awsRequestId, callback) { try { const response = await appstream.createStreamingURL(params); const url = response.StreamingURL; callback(null, { statusCode: 201, body: JSON.stringify({ Message: url, Reference: awsRequestId, }), headers: { 'Access-Control-Allow-Origin': '<origin-domain>', }, }); } catch (error) { console.log("Error: " + error.message); errorResponse('Error creating AS2 streaming URL.', awsRequestId, callback); } }
おわりに
単純にAWS SDK for JavaScriptのバージョン変更(v2→v3)だけの対応では足りなかったので、少し苦労しました。
お役に立てれば幸いです。