快速入门:向 ASP.NET Web 应用添加 Microsoft 登录Quickstart: Add sign-in with Microsoft to an ASP.NET web app

适用于:Applies to:
  • Azure AD v1.0 终结点Azure AD v1.0 endpoint

在本快速入门中,你将了解如何使用 OpenID Connect 通过基于传统 Web 浏览器的应用程序,根据 ASP.NET MVC 解决方案实现 Microsoft 登录。In this quickstart, you'll learn how to implement sign-in with Microsoft using an ASP.NET MVC solution with a traditional web browser-based application using OpenID Connect. 你将了解如何在 ASP.NET 应用程序中使用工作和学校帐户登录。You'll learn how to enable sign-ins from work and school accounts in your ASP.NET application.

在本快速入门结束时,应用程序可接受与 Azure Active Directory (Azure AD) 集成的组织的工作和学校帐户登录。At the end of this quickstart, your application will accept sign ins of work and school accounts from organizations that have integrated with Azure Active Directory (Azure AD).

先决条件Prerequisites

要开始,请确保满足下列先决条件:To get started, make sure you meet these prerequisites:

方案:在 ASP.NET 应用中让用户使用工作和学校帐户登录Scenario: Sign in users from work and school accounts in your ASP.NET app

本指南的工作原理

在此方案中,浏览器访问 ASP.NET 网站,并请求用户使用“登录”按钮进行身份验证。In this scenario, a browser accesses an ASP.NET web site and requests a user to authenticate using a sign in button. 在此方案中,呈现网页的大部分工作在服务器端完成。In this scenario, most of the work to render the web page occurs on the server side.

本快速入门演示了如何从空模板开始,使用户登录 ASP.NET Web 应用程序,包括添加登录按钮以及每个控制器和方法的步骤,并讨论这些任务背后的概念。The quickstart demonstrates how to sign in users on an ASP.NET web application starting from an empty template, and includes steps such as adding a sign in button and every controller and methods and discusses the concepts behind these tasks. 或者,还可以通过使用 Visual Studio Web 模板并选择“组织帐户”和云选项之一(该选项使用包含其他控制器、方法和视图的更丰富的模板),创建使 Azure AD 用户(工作和学校帐户)登录的项目。Alternatively, you can also create a project to sign in Azure AD users (work and school accounts) by using the Visual Studio web template and selecting Organizational Accounts and then one of the cloud options - this option uses a richer template, with additional controllers, methods and views.

Libraries

本快速入门使用以下包:This quickstart uses the following packages:

Library 说明Description
Microsoft.Owin.Security.OpenIdConnectMicrosoft.Owin.Security.OpenIdConnect 让应用程序可使用 OpenIdConnect 进行身份验证的中间件Middleware that enables an application to use OpenIdConnect for authentication
Microsoft.Owin.Security.CookiesMicrosoft.Owin.Security.Cookies 让应用程序可使用 Cookie 维持用户会话的中间件Middleware that enables an application to maintain user session using cookies
Microsoft.Owin.Host.SystemWebMicrosoft.Owin.Host.SystemWeb 让基于 OWIN 的应用程序可使用 ASP.NET 请求管道在 IIS 上运行Enables OWIN-based applications to run on IIS using the ASP.NET request pipeline

步骤 1:设置项目Step 1: Set up your project

这些步骤介绍如何使用 OpenID Connect 通过 OWIN 中间件在 ASP.NET 项目上安装和配置身份验证管道。These steps show how to install and configure the authentication pipeline through the OWIN middleware on an ASP.NET project using OpenID Connect.

要下载此示例的 Visual Studio 项目,请按照下列步骤操作:To download this sample's Visual Studio project instead, follow these steps:

  1. 下载 GitHub 上的示例项目Download the project on GitHub.
  2. 跳至“配置”步骤以在执行操作前配置代码示例。Skip to the Configuration step to configure the code sample before executing.

