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

Context.User.Identity.Name Is Empty Null Blank

Context.User.Identity.Name Is Empty Null Or Blank In Asp.Net. If you have set the forms authentication and trying to display logged in user name in your asp.net web application by getting the user name using user.identity.name and this is blank or empty as displayed in image below.

Context.User.Identity.Name is Empty

Then u might have missed few configuration settings.

If yor are getting user identity name null or emplty when u try to get it to display user name in welcome message (for example) then probably you have allowed anonymous access to your site hence user.identity.name is null.

To avoid this try to write the code as mentioned below

First of all set authentication mode to forms authentication in web.config file




Now deny anonymous access to your site by adding below mentioned code in authorization section of web.config.






the ? represents anonymous user

Now write this code in Page_load to check the value of Identity name.

protected void Page_Load(object sender, EventArgs e)
    {
        if (HttpContext.Current.User != null)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                lblName.Text = HttpContext.Current.User.Identity.Name.ToUpper().ToString();

            }
                      
        
        }
        
    }

Context.User.Identity.Name is Blank

Now identity name is not blank as shown in picture.

You may also read more about Forms Authentication And FormsAuthenticationTicket.

1

Forms Authentication In Asp.Net

Forms Authentication In Asp.Net 20.,3.5,4.0 With Folder Level Access And Managing Roles

Forms Authentication in asp.net

In examples below i'm explaining how to use forms authentication in Asp.Net and forms authentication tickets in Asp.net.












Forms Authentication In Asp.Net 2.0 and 3.5


Forms Authentication in ASP.NET is technique to decide how users can access your web application.

Using froms authentication we can decide certain users can access only certain pages or we can control the anonymous access, we can implement folder level access and access based on roles.

we can manage the access through web.config file or folder level access and through multiple web.config files using forms authentication.

Read More


Forms Authentication Ticket In Asp.Net 2.0 And 3.5


In this article i am going to describe how to implement Forms authentication tickets and manage user roles based access in ASP.NET using C# and multiple web.config files

Read More


Bypass Forms Authentication Or Skip Authorization


Some readers ask me how to skip or bypass forms authentication or Authorization for selected pages in asp.net or a scenario where only few pages on site needs user to log in rest can be accessed without login.

Read More


Detecting Session Timeout and Redirect to Login Page in ASP.NET


In this example i'll show how to detect the session timeout which occurs when user is idle for the time specified as Session imeout,using forms authentication,C# asp.NET and if it is than redirect the user to login page to login again, for this i've set time out value in web.config file to 1 minute

Read More



Have fun

0

Bypass Forms Authentication Or Skip Authorization Asp.Net

Bypass Forms Authentication Or Skip Authorization for selected pages in asp.net

In my previous articles i explained how to use forms authentication in asp.net
1. C# Forms Authentication using ticket and managing user roles in asp.net

2. ASP.NET 2.0 - Forms Authentication with C# and managing folder lavel access with multiple web.config files

And i also explained about how to validate use across pages using session and redirect to login page if user is not logged in

User validation across pages using session after login in ASP.NET using C sharp

Some readers ask me how to skip or bypass forms authentication or Authorization for selected pages in asp.net or a scenario where only few pages on site needs user to log in rest can be accessed without login.

For this we need to set HttpContext.Current.SkipAuthorization property to true in global application class called Global.asax

You can write code like this

string Url = Request.RawUrl;
int count = Url.Length - 10 ;
string TestUrl = Url.Substring(count);
string SessionData = Session["Authenticate"].ToString();
if (TestUrl != "Admin.aspx")
{
HttpContext.Current.SkipAuthorization = true;
}

Here i'm checking if the page url is not Admin.aspx than skip the authentication check
You can use multiple && (and) or || (or) conditions with this



Download the sample code attached



Related posts:
ASP.NET Submit form on Enter Key Default submit Button
Register custom controls dlls and user controls ascx in ASP.NET
Search records in GridView with searchbox in footer and highlight results using AJAX
User validation across pages using session after login in ASP.NET
Creating OpenFileDialog in winforms to open or browse for the file in .NET windows application using C#

18

Forms Authentication Ticket In Asp.Net 2.0 3.5

In this article i am explaining how to implement FormsAuthenticationTicket And Managing UserData Roles In Asp.Net 2.0,3.5,4.0 using C# And VB.NET



For implementing forms authentication without using formsauthentication ticket, read my previous article - Forms Authentication with C# and managing folder lavel access with multiple web.config files

Configuring web.config file in application root


