Меню Рубрики

Windows authentication asp net mvc

Authenticating Users with Windows Authentication (C#)

Learn how to use Windows authentication in the context of an MVC application. You learn how to enable Windows authentication within your application’s web configuration file and how to configure authentication with IIS. Finally, you learn how to use the [Authorize] attribute to restrict access to controller actions to particular Windows users or groups.

The goal of this tutorial is to explain how you can take advantage of the security features built into Internet Information Services to password protect the views in your MVC applications. You learn how to allow controller actions to be invoked only by particular Windows users or users who are members of particular Windows groups.

Using Windows authentication makes sense when you are building an internal company website (an intranet site) and you want your users to be able to use their standard Windows user names and passwords when accessing the website. If you are building an outwards facing website (an Internet website) consider using Forms authentication instead.

Enabling Windows Authentication

When you create a new ASP.NET MVC application, Windows authentication is not enabled by default. Forms authentication is the default authentication type enabled for MVC applications. You must enable Windows authentication by modifying your MVC application’s web configuration (web.config) file. Find the section and modify it to use Windows instead of Forms authentication like this:

When you enable Windows authentication, your web server becomes responsible for authenticating users. Typically, there are two different types of web servers that you use when creating and deploying an ASP.NET MVC application.

First, while developing an MVC application, you use the ASP.NET Development Web Server included with Visual Studio. By default, the ASP.NET Development Web Server executes all pages in the context of the current Windows account (whatever account you used to log into Windows).

The ASP.NET Development Web Server also supports NTLM authentication. You can enable NTLM authentication by right-clicking the name of your project in the Solution Explorer window and selecting Properties. Next, select the Web tab and check the NTLM checkbox (see Figure 1).

Figure 1 – Enabling NTLM authentication for the ASP.NET Development Web Server

For a production web application, on the hand, you use IIS as your web server. IIS supports several types of authentication including:

  • Basic Authentication – Defined as part of the HTTP 1.0 protocol. Sends user names and passwords in clear text (Base64 encoded) across the Internet. — Digest Authentication – Sends a hash of a password, instead of the password itself, across the internet. — Integrated Windows (NTLM) Authentication – The best type of authentication to use in intranet environments using windows. — Certificate Authentication – Enables authentication using a client-side certificate. The certificate maps to a Windows user account.

For a more detailed overview of these different types of authentication, see https://msdn.microsoft.com/library/aa292114(VS.71).aspx.

You can use Internet Information Services Manager to enable a particular type of authentication. Be aware that all types of authentication are not available in the case of every operating system. Furthermore, if you are using IIS 7.0 with Windows Vista, you will need to enable the different types of Windows authentication before they appear in the Internet Information Services Manager. Open Control Panel, Programs, Programs and Features, Turn Windows features on or off, and expand the Internet Information Services node (see Figure 2).

Figure 2 – Enabling Windows IIS features

Using Internet Information Services, you can enable or disable different types of authentication. For example, Figure 3 illustrates disabling anonymous authentication and enabling Integrated Windows (NTLM) authentication when using IIS 7.0.

Figure 3 – Enabling Integrated Windows Authentication

Authorizing Windows Users and Groups

After you enable Windows authentication, you can use the [Authorize] attribute to control access to controllers or controller actions. This attribute can be applied to an entire MVC controller or a particular controller action.

For example, the Home controller in Listing 1 exposes three actions named Index(), CompanySecrets(), and StephenSecrets(). Anyone can invoke the Index() action. However, only members of the Windows local Managers group can invoke the CompanySecrets() action. Finally, only the Windows domain user named Stephen (in the Redmond domain) can invoke the StephenSecrets() action.

Listing 1 – Controllers\HomeController.cs

Because of Windows User Account Control (UAC), when working with Windows Vista or Windows Server 2008, the local Administrators group will behave differently than other groups. The [Authorize] attribute won’t correctly recognize a member of the local Administrators group unless you modify your computer’s UAC settings.

Exactly what happens when you attempt to invoke a controller action without being the right permissions depends on the type of authentication enabled. By default, when using the ASP.NET Development Server, you simply get a blank page. The page is served with a 401 Not Authorized HTTP Response Status.

If, on the other hand, you are using IIS with Anonymous authentication disabled and Basic authentication enabled, then you keep getting a login dialog prompt each time you request the protected page (see Figure 4).

Figure 4 – Basic authentication login dialog

Источник

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

  1. Create a new project.
  2. Select ASP.NET Core Web Application. Select Next.
  3. Provide a name in the Project name field. Confirm the Location entry is correct or provide a location for the project. Select Create.
  4. Select Change under Authentication.
  5. In the Change Authentication window, select Windows Authentication. Select OK.
  6. Select Web Application.
  7. 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:

  1. Right-click the project in Solution Explorer and select Properties.
  2. Select the Debug tab.
  3. Clear the check box for Enable Anonymous Authentication.
  4. Select the check box for Enable Windows Authentication.
  5. 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:

  1. In IIS Manager, select the IIS site under the Sites node of the Connections sidebar.
  2. Double-click Authentication in the IIS area.
  3. Select Anonymous Authentication. Select Disable in the Actions sidebar.
  4. 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 is enabled. If the server supports Windows Authentication but it is 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 authentication requests 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.

Kerberos authentication on Linux or macOS doesn’t provide any role information for an authenticated user. To add role and group information to a Kerberos user, the authentication handler must be configured to retrieve the roles from an LDAP domain. The most basic configuration only specifies an LDAP domain to query against and will use the authenticated user’s context to query the LDAP domain:

Some configurations may require specific credentials to query the LDAP domain. The credentials can be specified in the options:

By default, the negotiate authentication handler resolves nested domains. In a large or complicated LDAP environment, resolving nested domains may result in a slow lookup or a lot of memory being used for each user. Nested domain resolution can be disabled using the IgnoreNestedGroups option.

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.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

  • Windows audio нет в списке служб
  • Windows audio streaming server
  • Windows audio recorder windows 7
  • Windows audio enhancements отключены
  • Windows audio device graph isolation