步骤 2:创建 ASP.NET 项目Step 2: Create your ASP.NET project

  1. 在 Visual Studio 中,转到“文件”>“新建”>“项目”。In Visual Studio, go to File > New > Project.
  2. 在 Visual C#\Web 下,选择“ASP.NET Web 应用程序(.NET Framework)”。Under Visual C#\Web, select ASP.NET Web Application (.NET Framework).
  3. 为应用程序命名,并单击“确定”。Name your application and select OK.
  4. 选择“空”并选中复选框,添加 MVC 引用。Select Empty and then select the checkbox to add MVC references.

步骤 3:添加身份验证组件Step 3: Add authentication components

  1. 在 Visual Studio 中,转到“工具”>“NuGet 包管理器”>“包管理器控制台”。In Visual Studio, go to Tools > Nuget Package Manager > Package Manager Console.

  2. 在包管理器控制台窗口中键入以下命令,添加 OWIN 中间件 NuGet 包Add OWIN middleware NuGet packages by typing the following in the Package Manager Console window:

    Install-Package Microsoft.Owin.Security.OpenIdConnect
    Install-Package Microsoft.Owin.Security.Cookies
    Install-Package Microsoft.Owin.Host.SystemWeb
    

关于这些包About these packages

上述库通过基于 Cookie 的身份验证使用 OpenID Connect 启用单一登录 (SSO)。The libraries above enable single sign-on (SSO) using OpenID Connect via cookie-based authentication. 完成身份验证后,代表用户的令牌会发送到应用程序,OWIN 中间件会创建会话 Cookie。After authentication is completed and the token representing the user is sent to your application, OWIN middleware creates a session cookie. 浏览器随后对后续请求使用此 cookie,这样一来,用户就无需重新验证,也不需要任何其他验证。The browser then uses this cookie on subsequent requests so the user doesn't need to reauthenticate, and no additional verification is needed.

步骤 4:配置身份验证管道Step 4: Configure the authentication pipeline

按照以下步骤创建 OWIN 中间件 Startup 类,以配置 OpenID Connect 身份验证。Follow these steps to create an OWIN middleware Startup Class to configure OpenID Connect authentication. 此类自动执行。This class is executed automatically.

Tip

如果项目的根文件夹中没有 Startup.cs 文件,请执行以下操作:If your project doesn't have a Startup.cs file in the root folder:

  1. 右键单击项目的根文件夹:> “添加”>“新建项”...>“OWIN Startup 类”Right-click on the project's root folder: > Add > New Item... > OWIN Startup class
  2. 将它命名为Name it Startup.cs

确保选择的类是 OWIN Startup 类,而不是标准 C# 类。Make sure the class selected is an OWIN Startup Class and not a standard C# class. 通过检查是否在命名空间上看到 [assembly: OwinStartup(typeof({NameSpace}.Startup))] 来进行确认。Confirm this by checking if you see [assembly: OwinStartup(typeof({NameSpace}.Startup))] above the namespace.

