Azure AD でサイレント認証を使用する

重要

セキュリティ修正プログラムを含む Active Directory Authentication Library (ADAL) の Microsoft サポートと開発は、 2022 年 6 月 30 日に終了します。 引き続きサポートを受けるには、Microsoft Authentication Library (MSAL) を使用するようにアプリケーションを更新します。 Microsoft Authentication Library (MSAL) へのアプリケーションの移行に関するページを参照してください。

注意

モバイル クライアントのタブで認証を機能させるには、Teams JavaScript SDK バージョン 1.4.1 以降を使用していることを確認します。

Azure AD のサイレント認証では、認証トークンをサイレント に更新することで、ユーザーが資格情報を入力する回数が最小限に抑えられます。 シングル サインオンの真のサポートについては、 SSO のドキュメントを参照してください

コード クライアント側を維持するには、JavaScript 用の Azure AD 認証ライブラリを使用して、Microsoft Azure Active Directory (Azure AD) アクセス トークンをサイレント モードで取得します。 ユーザーが最近サインインした場合、ポップアップ ダイアログ ボックスは表示されません。

Active Directory 認証ライブラリは AngularJS アプリケーション用に最適化されていますが、JavaScript シングルページ アプリケーション (SPA) でも動作します。

注意

現時点では、サイレント認証はタブでのみ機能します。 ボットからサインインする場合は機能しません。

サイレント認証のしくみ

Active Directory 認証ライブラリでは、OAuth 2.0 の暗黙的な許可フロー用に非表示の iframe が作成されます。 ただし、このライブラリでは prompt=none、Azure AD にサインイン ページが表示されないように指定されています。 ユーザーがサインインするか、アプリケーションへのアクセスを許可する必要がある場合は、ユーザー操作が必要になる場合があります。 ユーザー操作が必要な場合は、ライブラリがアプリに報告するエラーが Azure AD によって返されます。 必要に応じて、アプリにサインイン オプションを表示できるようになりました。

サイレント認証を行う方法

この記事のコードは、Teams 認証サンプル ノードである Teams サンプル アプリからのものです。

Azure AD を使用してサイレントでシンプルな認証構成可能タブを開始 し、指示に従ってローカル コンピューターでサンプルを実行します。

Active Directory 認証ライブラリを含め、構成する

Active Directory 認証ライブラリをタブ ページに含め、クライアント ID とリダイレクト URL を使用してライブラリを構成します。

<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.15/js/adal.min.js" integrity="sha384-lIk8T3uMxKqXQVVfFbiw0K/Nq+kt1P3NtGt/pNexiDby2rKU6xnDY8p16gIwKqgI" crossorigin="anonymous"></script>
<script type="text/javascript">
    // Active Directory Authentication Library configuration
    let config = {
        clientId: "YOUR_APP_ID_HERE",
        // redirectUri must be in the list of redirect URLs for the Azure AD app
        redirectUri: window.location.origin + "/tab-auth/silent-end",
        cacheLocation: "localStorage",
        navigateToLoginRequestUrl: false,
    };
</script>

ユーザー コンテキストを取得する

タブのコンテンツ ページで、現在のユーザーのサインイン ヒントを取得するために呼び出 app.getContext() します。 このヒントは、Azure AD の呼び出しで使用 loginHint されます。

// Set up extra query parameters for Active Directory Authentication Library
// - openid and profile scope adds profile information to the id_token
// - login_hint provides the expected user name
if (loginHint) {
    config.extraQueryParameter = "scope=openid+profile&login_hint=" + encodeURIComponent(loginHint);
} else {
    config.extraQueryParameter = "scope=openid+profile";
}

認証

Active Directory 認証ライブラリに、ユーザーの有効期限が切れていないトークンがキャッシュされている場合は、そのトークンを使用します。 または、サイレント モードでトークンを受信するように呼び出 acquireToken(resource, callback) します。 ライブラリは、要求されたトークンを使用してコールバック関数を呼び出すか、認証が失敗した場合にエラーを生成します。

コールバック関数でエラーが発生した場合は、明示的なサインイン オプションを表示して使用します。

let authContext = new AuthenticationContext(config); // from Active Directory Authentication Library
// See if there is a cached user and it matches the expected user
let user = authContext.getCachedUser();
if (user) {
    if (user.profile.oid !== userObjectId) {
        // User doesn't match, clear the cache
        authContext.clearCache();
    }
}

// In this example we are getting an id token (which Active Directory Authentication Library returns if we ask for resource = clientId)
authContext.acquireToken(config.clientId, function (errDesc, token, err, tokenType) {
    if (token) {
        // Make sure Active Directory Authentication Library gave us an ID token
        if (tokenType !== authContext.CONSTANTS.ID_TOKEN) {
            token = authContext.getCachedToken(config.clientId);
        }
        showProfileInformation(idToken);
    } else {
        console.log("Renewal failed: " + err);
        // Failed to get the token silently; show the login button
        showLoginButton();
        // You could attempt to launch the login popup here, but in browsers this could be blocked by
        // a popup blocker, in which case the login attempt will fail with the reason FailedToOpenWindow.
    }
});

戻り値を処理する

Active Directory 認証ライブラリは、サインイン コールバック ページで呼び出 AuthenticationContext.handleWindowCallback(hash) すことによって、Azure AD の結果を解析します。

有効なユーザーが存在することを確認し、呼び出 authentication.notifySuccess() すか authentication.notifyFailure() 、メイン タブのコンテンツ ページに状態を報告します。

import { authentication } from "@microsoft/teams-js";
if (authContext.isCallback(window.location.hash)) {
    authContext.handleWindowCallback(window.location.hash);
    if (window.parent === window) {
        if (authContext.getCachedUser()) {
            authentication.notifySuccess();
        } else {
            authentication.notifyFailure(authContext.getLoginError());
        }
    }
}

サインアウト フローを処理する

Azure AD 認証でサインアウト フローを処理するには、次のコードを使用します。

注意

Teams タブまたはボットからログアウトすると、現在のセッションがクリアされます。

function logout() {
localStorage.clear();
window.location.href = "@Url.Action("<<Action Name>>", "<<Controller Name>>")";
}

関連項目