Thursday, September 11, 2008

Authentication and Authorization in ASP.NET

  • Authentication is the process of verifying user's identity.

  • Authorization is the process of granting privilege to authenticated user.

  • The user is validated using authenticated process and then the authorization process identifies if the user has access to a given resource.

Authentication:-

  • Authentication is the process of obtaining identification credentials such as name and password from a user and validating those credentials against some authority. If the credentials are valid, the entity that submitted the credentials is considered an authenticated identity. Once an identity has been authenticated, the authorization process determines whether that identity has access to a given resource.

  • In ASP.NET, we can authenticate user in code or allow the user to be authenticated by other party such as MS Passport.

  • There are two layer of authentication in ASP.NET

  1. IIS layer :- IIS performs authentication if it is configured to do so. By default, IIS allows anonymous access which means all the users are authenticated. All the requests pass through IIS layer and then to ASP.NET authentication process.If any user requests IIS layer for anonymous access, the user is treated as authenticated and pass to ASP.NET process.

  2. ASP.net authentication process layer :-ASP.NET checks if impersonation is enabled in the web configuaration file i.e. web.config file. If impersonation is enabled, ASP.net acts as though it were the authenticated user otherwise it process with its own configured account.

    • To enable the application to authenticate users, we need to add element in the authorization section of Web.config.

Authentication modes : -

  1. Windows Authentication :-Windows Authentication is the default authentication mechanism for ASP.NET applications .The windows authentication authenticates users based on their windows accounts. In short, it uses windows network security. It uses IIS to perform authentication.Windows authentication is best suited for the application which is meant for a corporate users.

  2. Passport authentication :-The Passport authentication uses Microsoft's passport service to authenticate users. The new user is directed to the Microsoft site where he can register his identity. This facilitates user to access multiple sites using single user name and password. You need to install the Passport SDK to enable the Passport classes in the System.Web.Security namespace.

  3. Form authentication :- The Form authentication collects user's credential and lets the application use own logic to authenticate users. The collected user's credential is validated using the list maintained by the application. The application maintains its own user list either using element in the web.config file or using database. The advantage of using form authentication is that the users don't need to be the member of windows network to have access to the application.Form authentication is preferable for the applications which have diversified users from several places.

we can set authentication mode from web.config file.

<authentication mode="windows">
<authentication mode="passport">
<authentication mode="forms">

Authorization:-

  • Authorization determines whether an identity should be granted access to a specific resource. In ASP.NET, there are two ways to authorize access to a given resource:

  1. File authorization :- File authorization is performed by the 'FileAuthorizationModule'. It checks the access control list (ACL) of the .aspx or .asmx handler file to determine whether a user should have access to the file. ACL permissions are verified for the user's Windows identity (if Windows authentication is enabled) or for the Windows identity of the ASP.NET process. For more information, see ASP.NET Impersonation.

  2. URL authorization :-URL authorization is performed by the 'UrlAuthorizationModule', which maps users and roles to URLs in ASP.NET applications. This module can be used to selectively allow or deny access to arbitrary parts of an application (typically directories) for specific users or roles.
    With URL authorization, we explicitly allow or deny access to a particular directory by user name or role. To do so, we create an authorization section in the configuration file for that directory. To enable URL authorization, we specify a list of users or roles in the allow or deny elements of the authorization section of a configuration file. The permissions established for a directory also apply to its subdirectories, unless configuration files in a subdirectory override them.

    - The syntax is as below

    <authorization>
    < [ allow deny ] [ users ] [ roles ] [ verbs ] />
    </authorization>

- For e.g below authorization section shows how to allow access to the abc identity and deny access to all other users

<authorization>
<allow users="abc">
<deny users="*">
</authorization>

- Here ' * ' refers to all identities and ' ? ' refers to anonymous identity

The allow or deny element is required. we must specify either the users or the roles attribute. Both can be included, but both are not required. The verbs attribute is optional.