创建 OWIN 中间件 Startup 类:To create an OWIN middleware Startup Class:

  1. 将 OWIN 和 Microsoft.IdentityModel 命名空间添加到 Startup.csAdd OWIN and Microsoft.IdentityModel namespaces to Startup.cs:

    using Microsoft.Owin;
    using Owin;
    using Microsoft.Owin.Security;
    using Microsoft.Owin.Security.Cookies;
    using Microsoft.Owin.Security.OpenIdConnect;
    using Microsoft.Owin.Security.Notifications;
    using Microsoft.IdentityModel.Protocols;
    using System;
    using System.Threading.Tasks;
    
  2. 使用以下代码替换 Startup 类:Replace Startup class with the following code:

    public class Startup
    {
        // The Client ID (a.k.a. Application ID) is used by the application to uniquely identify itself to Azure AD
        string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];
    
        // RedirectUri is the URL where the user will be redirected to after they sign in
        string redirectUrl = System.Configuration.ConfigurationManager.AppSettings["redirectUrl"];
    
        // Tenant is the tenant ID (e.g. contoso.partner.onmschina.cn, or 'common' for multi-tenant)
        static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];
    
        // Authority is the URL for authority, composed by Azure Active Directory endpoint and the tenant name (e.g. https://login.partner.microsoftonline.cn/contoso.partner.onmschina.cn)
        string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);
    
        /// <summary>
        /// Configure OWIN to use OpenIdConnect 
        /// </summary>
        /// <param name="app"></param>
        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
    
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    // Sets the ClientId, authority, RedirectUri as obtained from web.config
                    ClientId = clientId,
                    Authority = authority,
                    RedirectUri = redirectUrl,
    
                    // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
                    PostLogoutRedirectUri = redirectUrl,
    
                    //Scope is the requested scope: OpenIdConnectScopes.OpenIdProfileis equivalent to the string 'openid profile': in the consent screen, this will result in 'Sign you in and read your profile'
                    Scope = OpenIdConnectScopes.OpenIdProfile,
    
                    // ResponseType is set to request the id_token - which contains basic information about the signed-in user
                    ResponseType = OpenIdConnectResponseTypes.IdToken,
    
                    // ValidateIssuer set to false to allow work accounts from any organization to sign in to your application
                    // To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name or Id (example: contoso.partner.onmschina.cn)
                    // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter
                    TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters() { ValidateIssuer = false },
    
                    // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        AuthenticationFailed = OnAuthenticationFailed
                    }
                }
            );
        }
    
        /// <summary>
        /// Handle failed authentication requests by redirecting the user to the home page with an error in the query string
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
        {
            context.HandleResponse();
            context.Response.Redirect("/?errormessage=" + context.Exception.Message);
            return Task.FromResult(0);
        }
    }
    

Note

OpenIDConnectAuthenticationOptions 中提供的参数将充当应用程序与 Azure AD 通信时使用的坐标。 OpenID Connect 中间件会使用 Cookie,因此,还需要设置 Cookie 身份验证,如以上代码所示。 ValidateIssuer 值告知 OpenIdConnect 不要限制某个特定组织的访问权限。The ValidateIssuer value tells OpenIdConnect to not restrict access to one specific organization.

步骤 5:添加控制器来处理登录和注销请求Step 5: Add a controller to handle sign-in and sign-out requests

创建新控制器来公开登录和注销方法。Create a new controller to expose sign-in and sign-out methods.

  1. 右键单击“控制器”文件夹,并选择“添加”>“控制器”Right-click the Controllers folder and select Add > Controller

  2. 选择“MVC (.NET 版本)控制器 - 空”。Select MVC (.NET version) Controller - Empty.

  3. 选择“设置” (应用程序对象和服务主体对象)。Select Add.

  4. 将其命名为 HomeController,然后选择“添加”。Name it HomeController and select Add.

  5. 向该类添加 OWIN 命名空间:Add OWIN namespaces to the class:

    using Microsoft.Owin.Security;
    using Microsoft.Owin.Security.Cookies;
    using Microsoft.Owin.Security.OpenIdConnect;
    
  6. 通过代码启动身份验证质询,添加下面的方法来处理控制器登录和注销:Add the following methods to handle sign-in and sign-out to your controller by initiating an authentication challenge via code:

    /// <summary>
    /// Send an OpenID Connect sign-in request.
    /// Alternatively, you can just decorate the SignIn method with the [Authorize] attribute
    /// </summary>
    public void SignIn()
    {
        if (!Request.IsAuthenticated)
        {
            HttpContext.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties { RedirectUri = "/" },
                OpenIdConnectAuthenticationDefaults.AuthenticationType);
        }
    }
    
    /// <summary>
    /// Send an OpenID Connect sign-out request.
    /// </summary>
    public void SignOut()
    {
        HttpContext.GetOwinContext().Authentication.SignOut(
            OpenIdConnectAuthenticationDefaults.AuthenticationType,
            CookieAuthenticationDefaults.AuthenticationType);
    }
    

步骤 6:创建应用的主页,通过登录按钮来登录用户Step 6: Create the app's home page to sign in users via a sign-in button

