In this post, we will discuss about authentication and authorization and how to implement authorization in asp.net mvc web application by comparing it to the way of implementing it in classic asp.net web application.

Let us Start with the basic definitions of authentication and authorization,

Authentication: Process of identifying and validating the identity of a User accessing
an application. In simple terms, Checking if a user trying to access your site is valid or not.


Authorization: Process of determining whether an authenticated user has permission to access a particular URL/resource or to perform some action.


In MVC, We don't need to edit the web.config file specifying the Authentication mode for your web application. Rather, In MVC the default template of MVC website defines a forms based authentication for us. And provides the membship and role provider setting in web.config file along with a connection string. All you need to do is to edit the connection string to point to the desired datasource.The code snippet shows the auto generated code in the web.config file when we create a new mvc asp.net web application.

<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" 
providerName="System.Data.SqlClient"/>

<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880"/>
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" applicationName="/"/>
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add connectionStringName="ApplicationServices" applicationName="/" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
<add applicationName="/" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</providers>
</roleManager>

We also don't require to insert location tabs to specify authorization for specific pages as we do in classic asp.net web site.

 

<location path="/forms/index.aspx" allowOverride="true">
    <system.web>
      <authorization>
        <allow roles="xyz"/>
        <deny users="abc"/>
      </authorization>
    </system.web>
  </location>

<location path="/forms/about.aspx" allowOverride="true">
    <system.web>
      <authorization>
        <allow roles="mno"/>
      </authorization>
    </system.web>
  </location>

 

 

ASP.NET MVC 2 ships with a filter attribute called "AuthorizeAttribute" that provides out-of-the-box authentication and authorization. Developers can apply the attribute to actions to restrict access to them. If the user isn’t permitted to access the action, the AuthorizeAttribute will transmit an HTTP status code of 401 Unauthorized to the browser, indicating that the request has been refused. Applications using ASP.NET’s forms authentication mechanism and with a login page specified in Web.config will then redirect the browser to the login page, and users may only proceed once they have been authenticated.

For Eg:

 

[Authorize]
 public ActionResult Index()
{
      return View();
 }

 

 

The above code will allow only authenticated user to get to the "Index" view page. Further, to allow only particular user/groups to have permissions to access a page, we can do something like:

[Authorize(Users="tom, jerry")]
public ActionResult Index()
{
      return View();
}


[Authorize(Roles="Admin, DataManager")]
 public ActionResult Edit(int id)
{
      return View();
}

For Hiding and showing links, to only authenticated users we can use the code snippets as:


<%
    if (Request.IsAuthenticated) {
%>
        Welcome <b><%= Html.Encode(Page.User.Identity.Name) %></b>!
        [ <%= Html.ActionLink("Log Off", "LogOff", "Account") %> ]
<%
    }
    else {
%> 
        [ <%= Html.ActionLink("Log On", "LogOn", "Account") %> ]
<%
    }
%>

Instead of specifying authorize attribute on each action method we can apply AuthorizeAttribute to a controller, and in that case it’s applied to every action in that controller. If multiple AuthorizeAttributes are applied to an action, all checks occur and the user must be authorized by all of them.

At the end, the conclusion is a single term "Authorize" needed  to acheive our goal.

Have Fun

:-)