- Веб-приложение, которое входит в систему пользователей: конфигурация кода Web app that signs in users: Code configuration
- Библиотеки Майкрософт, поддерживающие веб-приложения Microsoft libraries supporting web apps
- Файлы конфигурации. Configuration files
- Код инициализации Initialization code
- Следующие шаги Next steps
Веб-приложение, которое входит в систему пользователей: конфигурация кода Web app that signs in users: Code configuration
Узнайте, как настроить код для веб-приложения, которое входит в систему пользователей. Learn how to configure the code for your web app that signs in users.
Библиотеки Майкрософт, поддерживающие веб-приложения Microsoft libraries supporting web apps
Для защиты веб-приложения (и веб-API) используются следующие библиотеки Майкрософт: The following Microsoft libraries are used to protect a web app (and a web API):
Язык и платформа Language / framework | Проект включен Project on GitHub GitHub | Пакет Package | Появляться Getting запущен started | Выполнение входа пользователей Sign in users | Доступ к веб-API Access web APIs | Общедоступная версия (GA) или Generally available (GA) or Общедоступная Предварительная версия 1 Public preview 1 |
---|---|---|---|---|---|---|
.NET .NET | MSAL.NET MSAL.NET | Microsoft.Identity.Client Microsoft.Identity.Client | — — | GA GA | ||
ASP.NET Core ASP.NET Core | Безопасность ASP.NET ASP.NET Security | Microsoft.AspNetCore.Authentication Microsoft.AspNetCore.Authentication | — — | GA GA | ||
ASP.NET Core ASP.NET Core | Microsoft. Identity. Web Microsoft.Identity.Web | Microsoft. Identity. Web Microsoft.Identity.Web | — — | GA GA | ||
Java Java | MSAL4J MSAL4J | msal4j msal4j | Краткое руководство Quickstart | GA GA | ||
Node.js Node.js | MSAL Node MSAL Node | msal-node msal-node | Краткое руководство Quickstart | GA GA | ||
Node.js Node.js | Azure AD Passport Azure AD Passport | Passport-Azure-AD passport-azure-ad | Краткое руководство Quickstart | GA GA | ||
Python Python | MSAL Python MSAL Python | msal msal | Краткое руководство Quickstart | GA GA |
Выберите вкладку, соответствующую интересующей вас платформе: Select the tab that corresponds to the platform you’re interested in:
Фрагменты кода в этой статье и следующие извлекаются из пошагового руководства по ASP.NET Core веб-приложению, главе 1. Code snippets in this article and the following are extracted from the ASP.NET Core web app incremental tutorial, chapter 1.
Для получения подробных сведений о реализации может потребоваться обратиться к этому учебнику. You might want to refer to this tutorial for full implementation details.
Фрагменты кода в этой статье и следующие извлекаются из примера веб-приложения ASP.NET. Code snippets in this article and the following are extracted from the ASP.NET web app sample.
Для получения полной информации о реализации можно использовать этот пример. You might want to refer to this sample for full implementation details.
Фрагменты кода в этой статье и следующие извлекаются из примера веб-приложения Java, вызывающего Microsoft Graph в MSAL Java. Code snippets in this article and the following are extracted from the Java web application calling Microsoft graph sample in MSAL Java.
Для получения полной информации о реализации можно использовать этот пример. You might want to refer to this sample for full implementation details.
Фрагменты кода в этой статье и следующие извлекаются из Node.js вход пользователей в веб-приложение в примере в узле MSAL. Code snippets in this article and the following are extracted from the Node.js web application signing users in sample in MSAL Node.
Для получения полной информации о реализации можно использовать этот пример. You might want to refer to this sample for full implementation details.
Фрагменты кода в этой статье и следующие извлекаются из примера веб-приложения Python, вызывающего Microsoft Graph в MSAL Python. Code snippets in this article and the following are extracted from the Python web application calling Microsoft graph sample in MSAL Python.
Для получения полной информации о реализации можно использовать этот пример. You might want to refer to this sample for full implementation details.
Файлы конфигурации. Configuration files
Веб-приложения, которые входят в систему пользователей с помощью платформы Microsoft Identity, настраиваются с помощью файлов конфигурации. Web applications that sign in users by using the Microsoft identity platform are configured through configuration files. Ниже приведены значения, которые необходимо указать в конфигурации. These are the values you’re required to specify in the configuration:
- Облачный экземпляр ( Instance ), если вы хотите, чтобы приложение выполнялось в национальных облаках, например The cloud instance ( Instance ) if you want your app to run in national clouds, for example
- Аудитория в ИДЕНТИФИКАТОРе клиента ( TenantId ) The audience in the tenant ID ( TenantId )
- Идентификатор клиента ( ClientId ) для приложения, скопированный из портал Azure The client ID ( ClientId ) for your application, as copied from the Azure portal
Также можно увидеть ссылки на Authority . You might also see references to the Authority . Authority Значение представляет собой объединение Instance TenantId значений и. The Authority value is the concatenation of the Instance and TenantId values.
В ASP.NET Core эти параметры расположены в файле appsettings.js в разделе «AzureAd». In ASP.NET Core, these settings are located in the appsettings.json file, in the «AzureAd» section.
В ASP.NET Core другой файл (properties\launchSettings.jsв) содержит URL-адрес ( applicationUrl ) и порт TLS/SSL ( sslPort ) для приложения и различных профилей. In ASP.NET Core, another file (properties\launchSettings.json) contains the URL ( applicationUrl ) and the TLS/SSL port ( sslPort ) for your application and various profiles.
В портал Azure идентификаторы URI перенаправления, регистрируемые на странице проверки подлинности для вашего приложения, должны соответствовать этим URL-адресам. In the Azure portal, the redirect URIs that you register on the Authentication page for your application need to match these URLs. Для двух предыдущих файлов конфигурации они бы были https://localhost:44321/signin-oidc . For the two preceding configuration files, they would be https://localhost:44321/signin-oidc . Причина в том, что applicationUrl это http://localhost:3110 , но sslPort указано (44321). The reason is that applicationUrl is http://localhost:3110 , but sslPort is specified (44321). CallbackPath имеет /signin-oidc , как определено в appsettings.json . CallbackPath is /signin-oidc , as defined in appsettings.json .
Таким же образом URI выхода будет иметь значение https://localhost:44321/signout-oidc . In the same way, the sign-out URI would be set to https://localhost:44321/signout-oidc .
В ASP.NET приложение настраивается с помощью файла Web.config , строки 12 – 15. In ASP.NET, the application is configured through the Web.config file, lines 12 to 15.
В портал Azure идентификаторы URI ответа, регистрируемые на странице проверки подлинности для вашего приложения, должны соответствовать этим URL-адресам. In the Azure portal, the reply URIs that you register on the Authentication page for your application need to match these URLs. То есть они должны быть https://localhost:44326/ . That is, they should be https://localhost:44326/ .
В Java конфигурация находится в файле приложения. Properties , расположенном в папке src/main/resources . In Java, the configuration is located in the application.properties file located under src/main/resources .
В портал Azure идентификаторы URI ответа, регистрируемые на странице проверки подлинности для приложения, должны совпадать с redirectUri экземплярами, которые определяет приложение. In the Azure portal, the reply URIs that you register on the Authentication page for your application need to match the redirectUri instances that the application defines. То есть они должны быть http://localhost:8080/msal4jsample/secure/aad и http://localhost:8080/msal4jsample/graph/me . That is, they should be http://localhost:8080/msal4jsample/secure/aad and http://localhost:8080/msal4jsample/graph/me .
Здесь параметры конфигурации находятся в index.js Here, the configuration parameters reside in index.js
В портал Azure URI-коды ответов, регистрируемые на странице проверки подлинности для приложения, должны соответствовать экземплярам redirectUri, определяемым приложением ( http://localhost:3000/redirect ). In the Azure portal, the reply URIs that you register on the Authentication page for your application need to match the redirectUri instances that the application defines ( http://localhost:3000/redirect ).
В этом кратком руководстве предлагается сохранить секрет клиента в файле конфигурации для простоты. This quickstart proposes to store the client secret in the configuration file for simplicity. В рабочем приложении необходимо использовать другие способы хранения секрета, например хранилище ключей или переменную среды. In your production app, you’d want to use other ways to store your secret, such as a key vault or an environment variable.
Ниже приведен файл конфигурации Python в app_config. Корректировка: Here’s the Python configuration file in app_config.py:
В этом кратком руководстве предлагается сохранить секрет клиента в файле конфигурации для простоты. This quickstart proposes to store the client secret in the configuration file for simplicity. В рабочем приложении необходимо использовать другие способы хранения секрета, например хранилище ключей или переменную среды, как описано в документации по Flask. In your production app, you’d want to use other ways to store your secret, such as a key vault or an environment variable as described in Flask’s documentation.
Код инициализации Initialization code
Код инициализации различается в зависимости от платформы. The initialization code is different depending on the platform. Для ASP.NET Core и ASP.NET при входе в систему пользователи делегируются по промежуточного слоя OpenID Connect Connect. For ASP.NET Core and ASP.NET, signing in users is delegated to the OpenID Connect middleware. Шаблон ASP.NET или ASP.NET Core создает веб-приложения для конечной точки Azure Active Directory (Azure AD) v 1.0. The ASP.NET or ASP.NET Core template generates web applications for the Azure Active Directory (Azure AD) v1.0 endpoint. Для адаптации к платформе Microsoft Identity требуется определенная конфигурация. Some configuration is required to adapt them to the Microsoft identity platform. В случае с Java оно обрабатывается пружиной с совместным использованием приложения. In the case of Java, it’s handled by Spring with the cooperation of the application.
В ASP.NET Core веб-приложениях (и веб-API) приложение защищено, так как у вас есть [Authorize] атрибут на контроллерах или действия контроллера. In ASP.NET Core web apps (and web APIs), the application is protected because you have a [Authorize] attribute on the controllers or the controller actions. Этот атрибут проверяет, прошел ли пользователь проверку подлинности. This attribute checks that the user is authenticated. Код, который инициализирует приложение, находится в файле Startup. CS . The code that’s initializing the application is in the Startup.cs file.
Чтобы добавить проверку подлинности на платформе Microsoft Identity (прежнее название — Azure AD 2.0), необходимо добавить следующий код. To add authentication with the Microsoft identity platform (formerly Azure AD v2.0), you’ll need to add the following code. Комментарии в коде должны быть описательными. The comments in the code should be self-explanatory.
Если вы хотите непосредственно начать с новых шаблонов ASP.NET Core для платформы Microsoft Identity, использующих Microsoft. Identity. Web, можно скачать предварительную версию пакета NuGet, содержащую шаблоны проектов для .NET Core 3,1 и .NET 5,0. If you want to start directly with the new ASP.NET Core templates for Microsoft identity platform, that leverage Microsoft.Identity.Web, you can download a preview NuGet package containing project templates for .NET Core 3.1 and .NET 5.0. После установки можно напрямую создать экземпляр ASP.NET Core веб-приложений (MVC или Блазор). Then, once installed, you can directly instantiate ASP.NET Core web applications (MVC or Blazor). Дополнительные сведения см. в статье шаблоны проектов веб-приложений Microsoft. Identity. Web App . See Microsoft.Identity.Web web app project templates for details. Это самый простой подход, так как он выполняет все приведенные ниже действия. This is the simplest approach as it will do all the steps below for you.
Если вы предпочитаете запускать проект с текущим веб-проектом ASP.NET Core по умолчанию в Visual Studio или с помощью dotnet new mvc —auth SingleAuth или dotnet new webapp —auth SingleAuth , вы увидите код, подобный следующему: If you prefer to start your project with the current default ASP.NET Core web project within Visual Studio or by using dotnet new mvc —auth SingleAuth or dotnet new webapp —auth SingleAuth , you’ll see code like the following:
В этом коде используется устаревший пакет NuGet Microsoft. AspNetCore. Authentication. AzureAD. UI , который используется для создания приложения Azure AD версии 1.0. This code uses the legacy Microsoft.AspNetCore.Authentication.AzureAD.UI NuGet package which is used to create an Azure AD v1.0 application. В этой статье объясняется, как создать приложение платформы удостоверений Microsoft Identity (Azure AD 2.0), заменяющее этот код. This article explains how to create a Microsoft identity platform (Azure AD v2.0) application which replaces that code.
Добавьте в проект пакеты NuGet Microsoft. Identity. Web и Microsoft. Identity. Web. UI . Add the Microsoft.Identity.Web and Microsoft.Identity.Web.UI NuGet packages to your project. Удалите пакет NuGet Microsoft. AspNetCore. Authentication. AzureAD. UI, если он имеется. Remove the Microsoft.AspNetCore.Authentication.AzureAD.UI NuGet package if it is present.
Обновите код в ConfigureServices , чтобы он использовал AddMicrosoftIdentityWebAppAuthentication методы и AddMicrosoftIdentityUI . Update the code in ConfigureServices so that it uses the AddMicrosoftIdentityWebAppAuthentication and AddMicrosoftIdentityUI methods.
В Configure методе в Startup. CS включите проверку подлинности с помощью вызова app.UseAuthentication(); In the Configure method in Startup.cs, enable authentication with a call to app.UseAuthentication();
В приведенном выше коде: In the code above:
AddMicrosoftIdentityWebAppAuthentication Метод расширения определен в Microsoft. Identity. Web. The AddMicrosoftIdentityWebAppAuthentication extension method is defined in Microsoft.Identity.Web. Им It:
- Добавляет службу проверки подлинности. Adds the authentication service.
- Настраивает параметры для чтения файла конфигурации (здесь из раздела «AzureAD»). Configures options to read the configuration file (here from the «AzureAD» section)
- Настраивает параметры OpenID Connect Connect, чтобы центр сертификации был платформой Microsoft Identity. Configures the OpenID Connect options so that the authority is the Microsoft identity platform.
- Проверяет издателя маркера. Validates the issuer of the token.
- Гарантирует, что утверждения, соответствующие имени, сопоставляются с preferred_username утверждением в маркере идентификации. Ensures that the claims corresponding to name are mapped from the preferred_username claim in the ID token.
В дополнение к объекту конфигурации можно указать имя раздела конфигурации при вызове AddMicrosoftIdentityWebAppAuthentication . In addition to the configuration object, you can specify the name of the configuration section when calling AddMicrosoftIdentityWebAppAuthentication . По умолчанию это AzureAd . By default, it’s AzureAd .
AddMicrosoftIdentityWebAppAuthentication имеет другие параметры для расширенных сценариев. AddMicrosoftIdentityWebAppAuthentication has other parameters for advanced scenarios. Например, трассировка событий по промежуточного слоя OpenID Connect позволяет устранить неполадки в веб-приложении, если проверка подлинности не работает. For example, tracing OpenID Connect middleware events can help you troubleshoot your web application if authentication doesn’t work. При установке необязательного параметра subscribeToOpenIdConnectMiddlewareDiagnosticsEvents true будет показано, как обрабатывается информация по по промежуточного слоя ASP.NET Core по мере продвижения от HTTP-ответа к удостоверению пользователя в HttpContext.User . Setting the optional parameter subscribeToOpenIdConnectMiddlewareDiagnosticsEvents to true will show you how information is processed by the set of ASP.NET Core middleware as it progresses from the HTTP response to the identity of the user in HttpContext.User .
AddMicrosoftIdentityUI Метод расширения определен в Microsoft. Identity. Web. UI. The AddMicrosoftIdentityUI extension method is defined in Microsoft.Identity.Web.UI. Он предоставляет контроллер по умолчанию для управления входом и выходом. It provides a default controller to handle sign-in and sign-out.
Дополнительные сведения о том, как Microsoft. Identity. Web позволяет создавать веб-приложения, можно найти в https://aka.ms/ms-id-web/webapp You can find more details about how Microsoft.Identity.Web enables you to create web apps in https://aka.ms/ms-id-web/webapp
В настоящее время Microsoft. Identity. Web не поддерживает сценарий использования отдельных учетных записей пользователей (хранение учетных записей пользователей в приложении) при использовании Azure AD как и внешнего поставщика входа. Currently, Microsoft.Identity.Web does not support the scenario of Individual User Accounts (storing user accounts in-app) when using Azure AD as and external login provider. Дополнительные сведения см. в статье AzureAD/Microsoft-Identity-Web # 133 For details, see: AzureAD/microsoft-identity-web#133
Код, связанный с проверкой подлинности в веб-приложении ASP.NET и веб-API, находится в файле App_Start/стартуп.АУС.КС . The code related to authentication in an ASP.NET web app and web APIs is located in the App_Start/Startup.Auth.cs file.
В примере Java используется пружинная платформа. The Java sample uses the Spring framework. Приложение защищено, так как вы реализуете фильтр, который перехватывает каждый HTTP-ответ. The application is protected because you implement a filter, which intercepts each HTTP response. В кратком руководстве по веб-приложениям Java этот фильтр находится AuthFilter в src/main/java/com/microsoft/azure/msalwebsample/AuthFilter.java . In the quickstart for Java web apps, this filter is AuthFilter in src/main/java/com/microsoft/azure/msalwebsample/AuthFilter.java .
Фильтр обрабатывает поток кода авторизации OAuth 2,0 и проверяет, прошел ли пользователь проверку подлинности ( isAuthenticated() метод). The filter processes the OAuth 2.0 authorization code flow and checks if the user is authenticated ( isAuthenticated() method). Если пользователь не прошел проверку подлинности, он рассчитывает URL-адрес конечных точек авторизации Azure AD и перенаправляет браузер на этот универсальный код ресурса (URI). If the user isn’t authenticated, it computes the URL of the Azure AD authorization endpoints, and redirects the browser to this URI.
Когда получен ответ, содержащий код авторизации, он получает маркер с помощью MSAL Java. When the response arrives, containing the authorization code, it acquires the token by using MSAL Java. Когда он наконец получает маркер из конечной точки маркера (в URI перенаправления), пользователь вошел в систему. When it finally receives the token from the token endpoint (on the redirect URI), the user is signed in.
Дополнительные сведения см. в описании doFilter() метода в аусфилтер. Java. For details, see the doFilter() method in AuthFilter.java.
Код doFilter() написан немного иначе, но последовательность описана в этом порядке. The code of the doFilter() is written in a slightly different order, but the flow is the one described.
Дополнительные сведения о потоке кода авторизации, который запускается этим методом, см. в статье поток кода авторизации для платформы Microsoft Identity и OAuth 2,0. For details about the authorization code flow that this method triggers, see the Microsoft identity platform and OAuth 2.0 authorization code flow.
В образце Python используется Flask. The Python sample uses Flask. Инициализация Flask и MSAL Python выполняется в app. копировать # L1-L28. The initialization of Flask and MSAL Python is done in app.py#L1-L28.
Следующие шаги Next steps
В следующей статье вы узнаете, как активировать вход и выход. In the next article, you’ll learn how to trigger sign-in and sign-out.
Перейдите к следующей статье в этом сценарии, Войдите и выйдитеиз нее. Move on to the next article in this scenario, Sign in and sign out.
Перейдите к следующей статье в этом сценарии, Войдите и выйдитеиз нее. Move on to the next article in this scenario, Sign in and sign out.
Перейдите к следующей статье в этом сценарии, Войдите и выйдитеиз нее. Move on to the next article in this scenario, Sign in and sign out.
Перейдите к следующей статье в этом сценарии, Войдите всистему. Move on to the next article in this scenario, Sign in.
Перейдите к следующей статье в этом сценарии, Войдите и выйдитеиз нее. Move on to the next article in this scenario, Sign in and sign out.