在 Visual Studio 中,创建新视图来添加登录按钮并在身份验证后显示用户信息:In Visual Studio, create a new view to add the sign-in button and display user information after authentication:

  1. 右键单击“视图/主页”文件夹,然后选择“添加视图”。Right-click the Views\Home folder and select Add View.

  2. 将其命名为“Index”。Name it Index.

  3. 向文件添加以下 HTML,其中包括登录按钮:Add the following HTML, which includes the sign-in button, to the file:

    @{
        Layout = null;
    }
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Sign-In with Microsoft Guided Setup (Work Accounts)</title>
    </head>
    <body>
    @if (!Request.IsAuthenticated)
    {
        <!-- If the user is not authenticated, display the sign-in button -->
        <br /><a href="@Url.Action("SignIn", "Home")" style="text-decoration: none;">
            <svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="300px" height="50px" viewBox="0 0 3278 522" class="SignInButton">
                <style type="text/css">.fil0:hover {fill: #4B4B4B;} .fnt0 {font-size: 260px;font-family: 'Segoe UI Semibold', 'Segoe UI'; text-decoration: none;}</style>
                <rect class="fil0" x="2" y="2" width="3174" height="517" fill="black" /><rect x="150" y="129" width="122" height="122" fill="#F35325" /><rect x="284" y="129" width="122" height="122" fill="#81BC06" /><rect x="150" y="263" width="122" height="122" fill="#05A6F0" /><rect x="284" y="263" width="122" height="122" fill="#FFBA08" /><text x="470" y="357" fill="white" class="fnt0">Sign in with Microsoft</text>
            </svg>
        </a>
    }
    else
    {
        <span><br/>Hello @((User.Identity as System.Security.Claims.ClaimsIdentity)?.FindFirst("name")?.Value)</span>
        <br /><br />
        @Html.ActionLink("See Your Claims", "Index", "Claims")
        <br /><br />
        @Html.ActionLink("Sign out", "SignOut", "Home")
    }
    @if (!string.IsNullOrWhiteSpace(Request.QueryString["errormessage"]))
    {
        <div style="background-color:red;color:white;font-weight: bold;">Error: @Request.QueryString["errormessage"]</div>
    }
    </body>
    </html>
    

此页以 SVG 格式添加登录按钮,背景为黑色:This page adds a sign-in button in SVG format with a black background:
使用 Microsoft 登录

步骤 7:添加控制器来显示用户声明Step 7: Display user's claims by adding a controller

此控制器演示如何使用 [Authorize] 属性来保护控制器。This controller demonstrates the uses of the [Authorize] attribute to protect a controller. 此属性只允许通过身份验证的用户,从而限制对控制器的访问。This attribute restricts access to the controller by only allowing authenticated users. 下面的代码使用该属性来显示作为登录的一部分被检索的用户声明。The following code makes use of the attribute to display user claims that were retrieved as part of the sign-in.

  1. 右键单击“控制器”文件夹,然后选择“添加”>“控制器”。Right-click the Controllers folder, then select Add > Controller.

  2. 选择“MVC {version} 控制器 - 空”。Select MVC {version} Controller - Empty.

  3. 选择“设置” (应用程序对象和服务主体对象)。Select Add.

  4. 将其命名为“ClaimsController”。Name it ClaimsController.

  5. 将控制器类的代码替换为下面的代码,这将 [Authorize] 属性添加到类:Replace the code of your controller class with the following code - this adds the [Authorize] attribute to the class:

    [Authorize]
    public class ClaimsController : Controller
    {
        /// <summary>
        /// Add user's claims to viewbag
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity;
    
            //You get the user’s first and last name below:
            ViewBag.Name = userClaims?.FindFirst("name")?.Value;
    
            // The 'Name' claim can be used for showing the username
            ViewBag.Username = userClaims?.FindFirst(System.IdentityModel.Claims.ClaimTypes.Name)?.Value;
    
            // The subject/ NameIdentifier claim can be used to uniquely identify the user across the web
            ViewBag.Subject = userClaims?.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
    
            // TenantId is the unique Tenant Id - which represents an organization in Azure AD
            ViewBag.TenantId = userClaims?.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid")?.Value;
    
            return View();
        }
    }
    