- Attributes:-
1. users :-It will check the user accounts for this element.
2. roles :-It will check that the current request that is allowed or denied access to the resource.
3.verbs :-Defines the HTTP verbs to which the action applies, such as GET, HEAD, and POST.
- The following example grants access to Mary and members of the Admins role, while denying access to John ( unless John is a member of the Admins role ) and to all anonymous users.

<authorization>
<allow users = "Mary">
<allow roles = "Admins">
<deny users = "John">
<deny users = "?">
</authorization>

-Both users and roles can refer to multiple entities by using a comma-separated list such as in the following:
<allow users = "John, Mary, redmond\bar">

- Notice that the domain account [ redmond\bar ] must include both the domain and user name.
-The following example lets everyone do a GET, but only Mary can use POST:

<authorization>
<allow verb = "GET" users = "*">
<allow verb = "POST" users = "Mary">
<deny verb = "POST" users = "*">
</authorization>

Rules are applied using the following heuristics:

  • Rules defined in application-level configuration files take precedence over inherited rules. The system determines which rule takes precedence by constructing a merged list of all rules for a URL, with the most recent rules ( those nearest in the hierarchy ) at the head of the list.
  • Given a set of merged rules for an application, ASP.NET starts at the head of the list and checks rules until the first match is found.
    • If a match is found and the match is an <allow> element, the module grants access to the request.
    • If a match is found and the match is a <deny> element, the request is returned with a 401 HTTP status code.
    • If no rules match, the request is allowed unless otherwise denied.

Notice in the last situation, the request is allowed access even if no rules were matched. This happens so because the default configuration for ASP.NET defines an <allow users = "*"> element, which authorizes all users. By default, this rule is applied last.

To prevent this behavior, define a <deny users = "*"> element at the application level.

Like all other configuration settings, the access permissions established for a directory also apply to all of its subdirectories, unless explicitly overriden in a child configuration file.

Configuring authorization using the <location> element

Instead of defining access permissions in separate directory configuration files, you can also define one or more location elements in a root configuration file to specify the particular files or directories to which authorization settings defined in that location element should apply.

The following code example demonstrates how to allow an anonymous user to gain access to the Default.aspx page.

 <configuration>
<location path = "Logon.aspx">
<system.web>
<authorization>
<allow users = "?">
</authorization>
</system.web>
</location>
</configuration>

Wednesday, September 10, 2008

Caching In Asp.Net

Caching is used to speed up processing of an application.Caching is the process of taking information that is time-instensive to collect and storing it in a location that requires less time to access.
  • One could, fairly easily, build their own caching system using Application variables.We can use application-level variables as a cache to store database results. Since application variables are accessible from any page they are quite a logical choice for a caching system.
  • The main benefits of caching are performance-related: operations like accessing database information can be one of the most expensive operations of an ASP page's life cycle. If the database information is fairly static, this database-information can be cached.
  • When information is cached, it stays cached either indefinitely, until some relative time, or until some absolute time. Most commonly, information is cached for a relative time frame. That is, our database information may be fairly static, updated just a few times a week. Therefore, we might want to invalidate the cache every other day, meaning every other day the cached content is rebuilt from the database.
ASP.NET supports three types of caching for Web-based applications:
  1. Output Caching (Page Level Caching)
  2. Page Fragment Caching (often called Partial-Page Output Caching)
  3. Programmatic or Data Caching
