Showing posts with label Forms Authentication. Show all posts
Showing posts with label Forms Authentication. Show all posts

Thursday, September 30, 2010

How to redirect users to certain page based or username or user role

Step 1:
You need to setup default as intermidiate page. I have called it as Transfer.aspx
<authentication mode="Forms">
  <forms
    loginUrl="~/Login.aspx"
    defaultUrl="~/Transfer.aspx" />
</authentication>
Step 2:
Then please consider setup role based authenticaiton to relevent folders,
  <location path="Admin">
    <system.web>
      <authorization>
        <allow roles="Admin"/>
        <deny users="?"/>
      </authorization>
    </system.web>
  </location>
  <location path="Members">
    <system.web>
      <authorization>
        <allow roles="Member"/>
        <deny users="?"/>
      </authorization>
    </system.web>
  </location>
In the tranfer aspx page.
Point 1:  If you need a just perticular user, to redirect to a certain page, you can simple use user's name.
Transfer.aspx
<%@ Page Language="C#" %>
<script runat="server">
    protected override void OnLoad(EventArgs e)
    {
        if (this.Page.User != null && this.Page.User.Identity.IsAuthenticated)
        {
            if (this.Page.User.Identity.Name.Equals("Admin"))
                this.Response.Redirect("~/Admin/Default.aspx");
            else
                this.Response.Redirect("~/Member/Default.aspx");
        }
        else this.Response.Redirect("~/Login.aspx");
    }
</script>
Point 2:  If you need grop of users (role based) to redirect to a certain page,
Transfer.aspx
<%@ Page Language="C#" %>
<script runat="server">
    protected override void OnLoad(EventArgs e)
    {
        if (this.Page.User != null && this.Page.User.Identity.IsAuthenticated)
        {
            if (this.Page.User.IsInRole("Admin"))
                this.Response.Redirect("~/Admin/Default.aspx");
            else if (this.Page.User.IsInRole("Member"))
                this.Response.Redirect("~/Member/Default.aspx");
            else
                this.Response.Redirect("~/Default.aspx");
        }
        else this.Response.Redirect("~/Login.aspx");
    }
</script>

Tuesday, August 24, 2010

How to append RootUrl to ReturnUrl parameter in login page

We can append Root Url to return url parameter in the login page and do a response redirect to same page so that return url value will get updated to routed value.
Example:
public partial class Login : Page
{
    public string RootUrl
    {
        get
        {
            Uri requestUri = Context.Request.Url;
            HttpRequest request = Context.Request;
            string rootUrl = string.Format("{0}{1}{2}{3}{4}",
                requestUri.Scheme,
                Uri.SchemeDelimiter,
                requestUri.Host,
                requestUri.IsDefaultPort ? string.Empty : string.Format(":{0}", requestUri.Port),
                request.ApplicationPath);
            return rootUrl.EndsWith("/") ? rootUrl : string.Format("{0}/", rootUrl);
        }
    }
 
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        string returnUrl = this.Request.QueryString.Get("ReturnUrl");
        if (!string.IsNullOrEmpty(returnUrl))
        {
            if (!returnUrl.ToLower().Contains("http://"))
            {
                returnUrl = Path.Combine(this.RootUrl, returnUrl);
                string url = string.Format("{0}?ReturnUrl={1}", this.Request.Path, Server.UrlEncode(returnUrl));
                this.Response.Redirect(url);
            }
        }
    }
}
Referene

Monday, May 17, 2010

How to build login session timeout prompt message using jQuery

ASP.Net forms authentication session renew its authentication ticket only when the total escape time exceeds the half of the configured timeout. Say for example if you have 20 minutes configured in the web.config.
  1. Login time : 2.00 pm – Authentication ticket created (Expire on 2.20 pm)
  2. Do a postback: 2.05 pm. Before 10 minutes, which is a half of the configured timeout – Authentication ticket will not get renewed (Expire on 2. 20 pm)
  3. Leave browser – no postbacks
  4. Do a postback: 2.12 pm. After 10 minutes, which is a half of the configured timeout – Authentication ticket will get renewed (Expire on 2.32 pm)
If you need to have a time out message in your web page, we have to use a java script function with a counter. When counter comes to a certain point, say 2 minutes before the actual forms time out show the timeout message. However according to above explanation there is no constant timeout value for the first half of the timeout. Therefore we have to calculate the timeout and pass it to the java script function on each postback.

Example:





Test page inherit from the page base:

