Iis authentication windows authentication
Стандартные возможности аутентификации Internet Information Server (IIS), анонимный доступ, методы аутентификации, учетная запись IUSR_
Большая часть серверов IIS работает без требований к пользователю аутентифицироваться — то есть в режиме анонимного доступа. На самом деле такие анонимные пользователи работают от имени специальной учетной записи IUSR _имя_компьютера. Конечно же, настоятельно не рекомендуется использовать эту учетную запись для каких-то других целей, добавлять ее в другие группы (кроме группы Guests ), в которой эта учетная запись находится по умолчанию и т.п.
Однако в некоторых ситуациях анонимным доступом не обойтись. Обычно аутентификация требуется в двух случаях:
1) когда на Web -сервере находятся ресурсы, доступ к которым нужен не всем пользователям (проще говоря, чтобы задействовать систему разрешений);
2) для целей дополнительного протоколирования — чтобы можно было записывать информацию о том, какие именно пользователи обращались к ресурсам Web -сайта (во многих ситуациях, например в локальной сети, в этом случае можно обойтись без аутентификации — поскольку текущее имя пользователя автоматически записывается в логи Web -сервера).
Аутентификация в IIS , к сожалению, полностью основывается на системе безопасности Windows . Фактически мы можем предоставить доступ только тем пользователям, для которых у нас создана локальная учетная запись (или доменная учетная запись, если компьютер с IIS входит в домен). Конечно, по этой причине доступ на IIS со стандартными средствами можно предоставлять только пользователям локальной сети (или, например, очень ограниченному числу внешних партнеров). Рассчитывать на организацию системы аутентификации для пользователей из Интернета стандартными средствами не приходится (поскольку для каждого пользователя учетную запись Windows не создашь). Обычно для таких целей используются или самостоятельно созданные Web -приложения, или специальные надстройки на IIS , которые обеспечивают отдельную, независимую от Windows систему аутентификации. Ниже будет рассмотрены стандартные возможности аутентификации, а затем — дополнительные средства других производителей.
Настройку аутентификации стандартными методами предписывается производить из консоли Internet Information Services Manager -> свойства Web -сайта -> вкладка Directory Security -> кнопка Edit в группе Authentification and Access Control . При нажатии на эту кнопку открывается окно Authentification Method , в котором и производятся настройки параметров аутентификации. В этом окне вы можете:
- разрешить или запретить анонимный доступ на Web -сайт и выбрать учетную запись, которая будет использована для этой цели;
- выбрать методы аутентификации, которые могут быть использованы для доступа на Web -сервер.
О методах аутентификации необходимо рассказать подробнее:
- IntegratedWindowsAuthentification — единственный метод (кроме анонимного доступа), доступный по умолчанию. При использовании этого метода используются те же хэши NTLM (или Kerberos — negotiate для Windows 2000/ XP /2003), что и при обычной аутентификации в Windows (например, при обращении к файлам на файл-сервере). Конечно, ни один броузер, кроме Internet Explorer , такой аутентификации не поддерживает. Необходимо отметить, что, если прав учетной записи IUSR недостаточно (или анонимный доступ вообще отключен) следующее, что делает Internet Explorer — отсылает NTLM -хэш (его версия зависит от версии операционной системы) текущей учетной записи на сервер IIS . Если аутентификация не прошла (или прошла, но у учетной записи не оказалось прав на Web -ресурс), то открывается всплывающее окно аутентификации, в котором пользователь имеет возможность ввести данные другой учетной записи;
- DigestAuthentification — сравнительно новая технология (появилась только в Windows 2000/ IIS 5.0), основанная на открытых Интернет-стандартах (алгоритм хэширования MD 5 и RFC 2617). При использовании этого метода аутентификации сервер посылает специальную случайную последовательность символов — nonce — клиенту (для каждого сеанса она будет сгенерирована заново). Клиент принимает эту последовательность, на основе ее и своего пароля генерирует хэш по алгоритму MD 5 и пересылает ее серверу. Сервер, который производит такую же операцию и сравнивает полученные значения. Главной проблемой применения этого метода аутентификации является то, что IIS должен получить доступ к открытым паролям пользователей, которых по умолчанию нет и на контроллерах домена. Таким образом, чтобы этот метод аутентификации заработал, необходимо для учетных записей пользователей установить параметр » Store password using reversible encryption «, что обычно в защищенных сетях недопустимо.
- BasicAuthentification — самый простой тип аутентификации, который поддерживается практически всеми броузерами. При этом имя пользователя и пароль посылаются почти открытым текстом (на самом деле они кодируются, во избежание попадания служебных символов, по алгоритму Base 64). Те менее, конечно, расшифровать эти данные не составит никакого труда — например, при помощи утилиты Base 64 Decoder (она умеет декодировать и некоторые другие форматы) из каталога прочее на компакт-диске. Поскольку передаются таким образом на самом деле имя и пароль учетной записи Windows , то последствия могут оказаться очень серьезными (если в сети запущен сниффер). Безопасно пользоваться этим методом аутентификации можно только при использовании SSL .
- .NETPassportauthentification — возможность использовать для аутентификации централизованную систему . NET Passport от Microsoft . Не совсем понятно, зачем эта возможность помещена на графический интерфейс IIS Manager — использовать эту возможность могут только участники программы . NET Passport , фактически — очень ограниченный круг крупных Web -коммерсантов. Существует и множество других ограничений при использовании .NET Passport .
Есть и другие методы аутентификации, например, при помощи клиентских сертификатов (этот метод сертификации настраивается при помощи Edit в разделе Secure Certifications и о нем будет рассказано ниже), при помощи серверов RADIUS и смарт-карт, но обычно последние два способа используются в составе комплексных решений для очень защищенных Web -сайтов.
Еще несколько слов об служебных учетных записях и группах, имеющих отношение к IIS :
- IUSR _имя_компьютера — об этой учетной записи уже говорилось, она предназначена для обеспечения анонимного доступа на сервер IIS и никаких дополнительных прав ей предоставлять не рекомендуется;
- IWAM_имя_компьютера — еще одна гостевая учетная запись, которой не нужно давать лишние права. От имени этой учетной записи запускаются внешние процессы, порождаемые процессом INETINFO (то есть процессом Web -сервера). Иногда для работы Web 0-приложения этой учетной записи необходимо предоставить дополнительные права, например, на запись в каталог.
- IIS _WPG — эта группа предназначена для предоставления прав в операционной системе приложениям CGI и ASP . NET , работающим на Web -сервере. Если у вас таких приложений нет, выдавать какие-либо разрешения этой группе не нужно.
- ASPNET — как понятно из названия, эта учетная запись используется приложениями ASP . NET , работающими на сервере IIS . Если у вас не используется ASP . NET (не установлена как компонент IIS ), то этой учетной записи не будет. Этой учетной записи нужно предоставлять права, например, если приложению ASP . NET необходимо подключаться к SQL Server .
При помощи группы переключателей IP address and domain name restrictions можно также ограничить доступ к сайту по IP -адресам, целым IP -сетям или именам доменов DNS . Обычно такие возможности используются только в Интранет Web -серверах.
Configure Windows Authentication in ASP.NET Core
Windows Authentication (also known as Negotiate, Kerberos, or NTLM authentication) can be configured for ASP.NET Core apps hosted with IIS, Kestrel, or HTTP.sys.
Windows Authentication (also known as Negotiate, Kerberos, or NTLM authentication) can be configured for ASP.NET Core apps hosted with IIS or HTTP.sys.
Windows Authentication relies on the operating system to authenticate users of ASP.NET Core apps. You can use Windows Authentication when your server runs on a corporate network using Active Directory domain identities or Windows accounts to identify users. Windows Authentication is best suited to intranet environments where users, client apps, and web servers belong to the same Windows domain.
Windows Authentication isn’t supported with HTTP/2. Authentication challenges can be sent on HTTP/2 responses, but the client must downgrade to HTTP/1.1 before authenticating.
Proxy and load balancer scenarios
Windows Authentication is a stateful scenario primarily used in an intranet, where a proxy or load balancer doesn’t usually handle traffic between clients and servers. If a proxy or load balancer is used, Windows Authentication only works if the proxy or load balancer:
- Handles the authentication.
- Passes the user authentication information to the app (for example, in a request header), which acts on the authentication information.
An alternative to Windows Authentication in environments where proxies and load balancers are used is Active Directory Federated Services (ADFS) with OpenID Connect (OIDC).
IIS/IIS Express
Add authentication services by invoking AddAuthentication (Microsoft.AspNetCore.Server.IISIntegration namespace) in Startup.ConfigureServices :
Launch settings (debugger)
Configuration for launch settings only affects the Properties/launchSettings.json file for IIS Express and doesn’t configure IIS for Windows Authentication. Server configuration is explained in the IIS section.
The Web Application template available via Visual Studio or the .NET Core CLI can be configured to support Windows Authentication, which updates the Properties/launchSettings.json file automatically.
New project
- Create a new project.
- Select ASP.NET Core Web Application. Select Next.
- Provide a name in the Project name field. Confirm the Location entry is correct or provide a location for the project. Select Create.
- Select Change under Authentication.
- In the Change Authentication window, select Windows Authentication. Select OK.
- Select Web Application.
- Select Create.
Run the app. The username appears in the rendered app’s user interface.
Existing project
The project’s properties enable Windows Authentication and disable Anonymous Authentication:
- Right-click the project in Solution Explorer and select Properties.
- Select the Debug tab.
- Clear the check box for Enable Anonymous Authentication.
- Select the check box for Enable Windows Authentication.
- Save and close the property page.
Alternatively, the properties can be configured in the iisSettings node of the launchSettings.json file:
New project
Execute the dotnet new command with the webapp argument (ASP.NET Core Web App) and —auth Windows switch:
Existing project
Update the iisSettings node of the launchSettings.json file:
When modifying an existing project, confirm that the project file includes a package reference for the Microsoft.AspNetCore.App metapackage or the Microsoft.AspNetCore.Authentication NuGet package.
IIS uses the ASP.NET Core Module to host ASP.NET Core apps. Windows Authentication is configured for IIS via the web.config file. The following sections show how to:
- Provide a local web.config file that activates Windows Authentication on the server when the app is deployed.
- Use the IIS Manager to configure the web.config file of an ASP.NET Core app that has already been deployed to the server.
If you haven’t already done so, enable IIS to host ASP.NET Core apps. For more information, see Host ASP.NET Core on Windows with IIS.
Enable the IIS Role Service for Windows Authentication. For more information, see Enable Windows Authentication in IIS Role Services (see Step 2).
The ASP.NET Core Module is configured to forward the Windows Authentication token to the app by default. For more information, see ASP.NET Core Module configuration reference: Attributes of the aspNetCore element.
Use either of the following approaches:
Before publishing and deploying the project, add the following web.config file to the project root:
When the project is published by the .NET Core SDK (without the property set to true in the project file), the published web.config file includes the section. For more information on the property, see Host ASP.NET Core on Windows with IIS.
After publishing and deploying the project, perform server-side configuration with the IIS Manager:
- In IIS Manager, select the IIS site under the Sites node of the Connections sidebar.
- Double-click Authentication in the IIS area.
- Select Anonymous Authentication. Select Disable in the Actions sidebar.
- Select Windows Authentication. Select Enable in the Actions sidebar.
The section added to the web.config file by IIS Manager is outside of the app’s section added by the .NET Core SDK when the app is published. Because the section is added outside of the node, the settings are inherited by any sub-apps to the current app. To prevent inheritance, move the added section inside of the section that the .NET Core SDK provided.
When IIS Manager is used to add the IIS configuration, it only affects the app’s web.config file on the server. A subsequent deployment of the app may overwrite the settings on the server if the server’s copy of web.config is replaced by the project’s web.config file. Use either of the following approaches to manage the settings:
- Use IIS Manager to reset the settings in the web.config file after the file is overwritten on deployment.
- Add a web.config file to the app locally with the settings.
Kestrel
The Microsoft.AspNetCore.Authentication.Negotiate NuGet package can be used with Kestrel to support Windows Authentication using Negotiate and Kerberos on Windows, Linux, and macOS.
Credentials can be persisted across requests on a connection. Negotiate authentication must not be used with proxies unless the proxy maintains a 1:1 connection affinity (a persistent connection) with Kestrel.
The Negotiate handler detects if the underlying server supports Windows Authentication natively and if it’s enabled. If the server supports Windows Authentication but it’s disabled, an error is thrown asking you to enable the server implementation. When Windows Authentication is enabled in the server, the Negotiate handler transparently forwards to it.
Add authentication services by invoking AddAuthentication and AddNegotiate in Startup.ConfigureServices :
Add Authentication Middleware by calling UseAuthentication in Startup.Configure :
For more information on middleware, see ASP.NET Core Middleware.
Anonymous requests are allowed. Use ASP.NET Core Authorization to challenge anonymous requests for authentication.
Windows environment configuration
The Microsoft.AspNetCore.Authentication.Negotiate component performs User Mode authentication. Service Principal Names (SPNs) must be added to the user account running the service, not the machine account. Execute setspn -S HTTP/myservername.mydomain.com myuser in an administrative command shell.
Linux and macOS environment configuration
Instructions for joining a Linux or macOS machine to a Windows domain are available in the Connect Azure Data Studio to your SQL Server using Windows authentication — Kerberos article. The instructions create a machine account for the Linux machine on the domain. SPNs must be added to that machine account.
When following the guidance in the Connect Azure Data Studio to your SQL Server using Windows authentication — Kerberos article, replace python-software-properties with python3-software-properties if needed.
Once the Linux or macOS machine is joined to the domain, additional steps are required to provide a keytab file with the SPNs:
- On the domain controller, add new web service SPNs to the machine account:
- setspn -S HTTP/mywebservice.mydomain.com mymachine
- setspn -S HTTP/mywebservice@MYDOMAIN.COM mymachine
- Use ktpass to generate a keytab file:
- ktpass -princ HTTP/mywebservice.mydomain.com@MYDOMAIN.COM -pass myKeyTabFilePassword -mapuser MYDOMAIN\mymachine$ -pType KRB5_NT_PRINCIPAL -out c:\temp\mymachine.HTTP.keytab -crypto AES256-SHA1
- Some fields must be specified in uppercase as indicated.
- Copy the keytab file to the Linux or macOS machine.
- Select the keytab file via an environment variable: export KRB5_KTNAME=/tmp/mymachine.HTTP.keytab
- Invoke klist to show the SPNs currently available for use.
A keytab file contains domain access credentials and must be protected accordingly.
HTTP.sys
HTTP.sys supports Kernel Mode Windows Authentication using Negotiate, NTLM, or Basic authentication.
Add authentication services by invoking AddAuthentication (Microsoft.AspNetCore.Server.HttpSys namespace) in Startup.ConfigureServices :
Configure the app’s web host to use HTTP.sys with Windows Authentication (Program.cs). UseHttpSys is in the Microsoft.AspNetCore.Server.HttpSys namespace.
HTTP.sys delegates to Kernel Mode authentication with the Kerberos authentication protocol. User Mode authentication isn’t supported with Kerberos and HTTP.sys. The machine account must be used to decrypt the Kerberos token/ticket that’s obtained from Active Directory and forwarded by the client to the server to authenticate the user. Register the Service Principal Name (SPN) for the host, not the user of the app.
HTTP.sys isn’t supported on Nano Server version 1709 or later. To use Windows Authentication and HTTP.sys with Nano Server, use a Server Core (microsoft/windowsservercore) container. For more information on Server Core, see What is the Server Core installation option in Windows Server?.
Authorize users
The configuration state of anonymous access determines the way in which the [Authorize] and [AllowAnonymous] attributes are used in the app. The following two sections explain how to handle the disallowed and allowed configuration states of anonymous access.
Disallow anonymous access
When Windows Authentication is enabled and anonymous access is disabled, the [Authorize] and [AllowAnonymous] attributes have no effect. If an IIS site is configured to disallow anonymous access, the request never reaches the app. For this reason, the [AllowAnonymous] attribute isn’t applicable.
Allow anonymous access
When both Windows Authentication and anonymous access are enabled, use the [Authorize] and [AllowAnonymous] attributes. The [Authorize] attribute allows you to secure endpoints of the app which require authentication. The [AllowAnonymous] attribute overrides the [Authorize] attribute in apps that allow anonymous access. For attribute usage details, see Simple authorization in ASP.NET Core.
By default, users who lack authorization to access a page are presented with an empty HTTP 403 response. The StatusCodePages Middleware can be configured to provide users with a better «Access Denied» experience.
Impersonation
ASP.NET Core doesn’t implement impersonation. Apps run with the app’s identity for all requests, using app pool or process identity. If the app should perform an action on behalf of a user, use WindowsIdentity.RunImpersonated in a terminal inline middleware in Startup.Configure . Run a single action in this context and then close the context.
RunImpersonated doesn’t support asynchronous operations and shouldn’t be used for complex scenarios. For example, wrapping entire requests or middleware chains isn’t supported or recommended.