Authentication Models

.Template Authentication Options

Authentication and Authorization


Authentication is the process of confirming the identity of a user (client) to the server or to an application. IIS and the .NET framework work together to manage the authentication process. Together, IIS and the .NET framework provide two different HTTP approaches to authentication:

  1. Challenge-based - process requires the client to respond to the server's demands for credentials. (e.g. Basic, Digest, Windows Authentication Models)

  2. Login Redirection-based - process requires the client must send credentials to the application without being required by the server. (e.g. Forms Authentication Models)

Authorization is the process of determining where an authenticated user will be permitted to perform an action on a resource. The permitted action may be allowing the user to access a particular web page, or make updates to particular data. Traditional authorization is typically performed on a per-user or a user-role basis. ASP.NET 5 introduced Policy-Based Authorization where policy builders create re-usable authorization logic, and Resource-Bases Authorization where the resource authorization is coded in the handler for particular resources.

Authentication Models

Five of the authentication models for web applications are:

  1. Basic - authentication takes an anonymous request and returns a challenge (401 - Unauthorized) for a resource. The client must reply to the challenge by supplying credentials to access the resource. If the credentials are verified by the server, then the server returns an authorization token back to the client. The client then sends the authorization token (in the Authorization header) back to the server in another request for the resource, and is then granted access to the resource. Basic authorization does not encrypt the credentials (User Name/Password). The credentials are only encoded in base64 (see Base64 Ecoder and Decoder, so they are insecure.

  2. Digest - authentication is more secure than Basic as Digest hashes the credentials which are sent to the server. Digest is vulnerable to man-in-the-middle attacks where someone with a proxy can intercept the message and use the authorization token to imprersonate the user on the website.

  3. Windows - authentication requires a Windows server and operating systems. Does not work well over the Internet so is for Intranet applications on Windows networks. On the Intranet it can provide a single-signon experience where user signs on to the network and then are automatically authenticated to various Intranet applications. Windows authentication works in a similar to Basic and Digest. However it can be more secure and less obtrusive than Basic and Digest. WHen an anonymous request is made for a resource, the user is redirected to a login screen (Form). Once the credentials are verified, the user is redirected back to the original page it requested.

  4. Forms - authentication is the most popular form of authentication over the Internet. Forms is highly customizable where the developer has complete control over the entire authorization process. It requires the development of a login form for the entry of the user's credentials and typically a database to store the credentials. Forms authentication is not secure unless using secure HTTP as the credentials are sent in clear text. Forms authentication uses cookies by default. Once authenticated the server will send a cookie containing an authorization token. This cookie is send on subsequent requests to the server as proof of authentication. ASP.NET has extensibility points for Forms authentication where either Microsoft authentication APIs (Membership, Simple Membership, Identity) or custom authentication APIs can be connected.

  5. Federated - allows using third-party authorization systems (Twitter, Facebook, Google, etc.) in your web application. One the third-party authentication system verifies the credentials, it returns information to the web application indicating the user as been successfully authenticated. The web application does not need a permanent store of the user's credentials, but instead relies on the authentication data and mechanism from the third party.

ASP.NET supports the following types of authentication providers, which are specified in the root-level web.config file:

  1. Windows - (default) for Intranet, authenticates using Windows accounts.

  2. Forms - for Internet, uses cookies, requires HTTPS to be secure.

  3. None - used when no authentication is required or when using custom authentication code.

1
2
3
4
<system.web>
   <!-- mode=[Windows|Forms|None] -->
   <authentication mode="Windows" />
</system.web>


Configuration of Authentication Method in Root-level Web.config

Microsoft APIs for Forms Authentication

The most popular type of authentication for Web Applications running on the Internet is Forms authentication. Forms authentication requires the collecting the users credentials and checking them against a database of known users. Over time, Microsoft has provided various APIs to help with this process. In .NET 2.0 (2005) Microsoft introduce the concept of a extensible "Provider" model to help with the tasks required in Forms authentication. Microsoft included a default "Membership" and "Role" provider which would use SQL Server to store the user data (credentials, roles, profiles). With the Membership provider, Visual Studio could be used to generate the code required Forms authentication using a SQL Server database. The generation would even create the required database tables. The provider model allowed the use of other types of database management systems by creating "Custom Providers".

To help with the creation of Custom Membership Provides, Microsoft introduced "Simple Membership" which became a popular way of managing authentication in MVC (e.g. the MVC application template in MVC 4 uses Simple Membership). Simple Membership was just a wrapper on top of the older Membership API which allowed you to work with any of the most popular database management systems. At this point in time Web Forms was using the Membership provider, MVC was using Simple Membership, and they both were using their own Custom Membership providers because the APIs did not support all of their needs. In particular third-party authentication (Federated Authentication) was becoming popular and need support in .NET. Also, having different providers for different .NET development models did not fit in with the "One ASP.NET" philosophy.

So in .NET 4.5.1 (Visual Studio 2013) Microsoft created the "ASP.NET Identity" system as a replacement for the Membership and Simple Membership providers. Identity can be used will all the .NET development models and uses Entity Framework "Code First" to generate the required database tables. Identity supports third-party authentication of any OWIN-based host as well as cloud-based sources for Intranet authentication, such as Azure Active Directory (Azure AD). Identity is distributed through NuGet package manager.

Authentication Coding

Code can be added to applications to create custom authorizations, but better way to manage customization is to use the provider extensibility points in ASP.NET. Customer Membership and Role providers can be created and integrated into the application. Web Forms used the <authorization> element in the web.config to restrict access to resources. However MVC uses the Authorize attribute tag to control both authentication and authorization. Custom authentication and authorization tags can be created derived from the AuthorizeAttribute class. In MVC 3+ global filters can be created which could be used to require authentication to access any of the resources on the website. However with a global authentication filter, the <AllowAnonymous> needs to be used to decorate the login methods.

AuthorizeAttribute

The Authorize attribute tag can be added at the action method level or at the controller level. At the controller level, the attribute affects all the action methods within the controller. When added to both the controller and the action methods, the attribute at the action method level has priority. The authorize attribute requires the user be Authenticated to gain access to the tagged resource. Additional parameters can be added to the Authorize tag to further restrict the resource to a particular user (user ID) or group of users (roles). If unauthorized users try to access a resource marked with the Authorize attribute, a 401 status code will be generated and (if using Forms authentication) the framework will redirect the user to a login page. Examples usage of the built-in authorize attribute tags are:

  1. [Authorize] - the user must be authenticated.

  2. [Authorize(Users="Kevin,Cathy")] - authenticated users Kevin and Cathy can access the resource.

  3. [Authorize(Roles="admin")] - authenticated users included in the admin role can access the resource.

  4. [AllowAnonymous] - unauthenticated users can access the resource.

Below is an example of a custom authorization attribute derived from AuthorizeAttribute:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public class CheckAttendeeNameAttribute : System.Web.DomainServices.AuthorizationAttribute
{

    public override bool Authorize(System.Security.Principal.IPrincipal principal)
    {
        if (principal.IsInRole("Attendee") && principal.Identity.Name.StartsWith("A"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}


1
2
3
4
5
[CheckAttendeeNameAttribute]
public ActionResult ViewResults(int id)
{
    return View();
}


Custom Authorize Attribute

Gobal Authentication Filter

Add code example for Global Authentication Filter when working on Filters page.

Custom Membership Providers

ASP.NET 2.0 introduced the Membership system for Forms authentication. The concept was to automate the development process of creating support for user authentication to a database. The extensible providers: Membership, Profile, and Role together created a user system which would have previously been created by the developer. This included creating the database schema and well as the screens for login users and maintaining their credentials.

Two primary reasons for creating a custom membership provider when using Forms authentication is because the .NET membership provider does not support the database or the database has a different schema than used by the .NET membership provider. The default database used for membership providers is SQL Server, however other databases are also supported. See Tutorial: MySQL Connector/Net ASP.NET Membership and Role Provider

for information about using MySQL as a database for the membership system. Also use "aspnet_regsql.exe" for setting up the schema in a SQL Server database.

The first step in implementing a custom membership provider is to create a class that extends the MembershipProvider class. Then update the root-level web.config file to use the custom membership provide. In the example below, notice in the web.config:

  1. The "defaultProvider" attribute must be used in the membership element to specify the name of the custom membership provider.
  2. The "type" parameter must specify the fully qualified name of the customer membership provider class.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public class CustomMembershipProvider : MembershipProvider
{   
    public override MembershipUser CreateUser(string username, 
       string password, string email, string passwordQuestion, 
       string passwordAnswer, bool isApproved, 
       object providerUserKey, out MembershipCreateStatus status)
    {
        throw new NotImplementedException();
    }

    public override MembershipUser GetUser(string username, bool userIsOnline)
    {
        throw new NotImplementedException();
    }

    ...
}


Override MemberShipProvider to Create a Customer Membership Provider

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<connectionStrings>
    <add name="ApplicationServices" 
      connectionString="Server=your_server;Database=your_db;
                         Uid=your_user_name;Pwd=your_password;"
      providerName="System.Data.SqlClient" />
</connectionStrings>

<authentication mode="Forms">
  <forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>

<membership defaultProvider="CustomMembershipProvider">
  <providers>
    <clear/>
    <add name="CustomMembershipProvider" 
       type="CustomMembership.Models.CustomMembershipProvider"
        connectionStringName="AppDb"
        enablePasswordRetrieval="false"
        enablePasswordReset="true"
        requiresQuestionAndAnswer="false"
        requiresUniqueEmail="false"
        maxInvalidPasswordAttempts="5"
        minRequiredPasswordLength="6"
        minRequiredNonalphanumericCharacters="0"
        passwordAttemptWindow="10"
        applicationName="/" />
  </providers>


Web.Config Code to Configure Customer Membership Provider