演習 - ASP.NET MVC Web アプリを作成して Azure AD アプリを登録する

完了

この演習では、ASP.NET MVC Web アプリケーションを Visual Studio で作成し、Azure AD アプリケーションを Azure Active Directory 管理センターで作成します。 アプリケーションを作成したら、Microsoft Graph からのユーザー認証とデータ要求をサポートするために必要なパッケージとライブラリを追加します。

前提条件

Microsoft Graph アプリの開発には、Microsoft 365 テナントが必要です。

Microsoft 365 テナントについては、Microsoft 365 アカウントを持っていない場合、「Microsoft 365 開発者プログラム」サイトの手順に従って、開発者テナントを取得してください。

このモジュールの演習では、開発者のワークステーションに、次のツールがインストールされていることを前提としています。

ASP.NET MVC Web アプリケーションを作成する

Visual Studio を開き、[新しいプロジェクトの作成] を選択します。

[新しいプロジェクトの作成] ダイアログで、C# を使用する [ASP.NET Web アプリケーション (.NET Framework)] オプションを選択してから、[次へ] を選択します。

Visual Studio の [新しいプロジェクトの作成] ダイアログ

[プロジェクト名] フィールドに graph-tutorial と入力して、[作成] を選択します。

Visual Studio の [新しいプロジェクトの構成] ダイアログ

注:

この手順で指定した Visual Studio プロジェクトと正確に同じ名前を入力していることを確認します。 Visual Studio プロジェクトの名前が、コードでの名前空間の一部になります。 この手順のコードは、この手順で指定した Visual Studio プロジェクト名に一致する名前空間に応じて異なります。 異なるプロジェクト名を使用する場合には、Visual Studio プロジェクト作成時に入力したプロジェクト名に一致するようにすべての名前空間を調整しないと、コードがコンパイルされません。

[MVC] を選択し、[作成] を選択します。

Visual Studio の [新しい ASP.NET Core Web アプリケーションの作成] ダイアログ

F5 キーを押すか、[デバッグ] [デバッグ>の開始] の順に選択します。 すべてが適切に動作している場合は、既定のブラウザーが開き、既定の ASP.NET ページが表示されます。

NuGet パッケージを追加する

次に進む前に、bootstrap NuGet パッケージを更新し、後で使用する以下の追加の NuGet パッケージをインストールします:

[ ツール] > [NuGet パッケージ マネージャー パッケージ マネージャー > コンソール] の順に選択します

パッケージ マネージャー コンソールで、次のコマンドを入力します。

Update-Package bootstrap -Version 4.6.0
Install-Package Microsoft.Owin.Host.SystemWeb
Install-Package Microsoft.Owin.Security.OpenIdConnect
Install-Package Microsoft.Owin.Security.Cookies
Install-Package Microsoft.Identity.Client -Version 4.43.2
Install-Package Microsoft.Graph -Version 4.28.0

アプリを設計する

このセクションでは、アプリケーションの基本構造を作成します。

基本的な OWIN スタートアップ クラスを作成します。 ソリューション エクスプローラーgraph-tutorial フォルダーを右クリックし、[新しい項目の追加>] を選択します。 OWIN スタートアップ クラス テンプレートを選択し、Startup.cs ファイルを指定し、[追加] をクリックします。

ソリューション エクスプローラーModels フォルダーを右クリックし、[クラスの追加]>を選択します。クラスに Alert という名前を付け、[追加] を選択します。 Alert.cs の内容全体を次のコードで置き換えます。

namespace graph_tutorial.Models
{
    // Used to flash error messages in the app's views.
    public class Alert
    {
        public const string AlertKey = "TempDataAlerts";
        public string Message { get; set; }
        public string Debug { get; set; }
    }
}

アプリのグローバル レイアウトを更新するため、./Views/Shared/_Layout.cshtml ファイルを開き、内容全体を次のコードで置き換えます。

