Showing posts with label Security. Show all posts
Showing posts with label Security. Show all posts

Monday, May 27, 2013

ReturnUrl=%2f Issue in ASP.NET Forms Authentication

Some time back I used FormsAuthentication in an ASP.NET  project and everything seemed to be working fine expect for a one issue.

When I Loged into the application and clicked on LogOut it was navigating to the LogIn page and it adds 'ReturnUrl=%2f' to the Return URL and it caused me to click on the LogIn button twice with correct authentication details, in order to navigate to the default page. I added the below code snippet and it solved the issue for me.

In Global.asax.cs file.

    void Application_BeginRequest(object sender, EventArgs e)
    {
        if (Request.AppRelativeCurrentExecutionFilePath == "~/")
            HttpContext.Current.RewritePath("~/Gate/Index.aspx");//This is the default page to navigate after a successful login.
    }

Tuesday, May 7, 2013

How to Pass Custom Data in FormsAuthenticationTicket

Lets say we have an custom object with following properties.

public class AuthUser
{
public int UserID { get; set; }
public string UserNo { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public override string ToString()
{
return UserID + "," + UserNo + "," + UserName + "," + Password;
}
}

To pass custom data with the authentication ticket use below code.

AuthUser au = new AuthUser();
au.UserID = 1;
au.UserNo ="001";
au.UserName = "chamara";
au.Password = "123";
string userData = au.ToString();

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(

2, // Version number

txtUserName.Text.Trim(), // Username

DateTime.Now, // Issue date

DateTime.Now.AddDays(555), // Expiration date

false, // Persistent?

userData // User data
);

Retrieve Userdata

FormsIdentity id = (FormsIdentity)Context.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
string[] UserData = ticket.UserData.Split(',');

Monday, January 21, 2013

ASP.NET Security: Secure Sockets Layer (SSL)

SSL technology encrypts communication between a client and a website. Although it slows performance, it’s often used when private or sensitive information needs to be transmitted between an authenticated user and a web application. Without SSL, any information that’s sent over the Internet, including passwords, credit card numbers, and employee lists, is easily viewable to an eavesdropper with the right network equipment.

Even with the best encryption, you have another problem to wrestle with—just how can a client be sure a web server is who it claims to be? For example, consider a clever attacker who uses some sort of IP spoofing to masquerade as Amazon.com. Even if you use SSL to transfer your credit card information, the malicious web server on the other end will still be able to decrypt all your information seamlessly. To prevent this type of deception, SSL uses certificates.

The certificate establishes the identity, and SSL protects the communication. If a malicious user abuses a certificate, the certificate authority can revoke it. To use SSL, you need to install a valid certificate. You can then set IIS directory settings specifying that individual folders require an SSL connection. To access this page over SSL, the client simply types the URL with a preceding https instead of http at the beginning of the request.

In your ASP.NET code, you can check whether a user is connecting over a secure connection using code like this:

protected void Page_Load(Object sender, EventArgs e)
{
 if (Request.IsSecureConnection)
{
lblStatus.Text = "This page is running under SSL.";
}
else
{
lblStatus.Text = "This page isn't secure.<br />";
lblStatus.Text += "Please request it with the ";
lblStatus.Text += "prefix https:// instead of http://";
}
}

ASP.NET Security: Retrieving the User’s Identity

Once the user is logged in, you can retrieve the identity through the built-in User property, as shown here:

protected void Page_Load(Object sender, EventArgs e)
{
lblMessage.Text = "You have reached the secured page, ";
lblMessage.Text += User.Identity.Name + ".";
}

You don’t need to place the code in the login page. Instead, you can use the User object to examine the current user’s identity anytime you need to.

You can access the User object in your code because it’s a property of the current Page object. The User object provides information about the currently logged-in user. It’s fairly simple—in fact, User provides only one property and one method:

• The Identity property lets you retrieve the name of the logged-in user and the type of authentication that was used.

• The IsInRole() method lets you determine whether a user is a member of a given role (and thus should be given certain privileges).

Sunday, January 20, 2013

ASP.NET Security: Members of the FormsAuthentication Class

FormsCookieName 
A read-only property that provides the name of the forms authentication cookie.

FormsCookiePath 
A read-only property that provides the path set for the forms authentication cookie.

Authenticate() 
Checks a user name and password against a list of accounts that can be entered in the web.config file.

RedirectFromLoginPage() 
Logs the user into an ASP.NET application by creating the cookie, attaching it to the current response, and redirecting the user to the page originally requested.

SignOut() 
Logs the user out of the ASP.NET application by removing the current encrypted cookie.

SetAuthCookie() 
Logs the user into an ASP.NET application by creating and attaching the forms authentication cookie. Unlike the RedirectFromLoginPage() method, it doesn’t forward the user back to the initially requested page.

GetRedirectUrl() 
Provides the URL of the originally requested page. You could use this with SetAuthCookie() to log a user into an application and make a decision in your code whether to redirect to the requested page or use a more suitable default page.

GetAuthCookie() 
Creates the authentication cookie but doesn’t attach it to the current response. You can perform additional cookie customization and then add it manually to the response.

HashPasswordForStoringInConfigFile() 
Encrypts a string of text using the specified algorithm (SHA1 or MD5). This hashed value provides a secure way to store an encrypted password in a file or database.

ASP.NET Security: Controlling Access to Specific Files

Generally, setting file access permissions by directory is the cleanest and easiest approach. However, you also have the option of restricting specific files by adding <location> tags to your web.config file.

The location tags sit outside the main <system.web> tag and are nested directly in the base <configuration> tag, as shown here:

<configuration>
<system.web>
...
<authentication mode="Forms">
<forms loginUrl="~/Login.aspx" />
</authentication>

<authorization>
<allow users="*" />
</authorization>
</system.web>
...
<location path="SecuredPage.aspx">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>

<location path="AnotherSecuredPage.aspx">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>

</configuration>

In this example, all files in the application are allowed, except SecuredPage.aspx and AnotherSecuredPage.aspx, which have an additional access rule denying anonymous users.

Notice that even when you use multiple <location> sections to supply different sets of authorization rules, you still only include one <authentication> section. That’s because a web application can use only one type of authentication.

ASP.NET Security: Controlling Access to Specific Directories

A common application design is to place files that require authentication in a separate directory. With ASP.NET configuration files, this approach is easy. Just leave the default <authorization> settings in the normal parent directory, and add a web.config file that specifies stricter settings in the secured directory. This web.config simply needs to deny anonymous users (all other settings and configuration sections can be omitted).

<!-- This web.config file is in a subfolder. -->
<configuration>
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>

ASP.NET Security: Authorization Rules

If you make these changes to an application’s web.config file and request a page, you’ll notice that nothing unusual happens, and the web page is served in the normal way. This is because even though you have enabled forms authentication for your application, you have not restricted anonymous users. In other words, you’ve chosen the system you want to use for authentication, but at the moment none of your pages needs authentication. To control who can and can’t access your website, you need to add access control rules to the <authorization> section of your web.config file. Here’s an example that duplicates the

default behavior:

<configuration>
<system.web>
...
<authentication mode="Forms">
<forms loginUrl="~/Login.aspx" />
</authentication>
<authorization>
<allow users="*" />
</authorization>
</system.web>
...
</configuration>

The asterisk (*) is a wildcard character that explicitly permits all users to use the application, even those who haven’t been authenticated. Even if you don’t include this line in your application’s web.config file, this is still the behavior you’ll see, because the default settings inherited from the machine.config file allow all users. To change this behavior, you need to explicitly add a more restrictive rule, as shown here:

<authorization>
<deny users="?" />
</authorization>

The question mark (?) is a wildcard character that matches all anonymous users. By including this rule in your web.config file, you specify that anonymous users are not allowed. Every user must be authenticated, and every user request will require the security cookie. If you request a page in the application directory now, ASP.NET will detect that the request isn’t authenticated and attempt to redirect the request to the login page (which will probably cause an error, unless you’ve already created this file).

Now consider what happens if you add more than one rule to the authorization section:

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

When evaluating rules, ASP.NET scans through the list from top to bottom and then continues with the settings in any .config file inherited from a parent directory, ending with the settings in the base machine.config file. As soon as it finds an applicable rule, it stops its search. Thus, in the previous case, it will determine that the rule <allow users="*"> applies to the current request and will not evaluate the second line. This means these rules will allow all users, including anonymous users.

But consider what happens if these two lines are reversed:

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

Now these rules will deny anonymous users (by matching the first rule) and allow all other users (by matching the second rule).

Authentication and Authorization in ASP.NET

Two concepts form the basis of any discussion about security:

Authentication: This is the process of determining a user’s identity and forcing users to prove they are who they claim to be. Usually, this involves entering credentials (typically a user name and password) into some sort of login page or window. These credentials are then authenticated against the Windows user accounts on a computer, a list of users in a file, or a back-end database.

Authorization: Once a user is authenticated, authorization is the process of determining whether that user has sufficient permissions to perform a given action (such as viewing a page or retrieving information from a database). Windows imposes some authorization checks (for example, when you open a file), but your code will probably want to impose its own checks (for example, when a user performs a task in your web application such as submitting an order, assigning a project, or giving a promotion).

Authentication and authorization are the two cornerstones of creating a secure userbased site. The Windows operating system provides a good analogy. When you first boot up your computer, you supply a user ID and password, thereby authenticating yourself to the system. After that point, every time you interact with a restricted resource (such as a file, database, registry key, and so on), Windows quietly performs authorization checks to ensure your user account has the necessary rights.

You can use two types of authentication to secure an ASP.NET website:

Forms authentication: With forms authentication, IIS is configured to allow anonymous users (which is its default setting). However, you use ASP.NET’s forms authentication model to secure parts of your site. This allows you to create a subscription site or e-commerce store. You can manage the login process easily, and write your own login code for authenticating users against a database or simple user account list.

Windows authentication: With Windows authentication, IIS forces every user to log in as a Windows user. (Depending on the specific configuration you use, this login process may take place automatically, as it does in the Visual Studio test web server, or it may require that the user type a name and password into a Login dialog box.) This system requires that all users have Windows user accounts on the server (although users could share accounts). This scenario is poorly suited for a public web application but is often ideal with an intranet or company-specific site designed to provide resources for a limited set of users.