October 22, 2012 10:43 by
Scott
October 16, 2012 08:48 by
Scott
Introduction
This article describes how to create a permanent user login session in ASP.NET. The sample code includes an ASP.NET MVC4 project to control the user registration and login process. But you can use this technique in any type of ASP.NET project.
Forms Authentication
Before getting into the depth of this article, you must be familiar with forms authentication in ASP.NET. The configuration of form authentication resides in web.config file which has the following configuration-file fragment with the assigned values.
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn"
protection="All"
timeout="1"
name=".USERLOGINCONTROLAUTH"
path="/"
requireSSL="false"
slidingExpiration="true"
defaultUrl="~/Home/Index"
cookieless="UseDeviceProfile"
enableCrossAppRedirects="false"/></authentication>
The default values are described below:
- loginUrl points to your application's custom logon page. You should place the logon page in a folder that requires Secure Sockets Layer (SSL). This helps ensure the integrity of the credentials when they are passed from the browser to the Web server.
- protection is set to All to specify privacy and integrity for the forms authentication ticket. This causes the authentication ticket to be encrypted using the algorithm specified on the machineKey element, and to be signed using the hashing algorithm that is also specified on the machineKey element.
- timeout is used to specify a limited lifetime for the forms authentication session. The default value is 30 minutes. If a persistent forms authentication cookie is issued, the timeout attribute is also used to set the lifetime of the persistent cookie.
- name and path are set to the values defined in the application's configuration file.
- requireSSL is set to false. This configuration means that authentication cookies can be transmitted over channels that are not SSL-encrypted. If you are concerned about session hijacking, you should consider setting requireSSL to true.
- slidingExpiration is set to true to enforce a sliding session lifetime. This means that the session timeout is periodically reset as long as a user stays active on the site.
- defaultUrl is set to the Default.aspx page for the application.
- cookieless is set to UseDeviceProfile to specify that the application use cookies for all browsers that support cookies. If a browser that does not support cookies accesses the site, then forms authentication packages the authentication ticket on the URL.
- enableCrossAppRedirects is set to false to indicate that forms authentication does not support automatic processing of tickets that are passed between applications on the query string or as part of a form POST.
FormsAuthentication.SetAuthCookie Method
This method creates an authentication ticket for the supplied user name and adds it to the cookies collection of the response, or to the URL if you are using cookieless authentication. The first overload of this function has two parameters:
- userName: The name of the authenticated user
- createPersisntentCookie: True to create a persistent cookie (one that is saved across browser sessions); otherwise, false.
This method add a cookie or persistent cookie to the browser with an expire time set in "timeOut" parameter with the name and path set in "name" and "path" parameter. The user will be automatically logged out once the cookie is expired. So the user login session depends on the expire of forms authentication ticket saved in browser cookie. Here, I will create a permanent user login session using this technique.
Cookie Helper
The functionality of this class is to add a form authentication ticket to the browser cookie collection with a life time expiry.
public sealed class CookieHelper
{
private HttpRequestBase _request;
private HttpResponseBase _response;
public CookieHelper(HttpRequestBase request,
HttpResponseBase response)
{
_request = request;
_response = response;
}
//[DebuggerStepThrough()]
public void SetLoginCookie(string userName,string password,bool isPermanentCookie)
{
if (_response != null)
{
if (isPermanentCookie)
{
FormsAuthenticationTicket userAuthTicket =
new FormsAuthenticationTicket(1, userName, DateTime.Now,
DateTime.MaxValue, true, password, FormsAuthentication.FormsCookiePath);
string encUserAuthTicket = FormsAuthentication.Encrypt(userAuthTicket);
HttpCookie userAuthCookie = new HttpCookie
(FormsAuthentication.FormsCookieName, encUserAuthTicket);
if (userAuthTicket.IsPersistent) userAuthCookie.Expires =
userAuthTicket.Expiration;
userAuthCookie.Path = FormsAuthentication.FormsCookiePath;
_response.Cookies.Add(userAuthCookie);
}
else
{
FormsAuthentication.SetAuthCookie(userName, isPermanentCookie);
}
}
}
}
This function is used in login page or control on the click of login button. In the attached sample project, the following function is written in AccountController class. This function validates the login of the user and then add a permanent form authentication ticket to the browser.
private bool Login(string userName, string password,bool rememberMe)
{
if (Membership.ValidateUser(userName, password))
{
CookieHelper newCookieHelper =
new CookieHelper(HttpContext.Request,HttpContext.Response);
newCookieHelper.SetLoginCookie(userName, password, rememberMe);
return true;
}
else
{
return false;
}
}
October 11, 2012 08:15 by
Scott
As a web developer one common request is to make sure that the interfaces we build out for users look the best that they can and also provide users with the best experience both via the keyboard and mouse. As part of this we will often have areas of conflict. This post is going to cover one common scenario that will impact users that might be using DotNetNuke common styles or working to create their own custom button styles. With ASP.NET it is common for people to use "LinkButton" controls to trigger actions rather than your standard "Button" controls as they are easier to style.
There is nothing wrong with this until you try to perform actions against the 'LinkButton' and it doesn't function as you would expect. For this purposes of this post lets say we are building a custom login form that has two textboxes; txtUsername and txtPassword and a single LinkButton btnLogin. We want to ensure that if the user presses enter on either of the textboxes that they are logged in.
Using standard jQuery we would try something like this:
1: $("#<%=txtPassword.ClientID %>").keydown(function(event) {
2: if (event.keyCode == 13) {
3: $("#<%=btnLogin.ClientID %>").click();
4: }
5: });
This is a pretty standard jQuery method to listen for the enter key and simply "click" the button. However, if you are using a LinkButton this code will not work. The reason for this is that a LinkButton is rendered to the browser as an Anchor tag with a href property that contains a javascript action to trigger the postback. Click does nothing on the button as there is nothing for it to complete.
To get around this you need to actually look into the generated anchor tag, grab the href value and evaluate it. Similar to the following:
1: $("#<%=txtPassword.ClientID %>").keydown(function(event) {
2: if (event.keyCode == 13) {
3: eval($("#<%=btnLogin.ClientID %>").attr('href'));
4: }
5: });
Using this structure the postback will be triggered and the user will be logged in as you expect them. This works great for any linkbutton, including those styled with the default DotNetNuke 6.x form pattern styles.
October 1, 2012 08:04 by
Scott
Microsoft has just officially released the highly anticipated Windows Server 2012. The newly released server operating system offers a number of features that can be utilized to benefit developers, resellers and businesses. As a premier European Windows and ASP.NET hosting provider that follow the developments of Microsoft products, HostForLIFE.eu proudly announces the support of Windows Server 2012 Hosting Platform in the world-class Amsterdam (The Netherlands) data center.
“We know that our customers are always looking for new technologies and the latest Microsoft product. With the launch of Windows Server 2012, we believe that anyone can take advantage of all the improvements available in this platform”, said Manager of HostForLIFE.eu, Kevin Joseph. “The focus on high availability, scalability, and virtualization has made this one of the most important releases of Windows Server to date. We have been working closely with Microsoft throughout the pre-release development cycle of the platform to both drive the direction of the product and ensure our team is ready to support Server 2012 solutions. We couldn’t be more excited and confident in the solutions now available to our clients with Windows Server 2012.”
With our Windows Server 2012 Hosting Platform, customers have an access directly to all the newest technologies and frameworks, such as ASP.NET 4.5 Hosting, ASP.NET MVC 4 Hosting, Silverlight 5 Hosting, WebMatrix Hosting, Visual Studio Lightswitch Hosting and SQL 2012 Hosting. All these technologies/frameworks are integrated properly on our world-class Control Panel. The package is offered from just €2.45/month and we believe that this is the most affordable, features-rich Windows and ASP.NET Hosting package in European market.
HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see http://www.microsoft.com/web/hosting/HostingProvider/Details/953). Our service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, we have also won several awards from reputable organizations in the hosting industry and the detail can be found on our official website.
For more information about our service, please visit http://www.hostforlife.eu.
About HostForLIFE.eu:
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.
Our number one goal is constant uptime. Our data center uses cutting edge technology, processes, and equipment. We have one of the best up time reputations in the industry.
Our second goal is providing excellent customer service. Our technical management structure is headed by professionals who have been in the industry since its inception. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.