Home > Articles > Programming > Windows Programming

Like this article? We recommend

Like this article? We recommend

In the pre-.NET era, you didn't have to worry about all the different types of identities and principals. Low-level OS APIs automatically attached a principal token to processes. That token was used along the way to provide authorization; that is, it checked permissions against resources. (Admittedly, this picture is somehow simplified—for example, ignoring impersonation and remote procedure calls.)

In .NET, there are no particular requirements for the assembly code doing "authentication." Almost any piece of code is allowed to set (or change) the authentication token. The authentication token is represented by a Principal object, and it must be set into the Thread.CurrentPrincipal static property.

The .NET runtime has the Principal object, placed into the thread's CurrentPrincipal, flow out of band across method calls and uses it to perform its built-in authorization mechanism (which I'll cover shortly).

You'll probably place a Principal object in the thread's CurrentPrincipal, even when the application doesn't use .NET built-in authorization, in order to take advance of the out-of-band Principal object flow. If your application spawns different threads, you might think that calling CurrentPrincipal is required on each thread. Fortunately, that's not the case. Just call the SetThreadPrincipal method on the current Application Domain object. This method accepts any object implementing the IPrincipal interface. Doing so guarantees that the provided Principal object is copied automatically to all threads created or entering the Application Domain.

There is no automatic hook into Windows authentication in .NET. If you want to use the Windows Identity and Principal objects also as .NET Identity and Principal objects, you must explicitly require it by calling the ApplicationDomain's SetPrincipalPolicy static method:

//this call is typically put in the application's main
AppDomain.CurrentDomain.SetPrincipalPolicy( 
    PrincipalPolicy.WindowsPrincipal);

Other legal values of the PrincipalPolicy enumerator are NoPrincipal and UnAuthenticatedPrincipal. Calling SetPrincipalPolicy using NoPrincipal doesn't set any Principal object into Thread's CurrentPrincipal. If you don't call SetPrincipal Policy or SetThreadPrincipal (that is, if you ignore any security-related stuff at application startup), the .NET Framework calls SetPrincipalPolicy with the UnAuthenticatedPrincipal parameter. This parameter instructs the .NET runtime to put a generic Principal containing a Generic Identity object into the thread's CurrentPrincipal.

For an alternative way to access the WindowsPrincipal and WindowsIdentity objects, you have to call the WindowsIdentity.GetCurrent static method and then pass the obtained WindowsIdentity to the WindowsPrincipal constructor.

WindowsIdentity wi = WindowsIdentity.GetCurrent ();
WindowsPrincipal wp = new WindowsPrincipal (wi);

This option is useful if you don't want to attach the WindowsPrincipal to the current thread.

Custom Authentication

At this point, you have all the information you need to develop a custom authentication mechanism, using the following steps:

  • Check provided credentials against a user store.

  • Create a pair of Identity and Principal objects.

  • Set the Principal object into the Thread.CurrentPrincipal property and eventually on the whole Application Domain.

The authorization code in .NET can be as simple as the following code snippet:

private bool authenticate(string p_uid,string p_pwd) {
 string[] l_roles;
 if (CheckAgainstUserStore(p_uid,p_pwd, out l_roles)==true) {
 MyIdentity l_MyIdentity = new MyIdentity (p_uid);
 MyPrincipal l_MyPrincipal = new MyPrincipal(l_MyIdentity,l_roles );
 //for the current thread
 Thread.CurrentPrincipal = l_MyPrincipal ;
 //for threads which will be created later on 
 AppDomain.CurrentDomain.SetThreadPrincipal (l_MyPrincipal); 
 return true;
 }
 else
 return false;
}

MyPrincipal and MyIdentity are two custom classes; the CheckAgainstUserStore method matches the provided username and passwords against a user account store (file, database, Active Directory, and so on).

NOTE

For better encapsulation, you should move the CheckAgainstUserStore method and the assignment to the CurrentPrincipal right into the MyPrincipal constructor. This call is typically placed in the executable main routine.

Some of you might be thinking: "Hey, wait a minute! Does any piece of code really modify the Thread.CurrentPrincipal? This is not actually what happens when dealing with Windows security. Isn't any particular permission required?"

