Skip to main content

Using IsInRole() with Forms Authentication

A Little background….

Page object provides User [System.Security.Principal.IPrincipal] in order to access to the information about the current authenticated user. User is having following two important members. These members provide way to implement Role-based authorization programmatically.

Identity [Property] [System.Security.Principal.IPrincipal.Identity] – This property provides important members like AuthenticationType, IsAuthenticated, Name.



IsInRole[Method] [System.Security.Principal.IPrincipal] – This method takes single parameter that is string value of Role for which to check the membership.


First configure the web.config to use Forms Authentication as below:



<authentication mode="Forms">

<forms loginUrl="~/Login/Login.aspx?Session=Expired" protection="None" timeout="20" name=".ASPXAUTH" path="/"/>

</authentication>



On Login click event do the following:





protected void btnLogin_Click(object sender, EventArgs e)

{

/*Here put your code to fetch the userinformation which includes user name, role, password,etc. from Database*/

...



/*Now, create the Forms Authentication ticket with the application’s custom user role & user name,.*/

FormsAuthenticationTicket Authticket = new FormsAuthenticationTicket(1,

userName, DateTime.Now, DateTime.Now.AddMinutes(HttpContext.Current.Session.Timeout),

false, userrole.ToString(), FormsAuthentication.FormsCookiePath);



/*You may want to encrypt the ticket information before putting into the coockie.*/

string hash = FormsAuthentication.Encrypt(Authticket);



HttpCookie Authcookie = new HttpCookie          (FormsAuthentication.FormsCookieName, hash);



/*Here you can set some coockie sessings like persistence, httponly..*/

if (Authticket.IsPersistent)

Authcookie.Expires = Authticket.Expiration;



/*Now, add the cookie to the Reponse object of Current HttpContext.*/

HttpContext.Current.Response.Cookies.Add(Authcookie);



/*Put the userrole into session*/

HttpContext.Current.Session[USER_ROLE] = UserRole.Operator;



/*Now you can redirect the user to the requested page*/

HttpContext.Current.Response.Redirect(~/Operator/Home.aspx, false);

}  



Now, you can check the custom application user role on any page before authorizing the resource as follows:



Public static void CheckAuthorizedUserRole()

{

                if (!HttpContext.Current.User.IsInRole(“Operator”))

      {

FormsAuthentication.SignOut();
/*Or else, you can redirect the user to the desired page.[Probably, Access Denied!]*/
      }            

}



Here system will check for the specific user role, if not found forms authentication will forces the user to signout.



This way you can have the custom implementation of role based authorization.

Popular posts from this blog

Remote debugging Windows azure cloud service - Worker Role

Remote debugging Windows azure cloud service - Worker Role Very recently I was working on design and development of a worker role component of cloud service. Locally debugging worker role is pretty easy. You just need to know that you need to set Cloud project as a start-up project and ready to go. Problem is when you deploy worker role to azure and trying to troubleshoot an unknown issue.  Thankfully we have remote debugging enable for cloud services – both web and worker roles. This is really handy tool to remotely debug without having to putting a lot of tracing and digging into it. However, remote debugging in worker role/web role requires few steps to be followed: Make sure you are debugging from same machine where you published Make sure to turn on Remote debugger on while you publish (This should be turned off for Production publish profiles) Make sure to Select Debug mode With all the above settings after you publish, you should be able to Attach D

Differences between Object Serialization and Deserialization?

Serialization = putting the relevant state of the object into a streamable representation. That can mean converting it to a byte stream. This does not necessarily include copying every member variable into the stream. Deserialization = restoring an object from a serial representation and ensuring the invariants of the object. Deserialization can be thought of a separate constructor for the object.

Web-API - RESTful Services on Microsoft .net for building Ubiquitous web world

It's been very interesting to note about the fantastic things happening in the world of web development. Finally, we got the solid framework for building RESTful services on Microsoft platform. Let's have a very  quick look at the basic detail. REST [Representation State Transfer Protocol]           A representation is a opaque string of bytes that is effectively manifestation of a resource. REST was never about pretty URLs. The whole point of the hypermedia is that client should not need to know how to construct these URLs in the first place. For your clients, they are just STRINGS.           Web-API can be used when you have clients which consumes data from server over HTTP. Now a days, lot of browser applications are rich clients with web server returns some static html and then may be it uses client side framework like jquery, backbonejs or knockoutjs and makes calls back to server to pull data to execute some client-side functionality. Web-API's role is not j