public class PageBase : Page
{
    private string startUpStript = @"
        var timeout = ({0} * 60) - 10;
        var timeEscaped = 0;
        var timerTicks = 0;
        var showBefore = 30
        function CountDown() {{
            if (timeEscaped < timeout - showBefore) {{
                setTimeout(CountDown, 1000);
                timeEscaped++;
            }}
            else
                ShowTimer();
        }}
        function ShowTimer() {{
            $("".LoginTimeout"").fadeIn();
            DisplayTime();
        }}
        function DisplayTime() {{
            if (timerTicks < showBefore) {{
                $("".LoginTimeout .TimeoutMessage .Timeout"").text(showBefore - timerTicks);
                timerTicks++;
                setTimeout(DisplayTime, 1000);
            }}
            else ShowTimedOutMsg();
        }}
        function ShowTimedOutMsg() {{
            $("".LoginTimeout .TimeoutMessage"").fadeOut();
            $("".LoginTimeout .LoggedOutMessage"").fadeIn();
        }}
        $(document).ready(function () {{
            CountDown()
        }});
    ";
    public LoginTimeout LoginTimeout
    {
        get { return (LoginTimeout)Session["LoginTimeout"]; }
        set { Session["LoginTimeout"] = value; }
    }
    public override void ProcessRequest(HttpContext context)
    {
        base.ProcessRequest(context);
        if (context.User != null && context.User.Identity.IsAuthenticated)
        {
            FormsIdentity identity = this.User.Identity as FormsIdentity;
            FormsAuthenticationTicket ticket = identity.Ticket;
            if (this.LoginTimeout == null || this.LoginTimeout.IssuedTime != ticket.IssueDate)
            {
                this.LoginTimeout = new LoginTimeout()
                {
                    IssuedTime = ticket.IssueDate,
                    TimeOut = FormsAuthentication.Timeout
                };
            }
            else
            {
                TimeSpan adjustment = DateTime.Now - this.LoginTimeout.IssuedTime;
                this.LoginTimeout.TimeOut = FormsAuthentication.Timeout - adjustment;
            }
        }
    }
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        if (this.LoginTimeout != null)
            this.Page.ClientScript.RegisterClientScriptBlock(
                this.GetType(),
                this.GetType().Name,
                string.Format(this.startUpStript, this.LoginTimeout.TimeOut.Minutes),
                true);
    }
 
}
public class LoginTimeout
{
    public DateTime IssuedTime { getset; }
    public TimeSpan TimeOut { getset; }
}

Test page markup:

<%@ Page Language="C#" AutoEventWireup="true"
     CodeBehind="Test.aspx.cs" Inherits="ActiveTest.Test" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Test Page</title>
    <style type="text/css">
        body { font-family:Tahomafont-size:11px; }
        p { padding:0margin:0; }
        .LoginTimeoutdisplay:none; 
                       padding:10px; 
                       background-color:#ffbd8c; 
                       height:15px; 
                       border:dotted 1px #f57313; 
                       text-align:center; 
                       width:300px; }
        .LoginTimeout .LoggedOutMessage,
        .LoginTimeout .TimeoutMessage { position:absolute; }
        .LoginTimeout .LoggedOutMessage { display:none; }
    </style>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript" language="javascript"></script>
</head>
<body>
    Test Page
    <form method="get" action="Page2.html">
        <div class="LoginTimeout">
            <div class="TimeoutMessage">
                <p>Your login session will timeout in <strong>
                <span class="Timeout"></span></strong> seconds</p></div>
            <div class="LoggedOutMessage">
                <p>Your login sesson has timed out. You need to <a href="Login.aspx">
                login again</a></p></div>
        </div>
    </form>
</body>
</html>

Test page code behind:

namespace ActiveTest
{
    public partial class Test : PageBase
    {
 
    }
} 

Reference: Understanding the Forms Authentication Ticket and Cookie

Thursday, August 21, 2008

Protect file types (.xml, .doc, .html, .pdf etc.) using ASP.NET authentication: Microsoft ASP.NET

Because requests to .xml, .doc, .html, .pdf etc handled by the IIS instead of asp.net ISAPI module first it is required to configure specified extensions to be handled by the asp.net ISAPI module

How to configure custom file extension to be handled by the asp.net ISAPI module

In IIS (run ‘inetmgr’)
  1. Locate the website (or virtual directory, which configured as a web application) you want to configure custom file extensions to be secured.
  2. Right click and find the ‘Virtual Directory’ tab under properties
  3. In ‘Virtual Directory’ tab click configuration
  4. Add extension (ex: .xml) and browse aspnet_isapi.dll from the usual location (C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727). If you can’t find the exact directory perform a search and locate it.
  5. Uncheck ‘check that file exist’ checkbox just in case of request to a non existing file. then press ok
  6. If it is local it is recommend to do a IIS reset (run ‘iisreset’) if not if it is the production server or UAT, recycle the application pool
For securing asp web applications: please review my previous post - ASP.NET Authentication

Sunday, March 23, 2008

ASP.NET Authentication

About

Securing location of an asp.net website with password protection while allowing anonymous users to the rest of the site.
The application can then call FormsAuthentication.Authenticate, supplying the username and password, and ASP.NET will verify the credentials. Credentials can be stored in cleartext, or as SHA1 or MD5 hashes, according to the following values of the passwordFormat attribute:

Hash Type Description
Clear Passwords are stored in cleartext
SHA1 Passwords are stored as SHA1 digests
MD5 Passwords are stored as MD5 digests

Usage

<authentication>
  <credentials;passwordformat="SHA1">
    <user name="Mary" password="GASDFSA9823598ASDBAD">
      <user name="John" password="ZASDFADSFASD23483142">
  </credentials>
</authentication>


if (FormsAuthentication.Authenticate(this.Login1.UserName, this.Login1.Password))
    FormsAuthentication.RedirectFromLoginPage(this.Login1.UserName, false);
Web.config
<configuration>
  <system.web>
    <compilation batch="false" debug="true" defaultlanguage="c#">
      <authentication mode="Forms">
        <forms name="cornerstone" 
               defaulturl="admin/admin.aspx" 
               timeout="20" 
               protection="All" 
               loginurl="admin/login.aspx" 
               path="/">
          <credentials passwordformat="Clear">
            <user name="user1" password="password1">
              <user name="user2" password="password2">
        </credentials>
        </forms>
      </authentication>
      <authorization>
        <allow users="*">
    </authorization>
    </system.web>
  <location path="admin">
    <system.web>
      <authorization>
        <deny users="?">
      </authorization>
    </system.web>
  </location>
  <configuration>

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...