The answer is yes: You need a particular CAS permission to manipulate the CurrentPrincipal, specifically the SecurityPermission with the SecurityPermissionFlag.ControlPrincipal bit flag set (see Figure 1). Neither the intranet nor the Internet CodeGroups are granted this permission, so in a default configuration, only assemblies loaded from the local hard-drive can modify the thread's Principal.

Figure 1Figure 1 The ControlPrincipal Security Permission as shown in the Microsoft .NET Framework 1.1 Configuration snap-in.

If you think this doesn't guarantee enough protection, you can toughen the requirements of your authentication and authorization code in the following way:

  • Authentication: Place the authorization code, custom Principal classes, and custom Identity classes in the same assembly and provide an internal (Friend in VB.NET) constructor only for the latter two. No other assemblies can then create your custom security objects. There is a more sophisticated approach available as well: You can allow only assemblies developed by your company to create custom security objects. To do so, just sign all your company assemblies with the same key and then place the appropriate StrongNameSecurityPermission on the authentication assembly entry points.

  • Authorization: After you know exactly who can create a specific security object, you can restrict the authorization phase, requiring a specific Principal object type being present in Thread.CurrentPrincipal (more on this later).

Authentication in ASP.NET

Due to the stateless nature of HTTP, authentication in ASP.NET has some peculiarities. IIS provides four authentication mechanisms: Basic, Integrated, Digest, and Certificate Mapping. All these options map an Internet user to a local or domain user on the Web server. To have the user Identity and Principal transparently flow from IIS to the ASP.NET context, all you have to do is set authentication mode to Windows in the web.config file:

<authentication mode="Windows" /> 

NOTE

In ASP.NET, the WindowsPrincipal is available both through Thread.CurrentPrincipal and the Page.User property (yes, there is a Principal in it, not an Identity).

Most of the time, the complexity of managing a Windows user store for Internet application users requires you to develop other kinds of authentication solutions. ASP.NET offers two built-in authentication mechanisms: PassPort authentication and Form authentication. (Covering PassPort authentication is out of the scope of this article.)

Form authentication is an infrastructure for developing your own ASP.NET-based custom authentication. Instead of reauthenticating the user on each call, an authentication cookie is issued (it can be encrypted and protected against tampering). The Form Authentication infrastructure automatically redirects unauthenticated users to a login page and puts a GenericPrincipal (containing a FormsIdentity object) into both Thread.CurrentPrincipal and Page.User when the logon phase has completed successfully. The Form authentication infrastructure rebuilds and reattaches the FormsIdentity object to the ASP.NET execution context on each page request. However the infrastructure doesn't maintain in the Principal object the roles the user belongs to across HTTP requests. The best approach to work around this problem is the following:

  • Once and for all, stuff the roles list into the userdata parameter of the FormsAuthenticationTicket constructor while performing Form authentication:

  • private void Login_Click(object sender, System.EventArgs e) {
     if(pf_AuthenticateUser(txtUserName.Text)) {
     string l_roles = pf_getroles(txtUserName.Text);
     FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1, 
      txtUserName.Text , DateTime.Now, 
      DateTime.Now.AddMinutes(30), false, l_roles);
     string cookiestr = FormsAuthentication.Encrypt(tkt);
     HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName, 
      cookiestr);
     ck.Path = FormsAuthentication.FormsCookiePath; 
     Response.Cookies.Add(ck);
    
     string strRedirect =Request["ReturnUrl"];
     if (strRedirect==null)
      strRedirect = "default.aspx";
     Response.Redirect(strRedirect, true);
     }
    }
  • Extract the user data in the AuthenticateRequest Application event (which fires on each Web request); re-create a new, properly configured, GenericPrincipal; and assign it to the Thread.CurrentPrincipal and Page.User methods:

  • protected void Application_AuthenticateRequest(Object sender, EventArgs e) {
     if (Context.Request.IsAuthenticated ) {
     String[] arrRoles ;
     System.Web.Security.FormsIdentity ident ;
     ident = (System.Web.Security.FormsIdentity ) Context.User.Identity;
     arrRoles = ident.Ticket.UserData.Split (',');
     Context.User = new GenericPrincipal(ident, arrRoles);
     }
    }

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020