快速入门:生成一个与 Azure AD 集成以进行身份验证和授权的 .NET Web APIQuickstart: Build a .NET web API that integrates with Azure AD for authentication and authorization

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

如果正在生成的应用程序提供对受保护资源的访问,则需要知道如何防止有人在未经授权的情况下访问这些资源。If you’re building an application that provides access to protected resources, you need to know how to prevent unwarranted access to those resources. 借助 Azure Active Directory (Azure AD),只需编写几行代码,即可使用 OAuth 2.0 持有者访问令牌简单直接地保护 Web API。Azure Active Directory (Azure AD) makes it simple and straightforward to help protect a web API by using OAuth 2.0 bearer access tokens with only a few lines of code.

在 ASP.NET Web 应用中,可以使用 .NET Framework 4.5 中包含的社区驱动 OWIN 中间件的 Microsoft 实现来完成保护。In ASP.NET web apps, you can accomplish this protection by using the Microsoft implementation of the community-driven OWIN middleware included in .NET Framework 4.5. 现在,我们将使用 OWIN 来生成“待办事项列表”Web API:Here you'll use OWIN to build a "To Do List" web API that:

  • 指定要保护哪些 API。Designates which APIs are protected.
  • 验证 Web API 调用是否包含有效的访问令牌。Validates that the web API calls contain a valid access token.

在此快速入门中,你将生成待办事项列表 API 并了解如何:In this quickstart, you'll build the To Do List API and learn how to:

  1. 将一个应用程序注册到 Azure AD。Register an application with Azure AD.
  2. 将应用设置为使用 OWIN 身份验证管道。Set up the app to use the OWIN authentication pipeline.
  3. 配置一个客户端应用程序以调用 Web API。Configure a client application to call the web API.


开始前,请完成这些先决条件:To get started, complete these prerequisites:

步骤 1:将应用程序注册到 Azure ADStep 1: Register an application with Azure AD

若要帮助保护应用程序,首先需要在租户中创建一个应用程序,并向 Azure AD 提供一些关键信息。To help secure your application, you first need to create an application in your tenant and provide Azure AD with a few key pieces of information.

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 通过以下方式选择 Azure AD 租户:在页面右上角选择你的帐户,选择“切换目录”导航,然后选择合适的租户。Choose your Azure AD tenant by selecting your account in the top right corner of the page, select the Switch directory navigation, and then select the appropriate tenant.

    • 如果你的帐户下只有一个 Azure AD 租户,或者已选择了合适的 Azure AD 租户,请跳过此步骤。Skip this step, if you've only one Azure AD tenant under your account or if you've already selected the appropriate Azure AD tenant.
  3. 在左侧导航窗格中,选择“Azure Active Directory”。In the left-hand navigation pane, select Azure Active Directory.

  4. 选择“应用注册”,并选择“添加”。Select App registrations, and then select Add.

  5. 根据提示创建一个新的 Web 应用程序和/或 Web APIFollow the prompts and create a new Web Application and/or Web API.

    • 名称向用户描述应用程序。Name describes your application to users. 输入待办事项列表服务Enter To Do List Service.
    • “重定向 URI”是 Azure AD 用来返回应用程序请求的任何令牌的方案与字符串组合。Redirect URI is a scheme and string combination that Azure AD uses to return any tokens that your app has requested. 为此值输入 https://localhost:44321/Enter https://localhost:44321/ for this value.
  6. 在应用程序的“设置”>“属性”页中,更新应用 ID URI。From the Settings > Properties page for your application, update the App ID URI. 输入租户特定的标识符。Enter a tenant-specific identifier. 例如,输入 https://contoso.partner.onmschina.cn/TodoListServiceFor example, enter https://contoso.partner.onmschina.cn/TodoListService.

  7. 保存配置。Save the configuration. 让门户保持打开状态,因为稍后你还需要注册客户端应用程序。Leave the portal open, because you'll also need to register your client application shortly.

步骤 2:将应用设置为使用 OWIN 身份验证管道Step 2: Set up the app to use the OWIN authentication pipeline