Note

因为使用 [Authorize] 属性,仅当用户通过身份验证后,才能执行此控制器的所有方法。Because of the use of the [Authorize] attribute, all methods of this controller can only be executed if the user is authenticated. 如果用户未通过身份验证,并尝试访问控制器,OWIN 会启动身份验证质询,并强制用户进行身份验证。If the user is not authenticated and tries to access the controller, OWIN initiates an authentication challenge and force the user to authenticate. 上面的代码查看用户令牌中特定属性的用户的声明集合。The code above looks at the claims collection of the user for specific attributes included in the user’s token. 这些属性包括用户的全名和用户名,以及全局用户标识符使用者。These attributes include the user’s full name and username, as well as the global user identifier subject. 它还包含租户 ID,表示用户的组织的 ID。It also contains the Tenant ID, which represents the ID for the user’s organization.

步骤 8:创建视图来显示用户的声明Step 8: Create a view to display the user's claims

在 Visual Studio 中创建新视图,以在网页上显示用户的声明:In Visual Studio, create a new view to display the user's claims in a web page:

  1. 右键单击“视图/声明”文件夹,然后选择“添加视图”。Right-click the Views\Claims folder, then select Add View.

  2. 将其命名为“Index”。Name it Index.

  3. 将以下 HTML 添加到文件:Add the following HTML to the file:

    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Sign-In with Microsoft Sample</title>
        <link href="@Url.Content("~/Content/bootstrap.min.css")" rel="stylesheet" type="text/css" />
    </head>
    <body style="padding:50px">
    <h3>Main Claims:</h3>
    <table class="table table-striped table-bordered table-hover">
        <tr><td>Name</td><td>@ViewBag.Name</td></tr>
        <tr><td>Username</td><td>@ViewBag.Username</td></tr>
        <tr><td>Subject</td><td>@ViewBag.Subject</td></tr>
        <tr><td>TenantId</td><td>@ViewBag.TenantId</td></tr>
    </table>
    <br />
    <h3>All Claims:</h3>
    <table class="table table-striped table-bordered table-hover table-condensed">
        @foreach (var claim in ((System.Security.Claims.ClaimsIdentity) User.Identity).Claims)
        {
            <tr><td>@claim.Type</td><td>@claim.Value</td></tr>
        }
    </table>
    <br />
    <br />
    @Html.ActionLink("Sign out", "SignOut", "Home", null, new { @class = "btn btn-primary" })
    </body>
    </html>
    

步骤 9:配置 web.config 并注册应用程序Step 9: Configure your web.config and register an application

  1. 在 Visual Studio 中,将以下内容添加到 configuration\appSettings 部分下的 web.config(位于根文件夹中):In Visual Studio, add the following to web.config (located in the root folder) under the section configuration\appSettings:

    <add key="ClientId" value="Enter_the_Application_Id_here" />
    <add key="RedirectUrl" value="Enter_the_Redirect_Url_here" />
    <add key="Tenant" value="common" />
    <add key="Authority" value="https://login.partner.microsoftonline.cn/{0}" />
    
  2. 在解决方案资源管理器中,选择项目并查看“属性” 窗口(如果看不到“属性”窗口,请按 F4)In Solution Explorer, select the project and look at the Properties window (if you don’t see a Properties window, press F4)

  3. 将“已启用 SSL”更改为Change SSL Enabled to True

  4. 将项目的 SSL URL 复制到剪贴板:Copy the project's SSL URL to the clipboard:

    项目属性

  5. web.config 中,用项目的 SSL URL替换 Enter_the_Redirect_URL_hereIn web.config, replace Enter_the_Redirect_URL_here with the SSL URL of your project.

