|
Monday, January 09, 2006
Configure Forms authentication
Set IIS security to 'Anonymous', which means all the requests come to the webserver with user id "IUSR_MachineName'. Configure ASP.NET for Forms authentication in Web.Config Set Authorization to deny="?" and allow users="*" Create a FormsAuthetication Ticket in login page or control (Code Snippet 1 below) Redirect the user to the requested page. If the user directly reached the login page, redirect the user to home page. Code in Snippet 1 Create Generic Principal object in global.asax file and put it in current context user. (Snippet 2)
SNIPPET: 1 using System.Web.Security; private void Logon_Click(object sender, System.EventArgs e) { bool isAuthenticated = IsAuthenticated (txtUserName.Text, txtPassword.Text ); if (isAuthenticated == true ) { // roles format "ManagerEmployeeSales" // This makes it easy to store them in the authentication ticket string roles = RetrieveRoles( txtUserName.Text, txtPassword.Text); FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket( intVersion,txtUserName.Text, DateTime.Now,DateTime.Now.AddMinutes(20),boolPersistent,roles) // Version is 1, persistent= fasle string encryptedTicket = FormsAuthentication.Encrypt(authTicket); HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(authCookie); Response.Redirect( FormsAuthentication.GetRedirectUrl( txtUserName.Text, false )); } }
SNIPPET 2: using System.Web.Security; using System.Security.Principal; protected void Application_AuthenticateRequest(Object sender, EventArgs e) { string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = Context.Request.Cookies[cookieName]; if(null == authCookie) { // There is no authentication cookie. return; } FormsAuthenticationTicket authTicket = null; try { authTicket = FormsAuthentication.Decrypt(authCookie.Value); } catch(Exception ex) { // Log exception details (omitted for simplicity) return; } if (null == authTicket) { // Cookie failed to decrypt. return; } string[] roles = authTicket.UserData.Split(new char[]{''}); // Create an Identity object FormsIdentity id = new FormsIdentity( authTicket ); // This principal will flow throughout the request. GenericPrincipal principal = new GenericPrincipal(id, roles); // Attach the new principal object to the current HttpContext object Context.User = principal; }
|
|
|
0 Comments:
Post a Comment
<< Home