Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

patterns & practices Developer Center

Troubleshooting Security Issues

J.D. Meier, Alex Mackman, Michael Dunner, and Srinath Vasireddy
Microsoft Corporation

Published: November 2002

Last Revised: January 2006

See the "patterns & practices Security Guidance for Applications Index" for links to additional security resources.

See the Landing Page for the starting point and a complete overview of Building Secure ASP.NET Applications.

Summary: This section presents a set of troubleshooting tips, techniques and tools to help diagnose security related issues. (19 printed pages)


Process for Troubleshooting
Troubleshooting Authentication Issues
Troubleshooting Authorization Issues
Determining Identity
.NET Remoting
Auditing and Logging
Troubleshooting Tools

Process for Troubleshooting

The following approach has proven to be helpful for resolving security and security context related issues.

  1. Start by describing the problem very clearly. Make sure you know precisely what is supposed to happen, what is actually happening, and most importantly, the detailed steps required to reproduce the problem.

  2. Isolate the problem as accurately as you can. Try to determine at which stage during the processing of a request the problem occurs. Is it a client or server related issue? Does it appear to be a configuration or code related error? Try to isolate the problem by stripping away application layers. For example, consider building a simple console-based test client application to take the place of more complex client applications.

  3. Analyze error messages and stack traces (if they are available). Always start by consulting the Windows event and security logs.

  4. Check the Microsoft Knowledge Base to see if the problem has been documented as a Knowledge Base article.

  5. Many security problems relate to the identity used to run code; these are not always the identities you imagine are running the code. Use the code samples presented in the Determining Identity subsection of the "ASP.NET" section in this chapter to retrieve and diagnose identity information. If the identities appear incorrect, check the configuration settings in Web.config and machine.config and also check the IIS authentication settings for your application's virtual directory. Factors that can affect identity within an ASP.NET Web application include:

    • The <processModel> element in machine.config used to determine the process identity of the ASP.NET worker process (aspnet_wp.exe)

    Note With IIS 6.0 running on Windows Server 2003 in process isolation mode, the application pool identity is used to determine the process identity instead of the process model setting. By default, this identity is Network Service, which is the least privileged account.

    • Authentication settings in IIS
    • Authentication settings in Web.config
    • Impersonation settings in Web.config
  6. Even if it appears that the correct settings are being used and displayed, you may want to explicitly configure a Web.config file for your application (in the application's virtual directory) to make sure it is not inheriting settings from a higher-level application (perhaps from a Web.config in a higher-level virtual directory) or from machine.config.

  7. Use some of the troubleshooting tools listed in the Troubleshooting Tools section later in this chapter to capture additional diagnostics.

  8. Attempt to reproduce the problem on another computer. This can help isolate environmental-related problems and can indicate whether or not the problem is in your application's code or configuration.

  9. If your application is having problems accessing a remote resource, you may be running into impersonation/delegation related problems. Identify the security context being used for the remote resource access, and if you are using Windows authentication, verify that the account providing the context (for example, a process account), should be able to be authenticated by the remote computer.

  10. Search newsgroups to see if the problem has already been reported. If not, post the problem to the newsgroup to see if anyone within the development community can provide assistance.

    The online newsgroup for ASP.NET is located at:

  11. Call the Microsoft Support Center. For details, see the Microsoft Knowledge Base.

Searching for Implementation Solutions

If you have a specific issue and need to understand the best way to tackle the problem, use the following approach.

  • Search in Chapters 5, 6, and 7 of this guide for your scenario or a similar scenarios.
  • Consult the MSDN library documentation and samples.
  • Refer to one of the many ASP.NET information Web sites, such as:
  • Search the Microsoft Knowledge Base for an appropriate How To article.
  • Post questions to newsgroups.
  • Call the Microsoft Support Center.

Troubleshooting Authentication Issues

The first step when troubleshooting authentication issues is to distinguish between IIS and ASP.NET authentication failure messages.

  • If you are receiving an IIS error message you will not see an ASP.NET error code. Check the IIS authentication settings for your application's virtual directory.

    Create a simple HTML test page to remove ASP.NET from the solution.

  • If you are receiving an ASP.NET error message, review the ASP.NET authentication settings within your application's Web.config file.

IIS Authentication Issues

Because the authentication process starts with IIS, make sure IIS is configured correctly.

  • Make sure a user is being authenticated. Consider enabling just Basic authentication and manually log in to ensure you know what principal is being authenticated. Log in with a user name of the form "domain\username".

  • Restart IIS to ensure log on sessions aren't being cached. (Run IISReset.exe to restart IIS.)

  • Close your browser between successive tests to ensure the browser isn't caching credentials.

  • If you are using Integrated Windows authentication, check browser settings as described below.

    • Click Tools from the InternetOptions menu and then click the Advanced tab. Select Enable Integrated Windows Authentication (requires restart). Then restart the browser.
    • Click Tools from the InternetOptions menu, and then click the Security tab. Select the appropriate Web content zone and click CustomLevel. Within UserAuthentication ensure the Logon setting is set correctly for your application. You may want to select Prompt for user name and password to ensure that for each test you are providing explicit credentials and that nothing is being cached.
    • If the browser prompts you for credentials, this could mean you are currently logged into a domain that the server doesn't recognize (for example, you may be logged in as administrator on the local machine).
    • When you browse to an application on your local computer, your interactive logon token is used, as you are interactively logged onto the Web server.
  • Test with a simple Web page that displays security context information. A sample page is provided later in this chapter.

    If this fails, enable auditing on the requested file and check the Security event log. You must also enable auditing using Group Policy (through either the Local Security Policy tool, or the Domain Security Policy tool). Examine the log for invalid usernames or invalid object access attempts.

    • If your Web application is having problems accessing a remote resource, enable auditing on the remote resource.
    • An invalid username and/or password usually means that the account used to run ASP.NET on your Web server is failing to be correctly authenticated at the remote computer. If you are attempting to access remote resources with the default ASP.NET process identity account, check that you have duplicated the account (and password) on the remote computer.

    Note With IIS 6.0 running on Windows Server 2003, the default ASP.NET process identity has domainName\MachineName$ network credentials and can be used to configure access to remote resources.

    • If you see an error message that indicates that the login has failed for NT AUTHORITY\ANONYMOUS, this indicates that the identity on the Web server does not have any network credentials and is attempting to access the remote computer.

      Identify which account is being used by the Web application for remote resource access and confirm that it has network credentials. If the Web application is impersonating, this requires either Kerberos delegation (with suitably configured accounts) or Basic authentication at the Web server.

Using Windows Authentication

If the <authentication> element in your application's Web.config is configured for Windows authentication, use the following code in your Web application to check whether anonymous access is being used (and the authenticated user is the anonymous Internet user account [IUSR_MACHINE]).

WindowsIdentity winId = HttpContext.Current.User.Identity as WindowsIdentity;
if (null != winId)

Using Forms Authentication

Make sure that the cookie name specified in the <forms> element is being retrieved in the global.asax event handler correctly (Application_AuthenticateRequest). Also, make sure the cookie is being created. If the client is continuously sent back to the login page (specified by the loginUrl attribute on the <forms> element) this indicates that the cookie is not being created for some reason, or an authenticated identity is not being placed into the context (HttpContext.User)

Note In ASP.NET 2.0, the Membership feature encapsulates the above functionality. For more information, see "How To: Use Membership in ASP.NET 2.0."

Kerberos Troubleshooting

Use the following tools to help troubleshoot Kerberos-related authentication and delegation issues.

  • Kerbtray.exe. This utility can be used to view the Kerberos tickets in the cache on the current computer. It is part of the Windows 2000 Resource Kit and can be downloaded from the Microsoft Download Center. Search for "Kerbtray.exe".
  • Klist.exe. This is a command line tool similar to Kerbtray, but it also allows you to view and delete Kerberos tickets. Once again, it is part of the Windows 2000 Resource Kit and can be downloaded from the Microsoft Download Center. Search for "Klist.exe"
  • Setspn.exe. This is a command-line tool that allows you to manage the Service Principal Names (SPN) directory property for an Active Directory service account. SPNs are used to locate a target principal name for running a service. It is part of the Windows 2000 Resource Kit and can be downloaded from the Microsoft Download Center. Search for "setspn.exe".

Troubleshooting Authorization Issues

Check Windows ACLs

If your application is having problems accessing a file or registry key (or any securable Windows object protected with ACLs), check the ACLs to ensure that the Web application identity has at least read access.

Check Identity

Also make sure you know which identity is being used for resource access by the ASP.NET Web application. This is likely to be:

  • The ASP.NET process identity (as configured on the <processModel> element in Web.config.

    This defaults to the local ASPNET account specified with the username "machine" and password "AutoGenerate".

    Note With IIS 6.0 running on Windows Server 2003 in process isolation mode, the application pool identity is used to determine the process identity instead of the process model setting. By default, this identity is Network Service, which is the least privileged account.

  • The authenticated caller's identity (if impersonation is enabled within Web.config) as shown below.

    <identity impersonate="true" />

    If you have not disabled anonymous access in IIS, this will be IUSR_MACHINE.

  • A specified impersonation identity as shown below (although this is not recommended).

    <identity impersonate="true" userName="Bob" password="password" />

More information

For more information about the identity used to run ASP.NET and the identity used to access local and network resources, see Chapter 8, ASP.NET Security.

Check the <authorization> Element

Confirm that the <allow> and <deny> elements are configured correctly.

  • If you have <denyusers="?" /> and you are using Forms authentication and/or IIS anonymous authentication, you must explicitly place an IPrincipal object into HttpContext.User or you will receive an access denied 401 response.

  • Make sure the authenticated user is in the roles specified in <allow> and <deny> elements.

    Note When using roles in ASP.NET 2.0, make sure that the correct role provider is configured, and that the defaultProvider is set correctly in the roleManager element. For more information, see "How To: Use Role Manager in ASP.NET 2.0."


Enable Tracing

ASP.NET provides quick and simple tracing to show the execution of events within a page and the values of common variables. This can be a very effective diagnostic aid. Use the page level Trace directive to turn on tracing, as shown below:

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="Test.WebForm1" Trace="true" %>

More information

For more information on the new tracing feature in ASP.NET see the Knowledge Base article Q306731, INFO: New Tracing Feature in ASP.NET.

Configuration Settings

Most application settings should be placed in Web.config. The following list shows main security related settings that can be placed in Web.config.


The following setting which controls the identity used to run the ASP.NET worker process (aspnet_wp.exe) must be located in machine.config.


Note With IIS 6.0 running on Windows Server 2003 in process isolation mode, the application pool identity is used to determine the process identity instead of the process model setting. By default, this identity is Network Service, which is a least privileged account.

Configuration settings for an application are always retrieved from the application's Web.config file first and these override any equivalent settings within the machine.config file. If you want a particular setting to be applied to your application, explicitly configure the setting in the application's Web.config file.

The main (and often only) Web.config file for a particular application lives in its virtual directory root. Subdirectories can also contain Web.config files. Settings in these files override the settings from Web.config files in parent directories.

Determining Identity

Many security and access-denied problems relate to the identity used for resource access. The following code samples presented in this section can be used to help determine identity in Web pages, COM objects, and Web services.

For more information about .NET identity variables, see ASP.NET Identity Matrix in the Reference section of this guide.

Determining Identity in a Web Page

The following script can be used to gather security context-related information and indicates the identity being used to run a Web page.

To use this code, copy and paste it to create a file with a .aspx file extension. Copy the file to an IIS virtual directory and view the page from a browser.

<%@ Page language="c#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Threading" %>
<%@ Import Namespace="System.Security.Principal" %>
    <form id="WhoAmI" method="post" >
      <TABLE id=contextTable border=1>
          <TD align=middle colSpan=3 rowSpan="">
          <TD><asp:Label ID="contextName" Runat=server /></TD>
          <TD><asp:Label ID="contextIsAuth" Runat=server /></TD>
          <TD><asp:Label ID="contextAuthType" Runat=server /></TD>

      <TABLE id=windowsIdentityTable border=1>
          <TD align=middle colSpan=3 rowSpan="">WindowsIdentity.GetCurrent()</TD>
          <TD><asp:Label ID="windowsName" Runat=server /></TD>
          <TD><asp:Label ID="windowsIsAuth" Runat=server /></TD>
          <TD><asp:Label ID="windowsAuthType" Runat=server /></TD>

      <TABLE id=threadIdentityTable border=1>
          <TD align=middle colSpan=3 
          <TD><asp:Label ID="threadName" Runat=server /></TD>
          <TD><asp:Label ID="threadIsAuthenticated" Runat=server /></TD>
          <TD><asp:Label ID="threadAuthenticationType" Runat=server /></TD>
<script runat=server>
  void Page_Load(Object sender, EventArgs e)
    IIdentity id = HttpContext.Current.User.Identity;
    if(null != id)
      contextName.Text = id.Name;
      contextIsAuth.Text = id.IsAuthenticated.ToString();
      contextAuthType.Text = id.AuthenticationType;
    id = Thread.CurrentPrincipal.Identity;
    if(null != id)
      threadName.Text = id.Name;
      threadIsAuthenticated.Text = id.IsAuthenticated.ToString();
      threadAuthenticationType.Text = id.AuthenticationType;
    id = WindowsIdentity.GetCurrent();
    windowsName.Text = id.Name;
    windowsIsAuth.Text = id.IsAuthenticated.ToString();
    windowsAuthType.Text = id.AuthenticationType;

Determining Identity in a Web service

The following code can be used within a Web service to obtain identity information.

public string GetDotNetThreadIdentity()
  return Thread.CurrentPrincipal.Identity.Name;
public string GetWindowsThreadIdentity()
  return WindowsIdentity.GetCurrent().Name;
public string GetUserIdentity()
  return User.Identity.Name;
public string GetHttpContextUserIdentity()
  return HttpContext.Current.User.Identity.Name;

More information

Determining Identity in a Visual Basic 6 COM Object

The following method can be used to return the identity of a Visual Basic® 6 COM object. You can call Visual Basic 6.0 COM objects directly from ASP.NET applications through COM interop. The following method can be helpful when you need to troubleshoot access denied errors from your component when it attempts to access resources.

Private Declare Function GetUserName Lib "advapi32.dll" _
        Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

Public Function WhoAmI()
   Dim sBuff    As String
   Dim lConst   As Long
   Dim lRet     As Long
   Dim sName    As String

   lConst = 199
   sBuff = Space$(200)
   lRet = GetUserName(sBuff, lConst)
   WhoAmI = Trim$(Left$(sBuff, lConst))
End Function 

.NET Remoting

If a remote object is hosted in ASP.NET, and is configured for Windows authentication, you must specify the credentials to be used for authentication through the credentials property of the channel. If you do not explicitly set credentials, the remote object is called without any credentials. If Windows authentication is required, this will result in an HTTP status 401, access denied response.

To use the credentials associated with the current thread impersonation token (if the client thread is impersonating), or the process token (with no impersonation), use default credentials. This can be configured in the client-side configuration file using the following setting:

<channel ref="http" useDefaultCredentials="true" />

If an ASP.NET Web application calls a remote component and the Web application is configured for impersonation, the Web application must be using Kerberos or Basic authentication. All other authentication types can not be used in delegation scenarios.

If the Web application is not configured for impersonation, the process identity of the ASP.NET worker process is used.

Note Ensure the process in running under an account that can be authenticated by the remote computer.

More Information

For more information about setting client-side credentials when calling remote components, see Chapter 11, .NET Remoting Security.


To troubleshoot SSL related problems:

  • Confirm whether you can telnet to port 443 on the IP addresses of the client and server computer. If you cannot, this usually signifies that the sspifilt.dll is not loaded, or is the wrong version, or perhaps conflicts with other ISAPI extensions.

  • Examine the certificate. If you can telnet to 443, check the certificates attribute using the browser's ViewCertificate dialog box. Check the certificate's effective and expiration dates, whether the common name is correct, and also what the Authority Information Access (AIA) or Certificate Revocation List (CRL) distribution point is.

    Confirm that you can browse directory to those AIA/CRL points successfully.

  • If you are using a custom client application (and not a Web browser) to access an SSL-enabled Web site that requires client certificates, check that the client certificate is located in the correct store that the client application accesses.

    When you use a browser, the certificate must be in the interactive user's user store. Services or custom applications may load the client certificate from the machine store or a store associated with a service account's profile. Use the Services MMC snap-in (available when Certificate Services is installed), from the Administrative Tools program group to examine the contents of certificate stores.

More Information

See the following SSL related Knowledge Base articles.


The following articles in the Knowledge Base provides steps for troubleshooting IPSec issues.

Auditing and Logging

Windows Security Logs

Consult the Windows event and security logs early on in the problem diagnostic process.

More information

For more information on how to enable auditing and monitoring events, see the Knowledge Base and article Q300958, HOW TO: Monitor for Unauthorized User Access in Windows 2000.

SQL Server Auditing

By default, logon auditing is disabled. You can configure this either through SQL Server™ Enterprise Manager or by changing the registry.

SQL Server log files are by default located in the following directory. They are text-based and can be read with any text editor such as Notepad.

C:\Program Files\Microsoft SQL Server\MSSQL\LOG 

To enable logon auditing with Enterprise Manager

  1. Start Enterprise Manager.
  2. Select the required SQL Server in the left hand tree control, right-click and then click Properties.
  3. Click the Security tab.
  4. Select the relevant Audit level—Failure, Success or All.

To enable logon auditing using a registry setting

  1. Create the following AuditLevel key within the registry and set its value to one of the REG_DWORD values specified below.

  2. Set the value of this key to one of the following numeric values, which allow you to capture the relevant level of detail.

    3—captures both success and failed login attempts.

    2—captures only failed login attempts.

    1—captures only success login attempts.

    0—captures no logins.

It is recommended that you turn on failed login auditing as this is a way to determine if someone is attempting a brute force attack into SQL Server. The performance impacts of logging failed audit attempts are minimal unless you are being attacked, in which case you need to know anyway.

You can also set audit levels by using script against the SQL Server DMO (Database Management Objects), as shown in the following code fragment.

Sub SetAuditLevel(Server As String, NewAuditLevel As SQLDMO_AUDIT_TYPE)
    Dim objServer As New SQLServer2
    objServer.LoginSecure = True  'Use integrated security
    objServer.Connect Server      'Connect to the target SQL Server    
    'Set the audit level
    objServer.IntegratedSecurity.AuditLevel = NewAuditLevel
    Set objServer = Nothing
End Sub

From SQL Server Books online, the members of the enumerated type, SQLDMO_AUDIT_TYPE are:

SQLDMOAudit_All     3 Log all authentication attempts - success or failure 
SQLDMOAudit_Failure 2 Log failed authentication 
SQLDMOAudit_None    0 Do not log authentication attempts 
SQLDMOAudit_Success 1 Log successful authentication

Sample log entries

The following list shows some sample log entries for successful and failed entries in the SQL Server logs.

Successful login using Integrated Windows authentication:

2002-07-06 22:54:32.42 logon     Login succeeded for user 
'SOMEDOMAIN\Bob'. Connection: Trusted.

Successful login using SQL standard authentication:

2002-07-06 23:13:57.04 logon     Login succeeded for user 
'SOMEDOMAIN\Bob'. Connection: Non-Trusted.

Failed login:

2002-07-06 23:21:15.35 logon     Login failed for user 

IIS Logging

IIS logging can be set to different formats. If you use W3C Extended Logging, then you can take advantage of some additional information. For example, you can turn on Time Taken to log how long a page takes to be served. This can be helpful for isolating slow pages on your production Web site. You can also enable URI Query which will log Query String parameters, which can be helpful for troubleshooting GET operations against your Web pages. The figure below shows the Extended Properties dialog box for IIS logging.


Figure 13.1. IIS extended logging properties

Troubleshooting Tools

The list of tools presented in this section can prove invaluable and will help you diagnose both security and non-security related problems.

File Monitor (FileMon.exe)

This tool allows you to monitor files and folders for access attempts. It is extremely useful to deal with file access permission issues. It is available from

More information

For more information see the Knowledge Base article Q286198, HOWTO: Track 'Permission Denied' Errors on DLL Files.

Fusion Log Viewer (Fuslogvw.exe)

Fusion Log Viewer is provided with the .NET Framework SDK. This utility can be used to display details of failed assembly binds so that users can diagnose why the .NET Framework cannot locate an assembly at run time. (See the .NET Framework documentation for more information.)

To create Fusion logs for ASP.NET, you need to provide a log path in the registry and you need to enable the log failures option through the Fusion Log Viewer utility.

To provide a log path for your log files, use regedit.exe and add a directory location, such as e:\MyLogs, to the following registry key:



ISQL can be used to test SQL from a command prompt. This can be helpful when you want to efficiently test different logins for different users. You run ISQL by typing isql.exe at a command prompt on a computer with SQL Server installed.

Connecting by using SQL authentication

You can pass a user name by using the -U switch and you can optionally specify the password with the -P switch. If you don't specify a password, ISQL will prompt you for one. The following command, issued from a Windows command prompt, results in a password prompt. The advantage of this approach (rather than using the -P switch) is that the password doesn't appear on screen.

C:\ >isql -S YourServer -d pubs -U YourUser

Connecting by using Windows authentication

You can use the -E switch to use a trusted connection which uses the security context of the current interactively logged on user.

C:\ >isql -S YourServer -d pubs -E

Running a simple query

Once you are logged in, you can run a simple query, such as the one shown below.

1> use pubs
2> SELECT au_lname, au_fname FROM authors
3> go

To quit ISQL, type quit at the command prompt.

Windows Task Manager

Windows Task Manager on Windows XP and Windows Server 2003 allows you to display the identity being used to run a process.

To view the identity under which a process is running

  1. Start Task Manager.
  2. Click the Processes tab.
  3. From the View menu, click SelectColumns.
  4. Select UserName, and click OK.

The user name (process identity) is now displayed.

Network Monitor (NetMon.exe)

NetMon is used to capture and monitor network traffic.

More information

See the following Knowledge Base articles:

There are a couple of additional tools to capture the network trace when the client and the server are on the same machine (this can't be done with Netmon):

  • tcptrace.exe. Available from This is particularly useful for Web services since you can set it up to record and show traffic while your application runs. You can switch to Basic authentication and use tcptrace to see what credentials are being sent to the Web service.
  • packetmon.exe. Available from This is a cut down version of Network Monitor, but much easier to configure.

Registry Monitor (regmon.exe)

This tool allows you to monitor registry access. It can be used to show read accesses and updates either from all processes or from a specified set of processes. This tool is very useful when you need to troubleshoot registry permission issues. It is available from


This tool is useful for troubleshooting connectivity issues between IIS and Web clients. In this scenario, you may need to view data that is not displayed in the Web browser, such as the HTTP headers that are included in the request and response packets.

More information

For more information about this tool and the download, see the Knowledge Base article Q284285, How to Use Wfetch.exe to Troubleshoot HTTP Connections.

Visual Studio .NET Tools

The Microsoft .NET Framework SDK security tools can be found at the .NET Framework Tools Web site.

More information

See the following Knowledge Base articles:


This tool can be used as a generic client to test the functionality of your Web service. It captures and displays the SOAP response and request packets.

You can download the tool from the Web Service Tools page at

Windows 2000 Resource Kits

Windows 2000 Resource Kits

Windows 2000 Resource Kit Free Tool Downloads

patterns & practices Developer Center

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

© Microsoft Corporation. All rights reserved.