在 Azure 门户中注册应用程序,然后将其信息添加到 web.configRegister your application in the Azure Portal, then add its information to web.config

  1. 转到 Azure 门户 - 应用注册,注册应用程序。Go to the Azure portal - App registrations to register an application.
  2. 选择“新建应用程序注册”。Select New application registration.
  3. 输入应用程序的名称。Enter a name for your application.
  4. 将 Visual Studio 项目的 SSL URL 粘贴到登录 URL 中。Paste the Visual Studio project's SSL URL in Sign-on URL. 此 URL 还会自动添加到正在注册的应用程序的回复 URL 列表。This URL is also added automatically to the list of Reply URLs for the application you are registering.
  5. 选择“创建”以注册应用程序。Select Create to register the application. 执行此操作后会返回到应用程序列表。This action takes you back to the list of applications.
  6. 现在,搜索并/或选择刚刚创建的应用程序,打开其属性。Now, search and/or select the application you just created to open its properties.
  7. 将“应用程序 ID”下的 GUID 复制到剪贴板。Copy the GUID under Application ID to the clipboard.
  8. 返回到 Visual Studio,在 web.config 中,用刚刚注册的应用程序 ID 替换 Enter_the_Application_Id_hereGo back to Visual Studio and, in web.config, replace Enter_the_Application_Id_here with the Application ID from the application you just registered.

Tip

如果帐户配置为可访问多个目录,请确保为要向其注册应用程序的组织选择了正确的目录,方法是单击 Azure 门户右上角的帐户名称,然后按照指示验证所选目录:If your account is configured to access to multiple directories, make sure you have selected the right directory for the organization you want the application to be registered by clicking on your account name in the top right in the Azure portal, and then verifying the selected directory as indicated:
选择正确的目录

步骤 10:配置登录选项Step 10: Configure sign-in options

可以将应用程序配置为只允许某个组织的 Azure AD 实例中的用户登录,或者接受任何组织中的用户登录。You can configure your application to allow only users that belong to one organization's Azure AD instance to sign-in, or accept sign-ins from users that belong to any organization. 请按照以下选项之一的说明进行操作:Please follow the instructions of one of following choices:

将应用程序配置为允许任何公司或组织(多租户)的工作和学校帐户登录Configure your application to allow sign ins of work and school accounts from any company or organization (multi-tenant)

如果想接受任何已经与 Azure AD 集成的公司或组织的工作和学校帐户登录,请执行以下步骤。Follow the following steps if you want to accept sign ins of work and school accounts from any company or organization that has integrated with Azure AD. 这是 SaaS 应用程序 的常见方案:This is a common scenario for SaaS applications:

  1. 返回到 Azure 门户 - 应用注册,找到刚注册的应用程序。Go back to Azure portal - App registrations and locate the application you just registered.
  2. 在“所有设置”下,选择“属性”。Under All Settings, select Properties.
  3. 将“多租户”属性更改为“是”,然后选择“保存”。Change Multi-tenanted property to Yes, and then select Save.

有关此设置和多租户应用程序概念的详细信息,请参阅多租户概述For more information about this setting and the concept of multi-tenant applications, see Multi-tenant overview.

限制某个组织的 Active Directory 实例的用户登录应用程序(单租户)Restrict users from only one organization's Active Directory instance to sign in to your application (single-tenant)

此选项是业务线应用程序的常见方案。This option is a common scenario for line-of-business applications.

如果希望应用程序仅接受属于特定 Azure AD 实例的帐户(包括该示例的来宾帐户)进行登录,请按照下列步骤操作:If you want your application to accept sign-ins only from accounts that belong to a specific Azure AD instance (including guest accounts of that instance), follow these steps:

  1. 使用 Common 将 web.config 中的 Tenant 参数替换为组织的租户名称 - 例如 contoso.partner.onmschina.cn。Replace the Tenant parameter in web.config from Common with the tenant name of the organization - example, contoso.partner.onmschina.cn.
  2. OWIN Startup 类中的 ValidateIssuer 参数更改为 trueChange the ValidateIssuer argument in your OWIN Startup class to true.

