MSAL.js(v2)をTypeScriptで試してみる
MASL.js(V2)を使用してみます。まだ動いたので Azure Management Service API使ってサブスクリプションの一覧を取得してみます。
Microsoft ID プラットフォームのコード サンプル (v2.0 エンドポイント) の 認証コード フローと PKCE を使用した Microsoft Graph の呼び出し を参考に、 Vue.js + TypeScript で少し書き直しています。
アプリケーションを登録する
クイック スタート:Microsoft ID プラットフォームにアプリケーションを登録する を参考にアプリを登録します。
Azure ポータル のアプリの登録から作成して以下を設定するだけです。概要のアプリケーション (クライアント)IDは後程使いますのでメモっておきます。
クイック スタート:Microsoft ID プラットフォームにアプリケーションを登録する https://docs.microsoft.com/ja-jp/azure/active-directory/develop/quickstart-register-app
アプリケーションの作成
今回作成したコード(typescript-vuejs-masl-v2-sample)。作成した環境は以下となっています。
- Node.js 12.18.0 LTS
- Vue CLI 4.4.1
もとのサンプルの authRedirect.js を handleRedirectCallbackをhandleRedirectPromiseに変更、scopesを変更。あとはTypeScript + Vue.js な感じに少し手直しして完了です。
API関連を抜粋
設定
const msalConfig = { auth: { clientId: "Application(Client)ID", authority: "https://login.microsoftonline.com/common", redirectUri: "http://localhost:8080/" }, cache: { cacheLocation: "sessionStorage", storeAuthStateInCookie: false } };
ログイン
signIn() { const loginRequest = { scopes: ["https://management.core.windows.net//user_impersonation"] }; context.root.$msal.loginRedirect(loginRequest); },
ログアウト
signOut() { context.root.$msal.logout(); }
サブスクリプション一覧取得
const silentRequest = { scopes: ["https://management.core.windows.net//user_impersonation"] }; try { const response = await context.root.$msal.acquireTokenSilent( silentRequest ); const data = await callApi( "https://management.azure.com/subscriptions?api-version=2020-01-01", response.accessToken ); data.value.forEach(function(value: any) { const id: string = value.subscriptionId; subscriptions.push(id); }); } catch (error) { console.log("failed: ", error); }