- Integrated Windows Authentication
- Брокер веб-проверки подлинности Web authentication broker
- Регистрация приложения у поставщика Register your app with your online provider
- Составление URI запроса проверки подлинности Build the authentication request URI
- Подключение к поставщику Connect to the online provider
- Подключение с единым входом Connecting with single sign-on (SSO).
- Отладка Debugging
- Операционные журналы Operational logs
- Fiddler Fiddler
- Windows. Security. Authentication. Web Namespace
- Classes
- Enums
Integrated Windows Authentication
Integrated Windows authentication enables users to log in with their Windows credentials, using Kerberos or NTLM. The client sends credentials in the Authorization header. Windows authentication is best suited for an intranet environment. For more information, see Windows Authentication.
Advantages | Disadvantages |
---|---|
Built into IIS. | Not recommended for Internet applications. |
Does not send the user credentials in the request. | Requires Kerberos or NTLM support in the client. |
If the client computer belongs to the domain (for example, intranet application), the user does not need to enter credentials. | Client must be in the Active Directory domain. |
If your application is hosted on Azure and you have an on-premise Active Directory domain, consider federating your on-premise AD with Azure Active Directory. That way, users can log in with their on-premise credentials, but the authentication is performed by Azure AD. For more information, see Azure Authentication.
To create an application that uses Integrated Windows authentication, select the «Intranet Application» template in the MVC 4 project wizard. This project template puts the following setting in the Web.config file:
On the client side, Integrated Windows authentication works with any browser that supports the Negotiate authentication scheme, which includes most major browsers. For .NET client applications, the HttpClient class supports Windows authentication:
Windows authentication is vulnerable to cross-site request forgery (CSRF) attacks. See Preventing Cross-Site Request Forgery (CSRF) Attacks.
Брокер веб-проверки подлинности Web authentication broker
В этой статье описывается, как подключить ваше приложение универсальной платформы Windows (UWP) к поставщику сетевых удостоверений, использующему такие протоколы проверки подлинности, как OpenID или OAuth, например, Facebook, Twitter, Flickr, Instagram, и т. д. This article explains how to connect your Universal Windows Platform (UWP) app to an online identity provider that uses authentication protocols like OpenID or OAuth, such as Facebook, Twitter, Flickr, Instagram, and so on. Метод AuthenticateAsync отправляет запрос поставщику сетевых удостоверений и получает маркер доступа, описывающий ресурсы поставщика, к которым имеет доступ приложение. The AuthenticateAsync method sends a request to the online identity provider and gets back an access token that describes the provider resources to which the app has access.
Чтобы получить полный рабочий примера кода, клонируйте репозиторий WebAuthenticationBroker на GitHub. For a complete, working code sample, clone the WebAuthenticationBroker repo on GitHub.
Регистрация приложения у поставщика Register your app with your online provider
Вам нужно зарегистрировать приложение у поставщика сетевых удостоверений, к которому вы хотите подключиться. You must register your app with the online identity provider to which you want to connect. Узнать, как это делается, можно у поставщика сетевых удостоверений. You can find out how to register your app from the identity provider. После регистрации поставщик обычно передает идентификатор или секретный ключ для вашего приложения. After registering, the online provider typically gives you an Id or secret key for your app.
Составление URI запроса проверки подлинности Build the authentication request URI
URI запроса состоит из адреса, по которому поставщику отправляется запрос проверки подлинности, и другой необходимой информации (например, идентификатора приложения или секретных данных), а также URI перенаправления, по которому переходит пользователь, завершивший проверку подлинности, и ожидаемого типа ответа. The request URI consists of the address where you send the authentication request to your online provider appended with other required information, such as an app ID or secret, a redirect URI where the user is sent after completing authentication, and the expected response type. Вы можете выяснить у поставщика, какие именно параметры необходимы. You can find out from your provider what parameters are required.
URI запроса отправляется как параметр requestUri метода AuthenticateAsync. The request URI is sent as the requestUri parameter of the AuthenticateAsync method. Это должен быть безопасный адрес (который начинается с https:// ). It must be a secure address (it must start with https:// )
В следующем примере показано, как составляется URI запроса. The following example shows how to build the request URI.
Подключение к поставщику Connect to the online provider
Для подключения к поставщику сетевых удостоверений и получения маркера доступа вызывается метод AuthenticateAsync. You call the AuthenticateAsync method to connect to the online identity provider and get an access token. В этом методе в качестве параметра requestUri берется URI, созданный на предыдущем шаге, а в качестве параметра callbackUri — URI, выбранный для перенаправления пользователя. The method takes the URI constructed in the previous step as the requestUri parameter, and a URI to which you want the user to be redirected as the callbackUri parameter.
Помимо AuthenticateAsync пространство имен Windows.Security.Authentication.Web включает метод AuthenticateAndContinue. In addition to AuthenticateAsync, the Windows.Security.Authentication.Web namespace contains an AuthenticateAndContinue method. Этот метод не следует вызывать. Do not call this method. Он разработан для приложений, предназначенных для Windows Phone 8.1, и, начиная с Windows 10, считается устаревшим. It is designed for apps targeting Windows Phone 8.1 only and is deprecated starting with Windows 10.
Подключение с единым входом Connecting with single sign-on (SSO).
По умолчанию брокер веб-проверки подлинности не разрешает сохранять файлы cookie. By default, Web authentication broker does not allow cookies to persist. Из-за этого даже в том случае, когда пользователь приложения указывает, что не хочет выходить из приложения (например, установив флажок в диалоговом окне входа в систему поставщика), ему придется выполнять вход каждый раз при обращении к ресурсам данного поставщика. Because of this, even if the app user indicates that they want to stay logged in (for example, by selecting a check box in the provider’s login dialog), they will have to login each time they want to access resources for that provider. Чтобы выполнить вход с помощью единого входа, ваш поставщик сетевых удостоверений должен включить единый вход для брокера веб-проверки подлинности, а ваше приложение должно вызвать перегруженный метод AuthenticateAsync, где не применяется параметр callbackUri parameter. To login with SSO, your online identity provider must have enabled SSO for Web authentication broker, and your app must call the overload of AuthenticateAsync that does not take a callbackUri parameter. Это позволит брокеру веб-проверки подлинности хранить сохраненные файлы cookie, чтобы для будущих вызовов проверки подлинности, совершаемых тем же приложением, пользователю не требовалось выполнять повторный вход (пользователь фактически остается в системе до истечения срока действия маркера доступа). This will allow persisted cookies to be stored by the web authentication broker, so that future authentication calls by the same app will not require repeated sign-in by the user (the user is effectively «logged in» until the access token expires).
Отладка Debugging
Существует несколько способов выполнить диагностику API брокера веб-проверки подлинности, включая просмотр операционных журналов, веб-запросов и ответов с помощью веб-отладчика Fiddler. There are several ways to troubleshoot the web authentication broker APIs, including reviewing operational logs and reviewing web requests and responses using Fiddler.
Операционные журналы Operational logs
Нередко определить, что именно не работает, помогают операционные журналы. Often you can determine what is not working by using the operational logs. Существует выделенный канал журнала событий Microsoft-Windows- \ Web AUTH, позволяющий разработчикам веб-сайтов понять, как веб-страницы обрабатываются брокером веб-проверки подлинности. There is a dedicated event log channel Microsoft-Windows-WebAuth\Operational that allows website developers to understand how their web pages are being processed by the Web authentication broker. Чтобы включить его, запустите eventvwr.exe и включите операционный журнал в приложении и службах \ Microsoft \ Windows веб \ AUTH. To enable it, launch eventvwr.exe and enable Operational log under the Application and Services\Microsoft\Windows\WebAuth. Брокер веб-проверки подлинности также добавляет уникальную строку к строке агента пользователя, чтобы идентифицировать себя на веб-сервере. Also, the Web authentication broker appends a unique string to the user agent string to identify itself on the web server. Это строка «MSAuthHost/1.0». The string is «MSAuthHost/1.0». Обратите внимание, что номер версии в дальнейшем может меняться, поэтому ваш код не должен зависеть от номера версии. Note that the version number may change in the future, so you should not to depend on that version number in your code. Ниже приведен пример полной строки агента пользователя и полной процедуры отладки. An example of the full user agent string, followed by full debugging steps, is as follows.
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0; MSAuthHost/1.0)
- Включите операционные журналы. Enable operational logs.
- Запустите социальное приложение Contoso. Run Contoso social application.
- Записи, созданные в журналах, помогают глубже вникнуть в особенности поведения брокера веб-проверки подлинности. The generated logs entries can be used to understand the behavior of Web authentication broker in greater detail. В нашем случае записи могут содержать следующую информацию. In this case, these can include:
- Навигация начата: регистрирует время запуска AuthHost и содержит сведения о URL-адресах начала и окончания навигации. Navigation Start: Logs when the AuthHost is started and contains information about the start and termination URLs.
- Навигация выполнена: регистрирует выполнение загрузки веб-страницы. Navigation Complete: Logs the completion of loading a web page.
- Метатег: регистрирует подробную информацию в случае обнаружения метатега. Meta Tag: Logs when a meta-tag is encountered including the details.
- Завершение навигации: навигация завершена пользователем. Navigation Terminate: Navigation terminated by the user.
- Ошибка навигации: AuthHost обнаруживает ошибку навигации в URL-адресе, включая код состояния HttpStatusCode. Navigation Error: AuthHost encounters a navigation error at a URL including HttpStatusCode.
- Завершение навигации: обнаружен завершающий URL-адрес. Navigation End: Terminating URL is encountered.
Fiddler Fiddler
Веб-отладчик Fiddler можно использовать с приложениями. The Fiddler web debugger can be used with apps.
Поскольку AuthHost выполняется в собственном контейнере приложения, чтобы предоставить ему возможность частной сети, необходимо задать раздел реестра: редактор реестра Windows версии 5,00 Since the AuthHost runs in its own app container, to give it the private network capability you must set a registry key: Windows Registry Editor Version 5.00
HKey _ _ \ SOFTWARE \ Microsoft \ Windows NT \ CurrentVersion \ Параметры выполнения файлов образа Microsoft Windows NT CurrentVersion по локальному компьютеру \ authhost.exe \ енаблеприватенетворк = 00000001 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\authhost.exe\EnablePrivateNetwork = 00000001
Если этот раздел реестра отсутствует, его можно создать в командной строке с правами администратора. If you do not have this registry key, you can create it in a Command Prompt with administrator privileges.
Добавьте правило для AuthHost, поскольку эта служба создает исходящий трафик. Add a rule for the AuthHost as this is what is generating the outbound traffic.
Добавьте правило брандмауэра для входящего трафика в Fiddler. Add a firewall rule for incoming traffic to Fiddler.
Windows. Security. Authentication. Web Namespace
Enables apps to integrate with online web services without exposing a user’s credentials. The web authentication broker provides a set of APIs and infrastructure for apps to use Internet authentication and authorization protocols like OAuth and OpenID.
The single sign-on (SSO) mode of the web authentication broker APIs is provided to enable users to seamlessly authenticate to a single service across multiple apps. The provider of the service must allow the user to explicitly consent to that authentication, typically by providing a «Keep me logged in» option. The provider must also make it clear to the user how their identity is being used, typically by providing a link to a privacy statement from the logon page.
The Web authentication broker sample in the Samples gallery is an example of how to use single sign on (SSO) for connections.
If your app or its companion website accesses user data in Outlook.com or Microsoft OneDrive, the Live ConnectВ API hides some of the complexities of authentication tokens and make it a bit easier to write code to work with these cloud services. For more information about the Live ConnectВ API, see Using Live Connect to personalize apps (HTML) or Using Live Connect to personalize apps (XAML).
Classes
Starts the authentication operation. You can call the methods of this class multiple times in a single application or across multiple applications at the same time. The Web authentication broker sample in the Samples gallery is an example of how to use the WebAuthenticationBroker class for single sign on (SSO) connections.
Indicates the result of the authentication operation.
Enums
Gets the type of key used for token binding.
Contains the options available to the asynchronous operation.
Contains the status of the authentication operation.