要仅允许用户来自特定组织的列表,请按照下列步骤操作:To allow users from only a list of specific organizations, follow these steps:

  1. ValidateIssuer 设置为 true。Set ValidateIssuer to true.
  2. 使用 ValidIssuers 参数来指定组织列表。Use the ValidIssuers parameter to specify a list of organizations.

还可通过 IssuerValidator 参数实现自定义方法来验证颁发者。Another option is to implement a custom method to validate the issuers using the IssuerValidator parameter. 有关 TokenValidationParameters 的详细信息,请参阅此 MSDN 文章For more information about TokenValidationParameters, please see this MSDN article.

步骤 11:测试代码Step 11: Test your code

  1. 按 F5 在 Visual Studio 中运行项目。Press F5 to run your project in Visual Studio. 浏览器随即打开,并定向到 http://localhost:{port},可在其中看到“Microsoft 登录”按钮。The browser opens and directs you to http://localhost:{port} where you see the Sign in with Microsoft button.
  2. 选择登录按钮。Select the button to sign in.

登录Sign in

准备好测试后,请使用工作帐户 (Azure AD) 登录。When you're ready to test, use a work account (Azure AD) to sign in.

使用 Microsoft 浏览器窗口登录

使用 Microsoft 浏览器窗口登录

预期结果Expected results

登录后,用户会重定向到网站主页,该网站是门户上的应用程序注册信息中指定的 HTTPS URL。After sign-in, the user is redirected to the home page of your web site, which is the HTTPS URL specified in your application's registration information in the Portal. 此页现在显示“Hello {用户}”、注销链接,以及查看用户声明的链接(即指向之前创建的 Authorize 控制器的链接)。This page now shows Hello {User} and a link to sign out, and a link to see the user’s claims - which is a link to the Authorize controller created earlier.

查看用户的声明See user's claims

选择超链接,查看用户的声明。Select the hyperlink to see the user's claims. 此操作将用户引至控制器和视图,仅供通过身份验证的用户访问。This action leads you to the controller and view that is only available to users that are authenticated.

预期结果Expected results

此时应会显示一个表,其中包含已登录用户的基本属性:You should see a table containing the basic properties of the logged user:

属性Property Value 说明Description
NameName {用户全名}{User Full Name} 用户的名字和姓氏The user’s first and last name
用户名Username user@domain.com 用于标识已登录用户的用户名The username used to identify the logged user
使用者Subject {使用者}{Subject} 一个唯一标识 Web 上用户登录名的字符串A string to uniquely identify the user logon across the web
租户 IDTenant ID {Guid}{Guid} 唯一表示用户的 Azure AD 组织的 guidA guid to uniquely represent the user’s Azure AD organization

此外还可看到一个表格,其中包含身份验证请求中的所有用户声明。In addition, you see a table including all user claims included in authentication request. 有关 ID 令牌和说明中所有声明的列表,请参阅 ID 令牌中的声明列表For a list of all claims in an ID Token and their explanation, see List of claims in ID token.

(可选)访问具有 [Authorize] 属性的方法(Optional) Access a method that has an [Authorize] attribute

此步骤测试作为匿名用户对 Claims 控制器的访问:In this step, you test accessing the Claims controller as an anonymous user:
选择注销用户的链接并完成注销过程。Select the link to sign-out the user and complete the sign-out process.
现在浏览器中键入 http://localhost:{port}/claims,访问受 [Authorize] 属性保护的控制器Now in your browser, type http://localhost:{port}/claims to access your controller that is protected with the [Authorize] attribute

预期结果Expected results

应会出现提示,要求进行身份验证以查看视图。You should receive the prompt requiring you to authenticate to see the view.

其他信息Additional information

保护整个网站Protect your entire web site

若要保护整个网站,请在 Global.asax Application_Start 方法中将 AuthorizeAttribute 添加到 GlobalFiltersTo protect your entire web site, add the AuthorizeAttribute to GlobalFilters in Global.asax Application_Start method:

GlobalFilters.Filters.Add(new AuthorizeAttribute());