In this post, I share what I have learned about integrated windows authentication and how to enable it in a web application which consists of an angular front-end and ASP.NET core 3 backend.
What is integrated windows authentication?
Let me explain by giving an example. At work, my computer is joined to a domain controller, which is basically a server that runs active directory. Joining a domain controller means the domain controller manages my credentials, not my computer. When I login using my windows credentials, my computer communicates with the domain controller to validate my credentials and allow access. We have .NET applications running on IIS on a set of servers that are joined to the domain controller. IIS can check against the domain controller to ensure I have authenticated before granting access. Furthermore, it can work with the browser do so seamlessly without requiring me to enter my credentials because it has built in integrated windows authentication. This is possible because both the server on which IIS runs and the browser on my machine are joined to a same domain controller, and the browser supports the Negotiate authentication scheme. From the document, this is an advantage of integrated windows authentication.
Built into IIS. – Does not send the user credentials in the request. – If the client computer belongs to the domain (for example, intranet application), the user does not need to enter credentials
Integrated Windows Authentication
Hopefully, you now have some ideas about integrated windows authentication. Next, let’s look at how it works.
How does integrated windows authentication work?
Per the document, integrated windows authentication
works with any browser that supports the Negotiate authentication scheme, which includes most major browsers.
Integrated Windows Authentication
The Negotiate authentication scheme is Microsoft’s authentication mechanism which uses Kerberos which is a system that validates a user’s identity based on shared secrets and provides access by issuing tickets.
Here is how it works.
To access a protected resource, the client must present a valid ticket to the server. To obtain the ticket, the client sends a request to a Key Distribution Center (KDC). The client encrypts the request using the user’s credentials. Upon receiving the encrypted request, the KDC retrieves the user’s password from active directory given the username, and uses the password to decrypt the request. By way of encrypting and decrypting the request using the user’s password which the KDC can get from the database, the KDC can verify the user’s identity without having the client sending over the password. Once the client receives the ticket, which the KDC encrypts using a key that it shares with the resource server, the client sends over the ticket to the resource server, which in turn validates the ticket against the KDC using the shared key. Once all the validations are done, the server returns the resource to the client.
The above is just a high level summary. If you want to learn more about Kerberos and see examples, I suggest you watch this short video, read this blog and IETF article.
Hopefully, you now have some ideas about how integrated windows authentication works, let’s discuss when should you use it.
When should you use integrated windows authentication
As a summarize, you should consider using integrated windows authentication if:
- Both the server and the client machine use Windows and are joined to the same domain controllers.
- The application is for internal use only. Obviously, if it is accessible by the public, it will not work because the client computers may not use Windows and joined to the domain controllers.
- The browser supports Negotiate mechanism (most major browsers supports it).
- The server supports integrated windows authentication. As mentioned in the document, IIS has built in support for integrated windows authentication.
The document mentions integrated windows authentication is susceptible to cross-site request forgery, so just keep this in mind.
Now that you know about integrated windows authentication and how it works, let’s look at how you can implement it in your ASP.NET core application.
In my case, it turns out to be not difficult to configure my application and IIS to use integrated windows authentication. I just have to make a few changes in the app, and enable Windows authentication in IIS.
Changes in applicationhost.config
Set <WindowsAuthentication
> to true in applicationhost.config, which is under .vs -> {PROJECT_NAME} -> config directory. The .vs directory is hidden by default, so I enabled the option to show the hidden folders.
<windowsAuthentication enabled="true"> <providers> <add value="Negotiate" /> <add value="NTLM" /> </providers> </windowsAuthentication>
See this link for instructions on how to view hidden folder in Windows 10.
Changes in launchSettings.json
In launchSettings.json, which is under Properties folder of the ASP.NET core project, enable WindowsAuthentication under iisSettings:
{ "iisSettings": { "windowsAuthentication": true, "anonymousAuthentication": false, "iisExpress": { "applicationUrl": "http://localhost:61863/", "sslPort": 44378 } } }
Changes in Startup.cs file
- In
Configure(...)
method, add these middlewares:
app.UseAuthentication(); app.UseAuthorization();
Since the app is an ASP.NET core 3 app, per the document, I put the above middlewares between app.UseRouting()
and app.UseEndpoints()
.
If the app uses authentication/authorization features such as
AuthorizePage
or[Authorize]
, place the call toUseAuthentication
andUseAuthorization
: after,UseRouting
andUseCors
, but beforeUseEndpoints
:Migrate from ASP.NET Core 2.2 to 3.0
If you want to learn more, checkout this post on StackOverflow.
In ConfigureServices()
method, I added the following:
services.AddAuthentication(IISDefaults.AuthenticationScheme); services.AddAuthorization();
Changes on IIS site on remote server
- In IIS Manager, under Features View of the site, double-click on Authentication feature.
- Select Windows Authentication and set Status to Enabled.
Changes in angular app
Technically, you don’t need to make any changes in angular for integrated windows authentication to work. Some tutorials online I looked at suggest to add to the header the key and value: withCredentials: true
. However, I realized that this is not necessary, and the authentication still work even after I removed the codes.It appears the browser automatically handles the process by the Negotiate authentication scheme.
Optional: Get windows user’s info in angular
It seems as if there is not a way to get info about the windows user from the client app. Therefore, to get the username and status of the windows user, I make the call to the backend.
- In the asp.net core app, I added the following endpoint to return info about the authenticated user.
[Route("GetAuthenticatedUser")] [HttpGet("[action]")] public IdentityUser GetUser() { return new IdentityUser() { Username = User.Identity?.Name, IsAuthenticated = User.Identity != null ? User.Identity.IsAuthenticated : false, AuthenticationType = User.Identity?.AuthenticationType }; } public class IdentityUser { public string Username { get; set; } public bool IsAuthenticated { get; set; } public string AuthenticationType { get; set; } }
- In angular, I added a guard to load the user’s info and validate the user has access before activating the route.
@Injectable() export class AuthGuardService implements CanActivate { constructor(public router: Router, private apiService: ApiService) { } canActivate(): Observable<boolean> | Promise<boolean> | boolean { return this.apiService.User.pipe( take(1), switchMap(currentUser => { if (!currentUser) { return this.apiService.loadUser().pipe( take(1), switchMap(user => { return of(user && user.isAuthenticated); }), catchError((err: HttpErrorResponse) => { if (err) { console.error("Failed to load user: " + JSON.stringify(err)); if (err.status === 403) { this.apiService.setErrorMessage("You don't have access to use this application."); } else { this.apiService.setErrorMessage("Something went wrong! :("); } } return of(false); })); } return of(currentUser.isAuthenticated); })); } }
References
Integrated Windows Authentication
Enable Windows Authentication In Web API And Angular App
What is the difference between Negotiate and NTLM authentication?
Kerberos – authentication protocol
SPNEGO-based Kerberos and NTLM HTTP Authentication in Microsoft Windows
How to enable Windows authentication for a Web site, Web application, or Web service
Agenda
- What is Authentication and Authorization?
- Understanding Windows Authentication
- Types of Windows Authentication
- Programmatic Authentication
- Impersonation
Authentication and Authorization
In simple words, Authentication is the process that addresses the question «Who are you?«. Authentication is done by obtaining a valid username and password on an internet or intranet system. Once a user is authenticated, the system confirms that you match the identity of whoever you claim to be. However, authentication doesn’t confirm whether you are authorized to access the resource that you might be trying to access; that is done by Authorization.
Authorization addresses the question «What Can You Do?» and this happens after successful authentication. Authorization is the process of verifying that a user is allowed to access a requested resource. This process determines whether an authenticated user is permitted access to any part of an application, access to specific points of an application, or access only to specified datasets that the application provides. After all, how can you determine whether someone is allowed to do something if you don’t recognize that person’s identity.
Windows Authentication Overview
Form Authentication is a wonderful approach, if you are implementing your own authentication process using a back-end database and a custom page. But if you are creating a web application for a limited number of users who are already part of a network domain then Windows Authentication is beneficial and the preferred choice for authentication.
Windows-based authentication is manipulated between the Windows server and the client machine.
The ASP.NET applications reside in Internet Information Server (IIS). Any user’s web request goes directly to the IIS server and it provides the authentication process in a Windows-based authentication model. This type of authentication is quite useful in an intranet environment in which users are asked to log into a network.
In this scenario, you can utilize the credentials that are already in place for the authentication and authorization process. This authentication is done by IIS. It first accepts user’s credentials from the domain login «DomainUserName and Password». If this process fails then IIS displays an error and asks to re-enter the login information.
The following are the advantages of Windows Authentication:
- It relies on and allows the user to use existing Windows Accounts.
- Establishes the foundation for a Uniform Authentication model for multiple types of applications.
- For developers it is easy to implement.
The following are the disadvantages of Windows Authentication:
- Applicable to Microsoft platforms only.
- No custom control over this platform provided authentication process.
To set up your ASP.NET application to work with Windows-based authentication, begin by creating some users and groups. Within your Windows operating system, go to «Control Panel» -> «User Accounts» -> «Manage another account» -> «Create a new account» then choose «Add or Remove User». Then create an account «Test» as in the following screenshot.
Figure 1.1: New User Creation
Types of Windows Authentication
During implementation of Windows Authentication, typically IIS proposes a range of possible authentication strategies to authenticate each request it receives as in the following:
- Basic Authentication
- Digest Authentication
- Integrated Windows Authentication
- UNC Authentication
- Anonymous Authentication
Before you proceed with implementing and using Windows Authentication, let’s verify the prerequisites, in other words the IIS configuration. You can confirm whether IIS is already installed by typing in the address http://localhost (or http://127.0.0.1) in the browser. The following page was displayed in the browser and ensures that IIS is configured:
Figure 1.2 IIS Page
If the page shown above is not displayed then you don’t have IIS configured. In such a situation you need to manually turn on IIS from the Windows Feature List. Here, you just enable the Internet Information Services option as shown in the following screenshot, Figure 1.3.
Figure 1.3: Windows Features
This entire process will take some time to configure. Once completed you can open the IIS Manager from Administrative Tools or you can directly open it by running the inetmgr command. The following shows the IIS Manager as it appears when opened:
Figure 1.4 IIS Manager
________________________________________
Note: It is suggested to register the ASP.NET 4.0 version with the IIS 7.0 web server before creating any project via running the command «aspnet_regiis.exe -i».
________________________________________
Basic Authentication
This form of authentication is supported by all browsers. When a website requests client authentication using Basic Authentication, the web browser displays a login dialog box from user name and password as in the following screenshot.
Figure 1.5 IIS Basic Authentication
After a user provides built-in Windows user account information, the data is transmitted to the web server. Once IIS receives the authentication data, it attempts to authenticate the user with the corresponding Windows account. This password is encoded using Base64 and sent to the server. It is important to note that the Base64 encoding is not encryption. So the drawback of this mechanism is that the user name and password are sent in clear text (unencrypted) during communication.
Do It Yourself
In order to see Basic Authentication in action, we will create an ASP.NET website hosted on a local IIS web server. Use the following procedure to create the sample.
- First open the Visual Studio 2010 IDE. Then go to menu «File» -> «New» -> «Website…» and name this website «WinAuthTest».
Figure 1.6 New ASP.NET website
- Ensure that IIS 7.0 is properly configured with registration of ASP.NET 4.0 and other components as explained earlier.
- Open the IIS Manager using the inetmgr command from the Run window.
- You see in the IIS Manager that the website «WinAuthTest» entry is added with its corresponding virtual directory as in the following:
Figure 1.7 IIS
- Now click on «Authentication under IIS» in the dialog box. The following options will appear:
Figure 1.8 Authentications
- It might be possible that the various authentication options above are not displayed because they are turned on by default. So you can configure them manually from Windows Features under Internet Information Services Security options as in the following screenshot;
Figure 1.9 IIS Security options
- Now as shown in the reference Figure 1.8, enable the Basic Authentication and compile the ASP.NET «WinAuthTest» project by pressing F5. Windows will show the Figure 1.5 images.
- Enter the temporarily created Windows account «test» as in Figure 1.1 to proceed. Windows won’t let the website open until you enter the correct user name and password.
Digest Authentication
Digest Authentication, like Basic Authentication, requires the user to provide account information using a login dialog box that is displayed by the browser. Unlike Basic Authentication, the user name and password are not transmitted in clear text. Instead, a cryptographically secure hash with this information is sent. We can implement this authentication by simply enabling this option in IIS as in the following screenshot.
Figure 1.10 Digest Authentications
Digest Authentication involves hashing the user’s password using the MD5 algorithm. Windows is unable to store MD5 hashes of passwords for local accounts (SAM database) thus the limitation of Digest Authentication is that in IIS, it only functions when the virtual directory is being authenticated or controlled by a Windows Active Directory Domain Controller.
Digest Authentication protects users and applications from a variety of malicious attacks by incorporating a piece of information about the request as input to the hashing algorithm.
Enabling and disabling digest authentication can also be done programmatically. We can enable this authentication using the AppCmd command as in the following:
- appcmd.exe set config /section:digestAuthentication /enable:true
Integrated Windows Authentication
Integrated Windows Authentication is the most reasonable mechanism for LAN-WAN-based applications. For this authentication to work properly, both client and server must be on the same network. In fact, integrated authentication does not transmit any credential information. Instead, it coordinates with the domain server where it is logged in and gets that computer to send the authentication information to the server.
It does authentication without any client interactions. When IIS asks the client to authenticate itself, the browser sends a token that represents the Windows account of the current user. Technically, this authentication incorporates two authentication mechanisms, NTLM and Kerberos. Enabling integrated authentication via IIS Manager typically enables support for both of these two mechanisms as in the following screenshot:
Figure 1.11 Integrated Authentications
UNC Authentication
Universal Naming Convention (UNC) authentication allows you to configure IIS to use a specified user account when accessing resources on a remote share. This authentication can be implemented during creation of a virtual directory for a web application. Use the following procedure to configure UNC authentication:
- Open IIS Manager using inetmgr from the «Run» window.
- Locate the website at which you wish to add a new virtual directory. Right-click and choose «Add Virtual Directory».
Figure 1.12 UNC Authentications
- Enter the alias name that the directory should be accessed under and UNC physical path as in the following screenshot.
Figure 1.13 UNC Authentications
- Now click the «Connect as» button and choose the «Application User» radio button and chose a specific user account. Finally click the «Ok» button.
Anonymous Authentication
A remote user is not required to supply credentials to access a file when Anonymous Authentication is enabled. By default, the configured anonymous access account is the IUSR account created when IIS is installed. Anonymous Authentication can be configured from the IIS Manager as in the following screenshot.
Figure 1.15 Anonymous Authentications
It is important to note that if you enable more than one authentication option, the client will use the strongest authentication method as long as anonymous authentication is not enabled. If anonymous authentication is enabled then the client will access the website anonymously. So it is suggested to disable anonymous authentication during more than one authentication implementation.
Programmatic Authentication
You can access some additional information about the currently authenticated user using the WindowsIdentity class. The following code is required to do that:
- using System;
- using System.Configuration;
- using System.Web;
- using System.Web.Security;
- using System.Security.Principal;
- public partial class _Default : System.Web.UI.Page
- {
- protected void Button1_Click(object sender, EventArgs e)
- {
- if (Request.IsAuthenticated)
- {
- lblData.Text = «<b>Name: </b>» + User.Identity.Name;
- if (User is WindowsPrincipal)
- {
- WindowsPrincipal principal = (WindowsPrincipal)User;
- lblData.Text += «<br><b>Power user? </b>»;
- lblData.Text += principal.IsInRole(
- WindowsBuiltInRole.PowerUser).ToString();
- WindowsIdentity identity = principal.Identity as WindowsIdentity;
- lblData.Text += «<br><b>Token: </b>»;
- lblData.Text += identity.Token.ToString();
- lblData.Text += «<br><b>Guest? </b>»;
- lblData.Text += identity.IsGuest.ToString();
- lblData.Text += «<br><b>System? </b>»;
- lblData.Text += identity.IsSystem.ToString();
- }
- }
- }
- }
When you build this program, the following extra Windows-specific information will be displayed:
Figure 1.16 Information
Impersonation
Impersonation is the process under which an application can take the identity of its user to access all the resources the user is authorized for. Instead of using a fixed account for all users, web pages and applications, you can temporarily change the identity that ASP.NET uses for certain tasks.
You may want to access some resources residing on your local system, that requires you to login with valid credentials. Let’s say that you have some files in the location «C:temp». The ACL editor for the folder temp removes all the groups and leaves only the Administrator users and Administrator user groups associated to it as in the following screenshot.
Figure 1.17 ACL
Now create a simple ASP.NET Web Application with a Button and a List box control to access all files that reside in the temp folder as in the following code:
- protected void btnAccessFiles_Click(object sender, EventArgs e)
- {
- String[] xfiels = Directory.GetFiles(@«c:temp»);
- foreach (string a in xfiels)
- {
- ListBox1.Items.Add(a.ToString());
- }
- }
Now configure the application in IIS to use Windows integrated authentication. Finally build the project. When you click the button to access the files in the temp folder, you might see an error indicating that access to «C:temp» is denied. This is because your application is running with an ASP.NET account that will not be allowed access to the «C:temp» folder depending on the ACL.
So we need to make our application run under the Administrator’s identity that can be done by impersonation. We would add the following code to the web.config file to impersonate the Administrator identity:
- <configuration>
- <system.web>
- <identity impersonate =«true» userName =«VidyaVrat» password =«abc123»/>
- </system.web>
- </configuration>
Now build the project again to test the application and it should work fine when you click the button as in the following screenshot:
Figure 1.18 Output
Alternately, you can also configure impersonation using the IIS Manager. Let’s use the preceding example as a reference. When you are done with all the programmatic and other configurations related to impersonation you will see that in IIS Manager the ASP.NET impersonation option is enabled and configured with the impersonation «VidyaVrat» account as in the following;
Figure 1.19 Impersonations
From Wikipedia, the free encyclopedia
Integrated Windows Authentication (IWA)[1]
is a term associated with Microsoft products that refers to the SPNEGO, Kerberos, and NTLMSSP authentication protocols with respect to SSPI functionality introduced with Microsoft Windows 2000 and included with later Windows NT-based operating systems. The term is used more commonly for the automatically authenticated connections between Microsoft Internet Information Services, Internet Explorer, and other Active Directory aware applications.
IWA is also known by several names like HTTP Negotiate authentication, NT Authentication,[2] NTLM Authentication,[3] Domain authentication,[4] Windows Integrated Authentication,[5] Windows NT Challenge/Response authentication,[6] or simply Windows Authentication.
Overview[edit]
Integrated Windows Authentication uses the security features of Windows clients and servers. Unlike Basic Authentication or Digest Authentication, initially, it does not prompt users for a user name and password. The current Windows user information on the client computer is supplied by the web browser through a cryptographic exchange involving hashing with the Web server. If the authentication exchange initially fails to identify the user, the web browser will prompt the user for a Windows user account user name and password.
Integrated Windows Authentication itself is not a standard or an authentication protocol. When IWA is selected as an option of a program (e.g. within the Directory Security tab of the IIS site properties dialog)[7] this implies that underlying security mechanisms should be used in a preferential order. If the Kerberos provider is functional and a Kerberos ticket can be obtained for the target, and any associated settings permit Kerberos authentication to occur (e.g. Intranet sites settings in Internet Explorer), the Kerberos 5 protocol will be attempted. Otherwise NTLMSSP authentication is attempted. Similarly, if Kerberos authentication is attempted, yet it fails, then NTLMSSP is attempted. IWA uses SPNEGO to allow initiators and acceptors to negotiate either Kerberos or NTLMSSP. Third party utilities have extended the Integrated Windows Authentication paradigm to UNIX, Linux and Mac systems.
Supported web browsers[edit]
Integrated Windows Authentication works with most modern web browsers,[8] but does not work over some HTTP proxy servers.[7] Therefore, it is best for use in intranets where all the clients are within a single domain. It may work with other web browsers if they have been configured to pass the user’s logon credentials to the server that is requesting authentication. Where a proxy itself requires NTLM authentication, some applications like Java may not work because the protocol is not described in RFC-2069 for proxy authentication.
- Internet Explorer 2 and later versions.[7]
- In Mozilla Firefox on Windows operating systems, the names of the domains/websites to which the authentication is to be passed can be entered (comma delimited for multiple domains) for the «network.negotiate-auth.trusted-uris» (for Kerberos) or in the «network.automatic-ntlm-auth.trusted-uris» (NTLM) Preference Name on the about:config page.[9] On the Macintosh operating systems this works if you have a kerberos ticket (use negotiate). Some websites may also require configuring the «network.negotiate-auth.delegation-uris«.
- Opera 9.01 and later versions can use NTLM/Negotiate, but will use Basic or Digest authentication if that is offered by the server.
- Google Chrome works as of 8.0.
- Safari works, once you have a Kerberos ticket.
- Microsoft Edge 77 and later.[10]
Supported mobile browsers[edit]
- Bitzer Secure Browser supports Kerberos and NTLM SSO from iOS and Android. Both KINIT and PKINIT are supported.
See also[edit]
- SSPI (Security Support Provider Interface)
- NTLM (NT Lan Manager)
- SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism)
- GSSAPI (Generic Security Services Application Program Interface)
References[edit]
- ^
«Microsoft Security Advisory (974926) — Credential Relaying Attacks on Integrated Windows Authentication». Microsoft Security TechCenter. 2009-12-08. Archived from the original on 2013-06-19. Retrieved 2012-11-16.This advisory addresses […] Integrated Windows Authentication (IWA) […]
- ^
«Q147706: How to disable LM authentication on Windows NT». Microsoft Support. 2006-09-16. Archived from the original on 2012-11-17. Retrieved 2012-11-16.[…] Windows NT supported two kinds of challenge/response authentication: […] LanManager (LM) challenge/response […] Windows NT challenge/response (also known as NTLM challenge/response) […] LM authentication is not as strong as Windows NT authentication […]
- ^
«IIS Authentication». Microsoft MSDN Library. Archived from the original on 2012-11-28. Retrieved 2012-11-16.Integrated Windows authentication (formerly known as NTLM authentication […]) […]
- ^
«NTLM Overview». Microsoft TechNet. 2012-02-29. Archived from the original on 2012-10-31. Retrieved 2012-11-16.When the NTLM protocol is used, a resource server must […] Contact a domain authentication service
- ^
«MSKB258063: Internet Explorer May Prompt You for a Password». Microsoft Corporation. Archived from the original on 2012-10-21. Retrieved 2012-11-16.Windows Integrated authentication, Windows NT Challenge/Response (NTCR), and Windows NT LAN Manager (NTLM) are the same and are used synonymously throughout this article.
- ^
«IIS Authentication». Microsoft MSDN Library. Archived from the original on 2012-11-28. Retrieved 2012-11-16.Integrated Windows authentication (formerly known as […] Windows NT Challenge/Response authentication) […]
- ^ a b c
Microsoft Corporation. «Integrated Windows Authentication (IIS 6.0)». IIS 6.0 Technical Reference. Archived from the original on 2009-08-23. Retrieved 2009-08-30. - ^ «Integrated Windows Authentication — Gino Pipeline — SLAC Confluence».
- ^ «About:config entries». MozillaZine. 27 January 2012. Archived from the original on 2012-03-04. Retrieved 2012-03-02.
- ^ «Microsoft Edge identity support and configuration». Microsoft. 2020-07-15. Retrieved 2020-09-09.
External links[edit]
- Discussion of IWA in Microsoft IIS 6.0 Technical Reference
Integrated Windows Authentication
If your desktop or mobile application runs on Windows, and on a machine connected to a Windows domain — AD or AAD joined — it is possible to use the Integrated Windows Authentication (IWA) to acquire a token silently. No UI is required when using the application.
Use WAM instead
Public client applications should use WAM on Windows. WAM can login the current windows user silently. See https://aka.ms/msal-net-wam
This does not require complex setup and it even works for Personal accounts.
Constraints
-
Federated users only, i.e. those created in an Active Directory and backed by Azure Active Directory. Users created directly in AAD, without AD backing — managed users — cannot use this auth flow. This limitation does not affect the Username/Password flow.
-
Does not work for MSA users. For MSA uses try out WAM
-
IWA is for apps written for .NET Framework, .NET Core and UWP platforms
-
IWA does NOT bypass MFA (multi factor authentication). If MFA is configured, IWA might fail if an MFA challenge is required, because MFA requires user interaction.
This one is tricky. IWA is non-interactive, but 2FA requires user interactivity. You do not control when the identity provider requests 2FA to be performed, the tenant admin does. From our observations, 2FA is required when you login from a different country, when not connected via VPN to a corporate network, and sometimes even when connected via VPN. Don’t expect a deterministic set of rules, Azure Active Directory uses AI to continuously learn if 2FA is required. You should fallback to a user prompt (https://aka.ms/msal-net-interactive) if IWA fails
-
The authority passed in the
PublicClientApplicationBuilder
needs to be:- tenanted (of the form
https://login.microsoftonline.com/{tenant}/
wheretenant
is either the guid representing the tenant ID or a domain associated with the tenant. - for any work and school accounts (
https://login.microsoftonline.com/organizations/
)
Microsoft personal accounts are not supported (you cannot use /common or /consumers tenants)
- tenanted (of the form
-
Because Integrated Windows Authentication is a silent flow:
- the user of your application must have previously consented to use the application
- or the tenant admin must have previously consented to all users in the tenant to use the application.
- This means that:
- either you as a developer have pressed the Grant button on the Azure portal for yourself,
- or a tenant admin has pressed the Grant/revoke admin consent for {tenant domain} button in the API permissions tab of the registration for the application (See Add permissions to access web APIs)
- or you have provided a way for users to consent to the application (See Requesting individual user consent)
- or you have provided a way for the tenant admin to consent for the application (See admin consent)
-
This flow is enabled for .net desktop, .net core and Windows Universal Apps.
For more details on consent see v2.0 permissions and consent
How to use it?
Application registration
During the App registration , in the Authentication section for your application:
-
you don’t need to provide a Reply URI
-
but you need to choose Yes, to the question Treat application as a public client (in the Default client type paragraph)
Code
IPublicClientApplication
contains a method called AcquireTokenByIntegratedWindowsAuth
AcquireTokenByIntegratedWindowsAuth(IEnumerable<string> scopes)
You should normally use only one parameter (scopes
). However depending on the way your Windows administrator has setup the policies, it can be possible that applications on your windows machine are not allowed to lookup the logged-in user. In that case, use a second method .WithUsername()
and pass in the username of the logged in user as a UPN format — joe@contoso.com
.
The following sample presents the most current case, with explanations of the kind of exceptions you can get, and their mitigations
static async Task GetATokenForGraph() { string authority = "https://login.microsoftonline.com/contoso.com"; string[] scopes = new string[] { "user.read" }; IPublicClientApplication app = PublicClientApplicationBuilder .Create(clientId) .WithAuthority(authority) .Build(); var accounts = await app.GetAccountsAsync(); AuthenticationResult result = null; if (accounts.Any()) { result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault()) .ExecuteAsync(); } else { try { result = await app.AcquireTokenByIntegratedWindowsAuth(scopes) .ExecuteAsync(CancellationToken.None); } catch (MsalUiRequiredException ex) { // MsalUiRequiredException: AADSTS65001: The user or administrator has not consented to use the application // with ID '{appId}' named '{appName}'.Send an interactive authorization request for this user and resource. // you need to get user consent first. This can be done, if you are not using .NET Core (which does not have any Web UI) // by doing (once only) an AcquireToken interactive. // If you are using .NET core or don't want to do an AcquireTokenInteractive, you might want to suggest the user to navigate // to a URL to consent: https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id={clientId}&response_type=code&scope=user.read // AADSTS50079: The user is required to use multi-factor authentication. // There is no mitigation - if MFA is configured for your tenant and AAD decides to enforce it, // you need to fallback to an interactive flows such as AcquireTokenInteractive or AcquireTokenByDeviceCode } catch (MsalServiceException ex) { // Kind of errors you could have (in ex.Message) // MsalServiceException: AADSTS90010: The grant type is not supported over the /common or /consumers endpoints. Please use the /organizations or tenant-specific endpoint. // you used common. // Mitigation: as explained in the message from Azure AD, the authoriy needs to be tenanted or otherwise organizations // MsalServiceException: AADSTS70002: The request body must contain the following parameter: 'client_secret or client_assertion'. // Explanation: this can happen if your application was not registered as a public client application in Azure AD // Mitigation: in the Azure portal, edit the manifest for your application and set the `allowPublicClient` to `true` } catch (MsalClientException ex) { // Error Code: unknown_user Message: Could not identify logged in user // Explanation: the library was unable to query the current Windows logged-in user or this user is not AD or AAD // joined (work-place joined users are not supported). // Mitigation 1: on UWP, check that the application has the following capabilities: Enterprise Authentication, // Private Networks (Client and Server), User Account Information // Mitigation 2: Implement your own logic to fetch the username (e.g. john@contoso.com) and use the // AcquireTokenByIntegratedWindowsAuth form that takes in the username // Error Code: integrated_windows_auth_not_supported_managed_user // Explanation: This method relies on an a protocol exposed by Active Directory (AD). If a user was created in Azure // Active Directory without AD backing ("managed" user), this method will fail. Users created in AD and backed by // AAD ("federated" users) can benefit from this non-interactive method of authentication. // Mitigation: Use interactive authentication } } Console.WriteLine(result.Account.Username); }
Note: if you encounter the following error:
«Microsoft.Identity.Client.MsalClientException: Failed to get user name —> System.ComponentModel.Win32Exception: No mapping between account names and security IDs was done»
It means that you may be singed into the device with a local computer account as opposed to an Active Directory(AD) account. Please ensure that the device is added to the domain and that the currently signed in user backed by AD. It is not enough to have a computer joined to a domain alone as local accounts on the device wont be able to access your AD credentials.
Sample illustrating acquiring tokens through Integrated Windows Authentication with MSAL.NET
Sample | Platform | Description |
---|---|---|
active-directory-dotnet-iwa-v2 | Console (.NET) | .NET Core console application letting the user signed-in in Windows, acquire, with the Azure AD v2.0 endpoint, a token for the Microsoft Graph |
Additional information
In case you want to learn more about Integrated Windows Authentication:
- How this was done with the V1 endpoint: AcquireTokenSilent using Integrated authentication on Windows (Kerberos) in ADAL.NET
Troubleshooting
If you encounter the error code «parsing_wstrust_response_failed» It may be due to a number of configuration issues in the ADFS environment.
Some of those issues include:
- An account is not being available to perform IWA
- An IWA policy is preventing auto-IWA authentication
- Proxy or configuration issues prevent NTLM protocol (usually the case for 401 Negotiate/NTLM challenge presented by the endpoint for Windows authentication. You may be able to try using your own HttpClient or changing the current version of .NET to work around this issue).
- In case the Error Message is «Object reference not set to an instance of an object.» enable MSAL logging at Warning level to see more details.
For more information see AD FS Troubleshooting — Integrated Windows Authentication