<authentication mode="Forms">
<forms defaultUrl="Default.aspx" loginUrl="~/Login.aspx"
slidingExpiration="true" timeout="20"></forms>
</authentication>

Defining roles and accessibility in root web.config

<location path="Admin">
<system.web>
<authorization>
<allow roles="admin"/>
<deny users="*"/>
</authorization>

</system.web>

</location>


Defining roles settings for folders and aspx within those folders in web.config file in those folders

<system.web>
<authorization>
<allow roles="user"/>
<deny users="*"/>
</authorization>
</system.web>

settings for any logged in member

<system.web>
<authorization>
<deny users="?"/>
</authorization>


Now after creating Login page we need to authenticate user

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string userName = Login1.UserName;
string password = Login1.Password;
bool rememberUserName = Login1.RememberMeSet;

//Fetch User login information fromthe xml file into Dataset

string xmlFilePath = Server.MapPath("~/App_Data/LoginInfo.xml");
DataSet objDs = new DataSet();
objDs.ReadXml(xmlFilePath);
DataRow[] dRow = objDs.Tables[0].Select("UserName = '" + userName + "' and Password = '" + password + "'");
if (dRow.Length > 0)
{
//Fetch the role
string roles = dRow[0]["Roles"].ToString();

//Create Form Authentication ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(20), rememberUserName, roles, FormsAuthentication.FormsCookiePath);

// In the above parameters 1 is ticket version, username is the username associated with this ticket
//time when ticket was issued , time when ticket will expire, remember username is user has chekced it
//roles associted with the user, and path of cookie if any

//For security reasons we may hash the cookies
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);

// add the cookie to user browser

Response.Cookies.Add(cookie);

// get the requested page

string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null)
returnUrl = "~/Default.aspx";
Response.Redirect(returnUrl);
}


Now to retrieve the authentication and roles information on every request we need to write this code in Global.asax file

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
// look if any security information exists for this request

if (HttpContext.Current.User != null)
{

// see if this user is authenticated, any authenticated cookie (ticket) exists for this user

if (HttpContext.Current.User.Identity.IsAuthenticated)
{

// see if the authentication is done using FormsAuthentication

if (HttpContext.Current.User.Identity is FormsIdentity)
{

// Get the roles stored for this request from the ticket

// get the identity of the user

FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;

//Get the form authentication ticket of the user

FormsAuthenticationTicket ticket = identity.Ticket;

//Get the roles stored as UserData into ticket

string[] roles = ticket.UserData.Split(',');

//Create general prrincipal and assign it to current request

HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles);
}
}
}
}


To check whether user in in the role or not we need to write this code in every page which provide access on role basis

protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.User.IsInRole("admin"))
{
lblMessage.Text = "Welcome Administrator";
}
}


Download sample code


Related Articles :

1. Forms Authentication with C# and managing
folder lavel access with multiple web.config files


2. User validation across pages using session
after login in ASP.NET using C sharp


3. Detecting Session Timeout
and Redirect to Login Page in ASP.NET

9

Forms Authentication In Asp.Net 2.0 3.5 4.0

Forms Authentication in ASP.NET 2.0, 3.5, 4.0 With Folder Level Access And Multiple Web.Config Files is technique to decide how users can access your web application. Using forms authentication we can decide certain users can access only certain pages or we can control the anonymous access, we can implement folder level access And roles.

we can manage formsAuthentication through web.config file

Read my article on implementing FormsAuthentication Ticket And Managing Roles

1. First of all create a new website and add a new form , name it Login.aspx
Drag login control on it from the toolbox
Make sure you have a web.config file in root of your application

2. Right click on solution explorer and add new folder , name it membersArea
Add a new from and name it members.aspx
Add a web.config file in this folder.

Now to implement Forms Authentication we need to configure web.config file (in the application root)

For this we need to add Authentication and Authorization tags inside <system.web> tag of web.config

<system.web>
<authentication mode="Forms">
<forms defaultUrl="Default.aspx" loginUrl="~/Login.aspx"
slidingExpiration="true" timeout="20">
</forms>
</authentication>
</system.web>

Now To restrict access to the membersonly page which is inside membersonly folder so that only members can access this page we need to create a another web.config file inside this folder to provide it's access rules
In this web.config write this inside <system.web> tag
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>

Now for login process and checking the username and password we need to write this code, double click on the login control placed on the Login.aspx page, it will generate Login1_Authenticate event
protected void Login1_Authenticate
(object sender, AuthenticateEventArgs e)
{
bool isMember = AuthenticateUser(Login1.UserName, Login1.Password,
Login1.RememberMeSet);

if (isMember)
{
FormsAuthentication.RedirectFromLoginPage(Login1.UserName,
Login1.RememberMeSet);
}
}