@{
    var alerts = TempData.ContainsKey(graph_tutorial.Models.Alert.AlertKey)
        ? (List<graph_tutorial.Models.Alert>)TempData[graph_tutorial.Models.Alert.AlertKey]
        : new List<graph_tutorial.Models.Alert>();
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ASP.NET Graph Tutorial</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css"
            integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt"
            crossorigin="anonymous">
</head>

<body>
    <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
        <div class="container">
            @Html.ActionLink("ASP.NET Graph Tutorial", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse"
                    aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarCollapse">
                <ul class="navbar-nav mr-auto">
                    <li class="nav-item">
                        @Html.ActionLink("Home", "Index", "Home", new { area = "" },
                            new { @class = ViewBag.Current == "Home" ? "nav-link active" : "nav-link" })
                    </li>
                    @if (Request.IsAuthenticated)
                    {
                        <li class="nav-item" data-turbolinks="false">
                            @Html.ActionLink("Calendar", "Index", "Calendar", new { area = "" },
                                new { @class = ViewBag.Current == "Calendar" ? "nav-link active" : "nav-link" })
                        </li>
                    }
                </ul>
                <ul class="navbar-nav justify-content-end" style="align-items:center;">
                    <li class="nav-item">
                        <a class="nav-link" href="https://developer.microsoft.com/graph/docs/concepts/overview" target="_blank">
                            <i class="fas fa-external-link-alt mr-1"></i>Docs
                        </a>
                    </li>
                    @if (Request.IsAuthenticated)
                    {
                        <li class="nav-item dropdown">
                            <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">
                                @if (!string.IsNullOrEmpty(ViewBag.User.Avatar))
                                {
                                    <img src="@ViewBag.User.Avatar" class="rounded-circle align-self-center mr-2" style="width: 32px;">
                                }
                                else
                                {
                                    <i class="far fa-user-circle fa-lg rounded-circle align-self-center mr-2" style="width: 32px;"></i>
                                }
                            </a>
                            <div class="dropdown-menu dropdown-menu-right">
                                <h5 class="dropdown-item-text mb-0">@ViewBag.User.DisplayName</h5>
                                <p class="dropdown-item-text text-muted mb-0">@ViewBag.User.Email</p>
                                <div class="dropdown-divider"></div>
                                @Html.ActionLink("Sign Out", "SignOut", "Account", new { area = "" }, new { @class = "dropdown-item" })
                            </div>
                        </li>
                    }
                    else
                    {
                        <li class="nav-item">
                            @Html.ActionLink("Sign In", "SignIn", "Account", new { area = "" }, new { @class = "nav-link" })
                        </li>
                    }
                </ul>
            </div>
        </div>
    </nav>
    <main role="main" class="container">
        @foreach (var alert in alerts)
        {
            <div class="alert alert-danger" role="alert">
                <p class="mb-3">@alert.Message</p>
                @if (!string.IsNullOrEmpty(alert.Debug))
                {
                    <pre class="alert-pre border bg-light p-2"><code>@alert.Debug</code></pre>
                }
            </div>
        }

        @RenderBody()
    </main>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

注:

このコードはシンプルなスタイルのために Bootstrap を追加し、シンプルなアイコンのために Font Awesome を追加します。 また、ナビゲーション バーを使用するグローバル レイアウトを定義し、Alert クラスを使用してすべての警告を表示します。

Content/Site.css を開き、内容全体を次のコードに置き換えます。

body {
    padding-top: 4.5rem;
}

.alert-pre {
    word-wrap: break-word;
    word-break: break-all;
    white-space: pre-wrap;
}

Views/Home/Index.cshtml ファイルを開き、その内容を以下の内容に置き換えます。

@{
    ViewBag.Current = "Home";
}

<div class="jumbotron">
    <h1>ASP.NET Graph Tutorial</h1>
    <p class="lead">This sample app shows how to use the Microsoft Graph API to access a user's data from ASP.NET</p>
    @if (Request.IsAuthenticated)
    {
        <h4>Welcome @ViewBag.User.DisplayName!</h4>
        <p>Use the navigation bar at the top of the page to get started.</p>
    }
    else
    {
        @Html.ActionLink("Click here to sign in", "SignIn", "Account", new { area = "" }, new { @class = "btn btn-primary btn-large" })
    }
</div>

ソリューション エクスプローラーの Controllers フォルダーを右クリックし、[コントローラーの追加>]を選択します。[MVC 5 コントローラー ] - [空] を選択し、[追加] を選択します。 コントローラーの名前として BaseController を指定し、[追加] を選択します。 BaseController.cs の内容を次のコードに置き換えます。

using graph_tutorial.Models;
using System.Collections.Generic;
using System.Web.Mvc;

namespace graph_tutorial.Controllers
{
    public abstract class BaseController : Controller
    {
        protected void Flash(string message, string debug=null)
        {
            var alerts = TempData.ContainsKey(Alert.AlertKey) ?
                (List<Alert>)TempData[Alert.AlertKey] :
                new List<Alert>();

            alerts.Add(new Alert
            {
                Message = message,
                Debug = debug
            });

            TempData[Alert.AlertKey] = alerts;
        }
    }
}

Controllers/HomeController.cs を開き、public class HomeController : Controller 行を次のように変更します。

public class HomeController : BaseController

変更内容をすべて保存し、サーバーを再起動します。 これで、アプリの外観が変わります。

デザインが変更されたホーム ページのスクリーンショット

Azure AD アプリケーションを作成する

このセクションでは、Azure Active Directory 管理センターを使用して Azure AD Web アプリケーションの新規登録を作成します。

ASP.NET アプリの HTTPS URL を決定します。 Visual Studio の ソリューション エクスプローラー で、Graph チュートリアル プロジェクトを選択します。 [プロパティ] ウィンドウで、SSL URL の値を見つけます。 この値をコピーします。

Visual Studio の [プロパティ] ウィンドウのスクリーンショット

ブラウザーを開き、Azure Active Directory 管理センター (https://aad.portal.azure.com) に移動します。 テナントに対するグローバル管理者権限が付与されている職場または学校のアカウントを使用してサインインします。

左側のナビゲーションで、[Azure Active Directory] を選択します。

左側のナビゲーションで [アプリの登録の管理>] を選択します。

アプリの登録のスクリーンショット

[アプリの登録] ページで、[新規登録] を選択します。

[アプリの登録] ページのスクリーンショット

[新規登録] を選択します。 [アプリケーションを登録] ページで、次のように値を設定します。

  • 名前ASP.NET Graph チュートリアルに設定します。
  • [サポートされているアカウントの種類][任意の組織のディレクトリ内のアカウントと個人用の Microsoft アカウント] に設定します。
  • [リダイレクト URI] で、最初のドロップダウン リストを [Web] に設定し、値をこのセクションで以前に取得した ASP.NET アプリ URL に設定します。

[アプリケーションを登録する] ページのスクリーンショット

[登録] を選択します。 ASP.NET Graph チュートリアルページで、アプリケーション (クライアント) ID の値をコピーして保存し、次の手順に移ります。

新しいアプリ登録のアプリケーション ID のスクリーンショット

[管理] の下の [認証] を選択します。 [暗黙的な許可とハイブリッド フロー] のセクションを見つけて、ID トークンを有効にします (暗黙的なフローとハイブリッド フローに使用されます)

[暗黙的な許可] セクションのスクリーンショット

上部のメニューにある [保存] を選択して、変更を保存します。

[管理 ] で [証明書 & シークレット ] を 選択します[新しいクライアント シークレット] ボタンを選択します。 [説明] に値を入力して、[有効期限] のオプションのいずれかを選び、[追加] を選択します。

[クライアントシークレットの追加] ダイアログのスクリーンショット

このページを離れる前に、クライアント シークレットの値をコピーします。 次の手順で使用します。

重要

このクライアント シークレットは今後表示されないため、この段階で必ずコピーするようにしてください。

新規追加されたクライアント シークレットのスクリーンショット

概要

この演習では、ASP.NET MVC Web アプリケーションを Visual Studio で、Azure AD アプリケーションを Azure Active Directory 管理センターで作成しました。 アプリケーションを作成したら、Microsoft Graph からのユーザー認証とデータ要求をサポートするために必要なパッケージとライブラリを追加しました。

自分の知識をテストする

1.

Microsoft Graph では、サインインしたユーザー用にアクセス トークン生成がサポートされているアカウントはどの種類ですか?

2.

Microsoft Graph では、個別のサービス エンドポイントの使用よりもどのようなメリットがありますか?