Output Caching
  • Output Caching caches the HTML output of dynamic requests to ASP.NET Web pages.
  • Each time an incoming ASP.NET page request comes in, this engine checks to see if the page being requested has a cached output entry. If it does, this cached HTML is sent as a response; otherwise, the page is dynamically rendered, it's output is stored in the Output Cache engine.
  • Output Caching is particularly useful when we have very static HTML pages.
  • Output caching can be easily implemented using the @OuputCache page directive.
  • The syntax looks like this:
    • <%@OutputCache Duration="50" VaryByParam="none" %>
    • Duration:This parameter specifies how long, in seconds, the HTML output of the Web page should be held in the cache. When the duration expires, the cache becomes invalid and, with the next visit, the cached content is flushed, the ASP.NET Web page's HTML dynamically generated, and the cache repopulated with this HTML.
    • VaryByParam:This parameter is used to indicate whether any GET (QueryString) or POST (via a form submit with method="POST") parameters should be used in varying what gets cached. In other words, multiple versions of a page can be cached if the output used to generate the page is different for different values passed in via either a GET or POST.
      • The VaryByParam is a useful setting that can be used to cache different "views" of a dynamic page whose content is generated by GET or POST values. For example, you may have an ASP.NET Web page that reads in a Part number from the QueryString and displays information about a particular widget whose part number matches the QueryString Part number. Imagine for a moment that Output Caching ignored the QueryString parameters altogether (which you can do by setting VaryByParam="none"). If the first user visited the page with QueryString /ProductInfo.aspx?PartNo=4, she would see information out widget #4. The HTML for this page would be cached. The next user now visits and wished to see information on widget #8, a la /ProductInfo.aspx?PartNo=8. If VaryByParam is set to VaryByParam="none", the Output Caching engine will assume that the requests to the two pages are synonymous, and return the cached HTML for widget #4 to the person wishing to see widget #8! To solve for this problem, you can specify that the Output Caching engine should vary its caches based on the PartNo parameter by either specifying it explicitly, like VaryByParam="PartNo", or by saying to vary on all GET/POST parameters, like: VaryByParam="*".
Partial-Page Output Caching
  • More often than not, it is impractical to cache entire pages. For example, we may have some content on our page that is fairly static, such as a listing of current inventory, but you may have other information, such as the current stock price of any company, that we wish to not be cached at all. Since Output Caching caches the HTML of the entire ASP.NET Web page, clearly Output Caching cannot be used for these scenarios: enter Partial-Page Output Caching.
  • Partial-Page Output Caching, or page fragment caching, allows specific regions of pages to be cached. ASP.NET provides a way to take advantage of this powerful technique, requiring that the part(s) of the page you wish to have cached appear in a User Control. One way to specify that the contents of a User Control should be cached is to supply an OutputCache directive at the top of the User Control. That's it! The content inside the User Control will now be cached for the specified period, while the ASP.NET Web page that contains the User Control will continue to serve dynamic content.
  • For this we should not place an OutputCache directive in the ASP.NET Web page that contains the User Control - just put it inside of the User Control.
Data Caching
  • Sometimes, more control over what gets cached is desired. ASP.NET provides this power and flexibility by providing a cache engine. Programmatic or data caching takes advantage of the .NET Runtime cache engine to store any data or object between responses. That is, you can store objects into a cache.
  • This data cache is kept in memory and "lives" as long as the host application does. In other words, when the ASP.NET application using data caching is restarted, the cache is destroyed and recreated. Data Caching is almost as easy to use as Output Caching or Fragment caching.
  • The syntax looks like this:
    • - Cache["ABC"] = str; // C#
      - Cache("ABC") = str ' VB.NET
    • We Can retrive values by
    • - str = Cache["ABC"]; // C#
      - str = Cache("ABC") ' VB.NET
    • Note that after we retrieve a cache value in the above manner we should first verify that the cache value is not null prior to doing something with the data. Since Data Caching uses an in-memory cache, there are times when cache elements may need to be evicted. That is, if there is not enough memory and we attempt to insert something new into the cache, something else will be get!
    • The Data Cache engine does all of this scavenging for your behind the scenes, of course. However, don't forget that you should always check to ensure that the cache value is there before using it. This is fairly simply to do - just check to ensure that the value isn't null/Nothing. If it is, then you need to dynamically retrieve the object and restore it into the cache.