要验证传入的请求和令牌,需要将应用程序设置为与 Azure AD 通信。To validate incoming requests and tokens, you need to set up your application to communicate with Azure AD.

  1. 要开始,请打开解决方案,然后使用包管理器控制台将 OWIN 中间件 NuGet 包添加到 TodoListService 项目。To begin, open the solution and add the OWIN middleware NuGet packages to the TodoListService project by using the Package Manager Console.

    PM> Install-Package Microsoft.Owin.Security.ActiveDirectory -ProjectName TodoListService
    PM> Install-Package Microsoft.Owin.Host.SystemWeb -ProjectName TodoListService
  2. 将名为 Startup.cs 的 OWIN 启动类添加到 TodoListService 项目。Add an OWIN Startup class to the TodoListService project called Startup.cs. 右键单击项目,选择“添加”>“新建项”,然后搜索“OWIN”。Right-click the project, select Add > New Item, and then search for OWIN. 当应用程序启动时,该 OWIN 中间件将调用 Configuration(…) 方法。The OWIN middleware will invoke the Configuration(…) method when your app starts.

  3. 将类声明更改为 public partial class StartupChange the class declaration to public partial class Startup. 我们已在另一个文件中实现了此类的一部分。We’ve already implemented part of this class for you in another file. Configuration(…) 方法中,调用 ConfgureAuth(…) 以设置 Web 应用的身份验证。In the Configuration(…) method, make a call to ConfgureAuth(…) to set up authentication for your web app.

    public partial class Startup
        public void Configuration(IAppBuilder app)
  4. 打开文件 App_Start\Startup.Auth.cs 并实现 ConfigureAuth(…) 方法。Open the file App_Start\Startup.Auth.cs and implement the ConfigureAuth(…) method. WindowsAzureActiveDirectoryBearerAuthenticationOptions 中提供的参数充当应用与 Azure AD 通信时使用的坐标。The parameters that you provide in WindowsAzureActiveDirectoryBearerAuthenticationOptions will serve as coordinates for your app to communicate with Azure AD. 若要使用它们,需使用 System.IdentityModel.Tokens 命名空间中的类。To use them you'll need to use classes in the System.IdentityModel.Tokens namespace.

    using System.IdentityModel.Tokens;
    public void ConfigureAuth(IAppBuilder app)
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                 Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
                 TokenValidationParameters = new TokenValidationParameters
                    ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
  5. 使用 [Authorize] 属性并结合 JSON Web 令牌 (JWT) 持有者身份验证来保护控制器和操作。Use the [Authorize] attributes to help protect your controllers and actions with JSON Web Token (JWT) bearer authentication. 使用授权标记修饰 Controllers\TodoListController.cs 类,这会强制用户在访问该页面之前进行登录。Decorate the Controllers\TodoListController.cs class with an authorize tag, which forces the user to sign in before accessing that page.

    public class TodoListController : ApiController

    如果已授权的调用方成功调用了某个 TodoListController API,该操作可能需要访问有关调用方的信息。When an authorized caller successfully invokes one of the TodoListController APIs, the action might need access to information about the caller. OWIN 通过 ClaimsPrincpal 对象提供对持有者令牌中的声明的访问。OWIN provides access to the claims inside the bearer token via the ClaimsPrincpal object.

  6. Web API 的一个常见要求是验证令牌中的“作用域”,以确保最终用户授予访问待办事项列表服务所需的权限。A common requirement for web APIs is to validate the "scopes" present in the token to ensure that the user has consented to the permissions required to access the To Do List Service.

    public IEnumerable<TodoItem> Get()
        // user_impersonation is the default permission exposed by applications in Azure AD
        if (ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value != "user_impersonation")
            throw new HttpResponseException(new HttpResponseMessage {
              StatusCode = HttpStatusCode.Unauthorized,
              ReasonPhrase = "The Scope claim does not contain 'user_impersonation' or scope claim not found"
  7. 打开位于 TodoListService 项目根目录中的 web.config 文件,并在 <appSettings> 节中输入你的配置值。Open the web.config file in the root of the TodoListService project, and enter your configuration values in the <appSettings> section.

    • ida:Tenant 是 Azure AD 租户的名称,例如,contoso.partner.onmschina.cn。ida:Tenant is the name of your Azure AD tenant--for example, contoso.partner.onmschina.cn.
    • ida:Audience 是在 Azure 门户中为应用程序输入的应用 ID URI。ida:Audience is the App ID URI of the application that you entered in the Azure portal.

步骤 3:配置客户端应用程序并运行服务Step 3: Configure a client application and run the service

需要先配置待办事项列表客户端,使它能够从 Azure AD 获取令牌并可调用服务,然后才能看到待办事项列表服务的运行情况。Before you can see the To Do List Service in action, you need to configure the To Do List client so it can get tokens from Azure AD and make calls to the service.

  1. 返回到 Azure 门户Go back to the Azure portal.

  2. 在 Azure AD 租户中创建新的应用程序,并在最终提示中选择“本机客户端应用程序” 。Create a new application in your Azure AD tenant, and select Native Client Application in the resulting prompt.

    • 名称向用户描述应用程序。Name describes your application to users.
    • 输入 http://TodoListClient/ 作为“重定向 URI”值。Enter http://TodoListClient/ for the Redirect URI value.
  3. 完成注册后,Azure AD 将向应用分配唯一应用程序 ID。After you finish registration, Azure AD assigns a unique application ID to your app. 在后面的步骤中会用到此值,因此,请从应用程序页复制此值。You’ll need this value in the next steps, so copy it from the application page.

  4. 在“设置”页上,选择“所需权限”,并选择“添加”。From the Settings page, select Required Permissions, and then select Add. 找到并选择待办事项列表服务,在“委派的权限”下添加“访问 TodoListService”权限,并选择“完成”。Locate and select the To Do List Service, add the Access TodoListService permission under Delegated Permissions, and then select Done.

  5. 在 Visual Studio 中,打开 TodoListClient 项目中的 App.config,然后在 <appSettings> 节中输入配置值。In Visual Studio, open App.config in the TodoListClient project, and then enter your configuration values in the <appSettings> section.

    • ida:Tenant 是 Azure AD 租户的名称,例如,contoso.partner.onmschina.cn。ida:Tenant is the name of your Azure AD tenant, for example, contoso.partner.onmschina.cn.
    • ida:ClientId 是从 Azure 门户复制的应用 ID。ida:ClientId is the app ID that you copied from the Azure portal.
    • todo:TodoListResourceId 是在 Azure 门户中为待办事项列表服务应用程序输入的应用 ID URI。todo:TodoListResourceId is the App ID URI of the To Do List Service application that you entered in the Azure portal.
  6. 清理、生成并运行每个项目。Clean, build, and run each project.

  7. 可以使用 *.partner.onmschina.cn 域在租户中创建一个新用户(如果尚未这样做)。If you haven’t done so already, create a new user in your tenant with a *.partner.onmschina.cn domain.

  8. 以该用户的身份登录到待办事项列表客户端,并向该用户的待办事项列表添加一些任务。Sign in to the To Do List client with that user, and add some tasks to the user's to-do list.

后续步骤Next steps

  • 有关参考,请从 GitHub 下载已完成的示例(无配置值)。For reference, download the completed sample (without your configuration values) from GitHub. 现在,可以转到其他标识方案。You can now move on to other identity scenarios.