And this for checking username and password, i m using hard coded values
private bool AuthenticateUser(string userName, string password, bool rememberUserName)
{
string userName = "amiT";
string password = "password";

if (userName.Equals(userName) && password.Equals(password))
{
return true;
}
else
{
return false;
}
}


16

Detecting Session Timeout And Redirect To Login Page In ASP.NET

This is example of Detecting Session Timeout and Redirect to Login Page in ASP.NET, session timeout occurs when user is idle for the time specified as in web.config file.

For this i've set time out value in web.config to 1 minute.

1st Method
In web.config file, set the sessionstate mode to inproc and authentication mode to Forms
<system.web>
<compilation debug="true"/>
<authentication mode="Forms"/>
<sessionState mode="InProc" cookieless="false" timeout="1">
</sessionState>
</system.web> 


I've created three pages in this example , one is login page , when session expires , i redirect to this page , one is navigation page where i'll check if session is valid or not , if it is valid than only user will see this page other wise he gets redirected to login page.

Add Global.asax class file in root of your application or website.
This method works only if Global.asax is present in application.


Write below mentioned code in Page_Init event of the page where we want to check for session timeout.

we can also put this code in in a class and inherit all pages of application from this class acting as base class for all pages to check for session timeout.

C# CODE
protected void Page_Init(object sender, EventArgs e)
    {
        if (Context.Session != null)
        {
            if (Session.IsNewSession)
            {
                HttpCookie newSessionIdCookie = Request.Cookies["ASP.NET_SessionId"];
                if (newSessionIdCookie != null)
                {
                    string newSessionIdCookieValue = newSessionIdCookie.Value;
                    if (newSessionIdCookieValue != string.Empty)
                    {
                        // This means Session was timed Out and New Session was started
                        Response.Redirect("Login.aspx");
                    }
                }
            }
        }
    }

VB.NET
Protected Sub Page_Init(sender As Object, e As EventArgs)
 If Context.Session IsNot Nothing Then
  If Session.IsNewSession Then
   Dim newSessionIdCookie As HttpCookie = Request.Cookies("ASP.NET_SessionId")
   If newSessionIdCookie IsNot Nothing Then
    Dim newSessionIdCookieValue As String = newSessionIdCookie.Value
    If newSessionIdCookieValue <> String.Empty Then
     ' This means Session was timed Out and New Session was started
     Response.Redirect("Login.aspx")
    End If
   End If
  End If
 End If
End Sub


2nd Method.
Code for Default.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnSessionStart"
runat="server"
OnClick="btnSessionStart_Click"
Text="Start Session" /><br />
<br />
<br />
<asp:Button ID="btnCheck"
runat="server"
OnClick="btnCheck_Click"
Text="Check Session ID" />
<br />
<asp:TextBox ID="txtSession"
runat="server"
Width="266px">
</asp:TextBox><br />
<br />
<asp:Button ID="btnGO"
runat="server"
OnClick="btnGO_Click"
Text="Go to Other Page" />
<br />
<br />
</div>
</form>
</body>
</html>

And the code behind for this page is like
protected void btnSessionStart_Click
(object sender, EventArgs e)
{
Guid Session_id = Guid.NewGuid();
Session["SessionID"]
= Session_id.ToString();

}
protected void btnCheck_Click
(object sender, EventArgs e)
{
if (Session["SessionID"] != null)
txtSession.Text =
Session["SessionID"].ToString();
else
txtSession.Text =
"Session has expired";
}
protected void btnGO_Click
(object sender, EventArgs e)
{
Response.Redirect("Default2.aspx");
}

On the page where we want to check the session has timed out or not, we need to check it in the Page_Init event of the page , if session is not null than user will be able to go to the page other wise he will be redirected to login page.

In this page I've just put a button to go to home page
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnHome"
runat="server" OnClick="btnHome_Click"
Text="Home" /></div>
</form>
</body>
</html>

And the Code behind for this page is

protected void Page_Init(object sender, EventArgs e)
{
CheckSession();
}
protected void btnHome_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}

private void CheckSession()
{
if (Session["SessionID"] == null)
{
Response.Redirect("Login.aspx");
}

}

If we need to check this in all the pages of application than we can create a BaseClass and write the above mentioned code of CheckSession and Page_Init part and drive all ur pages from this class by typing BaseClassName in place of System.Web.UI.Page and it will check all pages for session timeout every time page is loaded


Find More Articles