How to check if user is logged in - asp.net

I have created a Login page where users must provide username and password to have access to some specific resources, where they can upload images, or just edit some description about themselves.
My web.config file looks like this:
<authentication mode="Forms">
<forms loginUrl="Secure/Login.aspx" defaultUrl="index.aspx" name=".ASPXFORMSAUTH" timeout="30"/>
</authentication>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
<location path="Secure">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
So when the user has typed in the username and pw, he is redirected to the index.aspx page.
Depending wether the user is logged in or not, the index.aspx should show or hide some stuff.
This is how I check if he is logged in:
bool isLoggedIn = HttpContext.Current.User.Identity.IsAuthenticated;
if (isLoggedIn)
{
placeHolder2.Visible = true;
...
}
Now the problem is that the: HttpContext.Current.User.Identity.IsAuthenticated; ALWAYS returns true, so unauthorised people will be seeing the stuff that should be hidden.
I am not sure about the: HttpContext.Current.User.Identity.IsAuthenticated;
I just googled "How to check if user is logged in", and suggestions were the:
HttpContext.Current.User.Identity.IsAuthenticated;
I want only the people that are logged in to view the private stuff. How do I go about this? How do I make the: HttpContext.Current.User.Identity.IsAuthenticated only return true when the user is logged in?
Thanks

if (Request.IsAuthenticated) {.....}
edit based on some comments
Authenticated via "Forms", check here
HttpContext.Current.User.Identity.IsAuthenticated // will be "Forms" if using forms based auth
// "Negotiate" is using windows integrated
// etc
If using .net 4.5 and you wanted "SET" user claims.
The ClaimsPrincipal is recommended reading

bool isLoggedIn = System.Web.HttpContext.Current.User.Identity.IsAuthenticated

My coding is
bool val1 = (System.Web.HttpContext.Current.User != null) &&
(System.Web.HttpContext.Current.User.Identity.IsAuthenticated) &&
(System.Web.HttpContext.Current.User.Identity.AuthenticationType.ToString() == "Forms");
for identifying the users with domain login and logged in form

Related

FormsAuthentication.SetAuthCookie in Generic Handler ashx

I have an Generic Handler where I would like to auto-login based on some querystrings.
But then I set FormsAuthentication.SetAuthCookie(user.Name, false), but HttpContext.Current.User.Identity.IsAuthenticated return false, and I can't redirect because of the limits set in web.config.
So how do I set FormsAuthentications in an .ashx-file?
To perform a login using the FormsAuthentication module, you may want to just use the RedirectFromLoginPage static method, which, under the covers:
prepares the authentication token;
encrypts it;
adds it to the cookie collection of the response;
performs the redirect to the required page (or the default one, as per your web.config).
Here is a short prototype for your handler:
public void ProcessRequest(HttpContext context)
{
// TODO: Determine the user identity
var username = context.Request.QueryString["username"];
FormsAuthentication.RedirectFromLoginPage(username, true);
}
If you are not comfortable by the way this method performs its job, you may do each activity in a manual way:
prepare a FormsAuthenticationTicket with the user name;
encrypt it by way of the Encrypt method;
add it to the response Cookies;
issue a redirect.
Have you tried adding it as a location path in the web.config?
<configuration>
<location path="foo.ashx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<location >
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
</configuration>

ASP.Net authentication: Can I have multiple responses when user fails to authenticate/authorize to access a page

I am using ASP.net form authentication for my web application. I have folder "admin" for administration work, and also I can lock one user if he/she misbehaves.
currently if an normal user tries to access the admin page, it will be redirected to the logon page, although he/she is already logged on.
The question is: how can I configure the web app, so that when the user fails to access a page, I can show different pages such as "you need admin privilege to access this page"/"your account is locked out"/(normal logon page)?
ValidateUser() can only return bool. :(
Thanks a lot
You'll need to implement roles and add people to them. Once you assign people to the proper roles, you would check to see if the person is in the proper role to access a page. If not, redirect them or show the proper error message. You would be able to do this with code behind like it seems like you are already trying:
if(!Roles.IsUserInRole("Administrator")) Response.Redirect("~/");
Or you can use the web.config
<configuration>
<location path="memberPages">
<system.web>
<authorization>
<allow roles="Administrator" />
<deny users="*" />
</authorization>
</system.web>
</location>
<configuration>
See the links below for more info:
https://web.archive.org/web/20210417083524/https://www.4guysfromrolla.com/articles/121405-1.aspx
http://msdn.microsoft.com/en-us/library/ff647401.aspx
I solved this kind of problem giving different urls to diffenrent roles.
To admin you give www.yoursite.com/admin
to user you give www.yoursite.com/private
asp.net will automatically redirect both to the login.aspx page but you can get from the url parameter which kind of user it is.
//I detect where the request originated from
string str = Request.QueryString["ReturnUrl"] == null ? "" : Request.QueryString["ReturnUrl"].ToString();
//if this is Admin can access to Admin Area only
if (str.Contains("Admin") == true || str.Contains("admin") == true || str.Contains("ADMIN") == true)
{ .......

How does ASP.NET's Authentication module work?

I can not make it clear about how the asp.net's authentication work,I set the following configuration according to the help document and google:
<configuration>
<!--
Login.aspx and the random_code_img.aspx does not need authentication
But excluding the above files,all the page are protected.
-->
<location path="Login.aspx">
</location>
<location path="random_code_img.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<system.web>
<authorization>
<deny users="?"/>
</authorization>
..........
</system.web>
</configuration>
Now in the login.aspx.cs:
Within the method loginButton_click:
if (Membership.ValidateUser(username, password))
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
username,
DateTime.Now,
DateTime.Now.AddMinutes(30),
isPersistent,
"",
FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie.
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
// Redirect back to the protected URL.
Session["havelogined"] = "1";
HttpContext.Current.Response.Write("<script>location.replace('Default.aspx')</script>");
}
else{
//do something
}
However in the login.aspx,after I enter the name and password,then click the login button,I was redirected to Default.aspx in the address bar of the browser,but I can not see the content of the Default.aspx,I just see:
Access is denied.
Description: An error occurred while accessing the resources required to serve this request. The server may not be configured for access to the requested URL.
Error message 401.2................
So I wonder how does the asp.net's authentication know if I am logined or not? Can I repace these notice with some readable information?
Also,
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
What does the "users" here mean?
I do not think they are the registered users in my database.
HTTP 401.2 status code corresponds to "No Authentication method configured". I'll need more info to confirm. If I had to guess I'd say you are missing the <forms> tag under the <authentication> tag.
If you haven't already found this article, you might try this link which talks about how to fully setup forms authentication - http://msdn.microsoft.com/en-us/library/xdt4thhy.aspx
the
<allow users="*"/>
means allow all users. In essence it is instructing ASP.NET to allow all users (authenticated or unauthenticated) access to random_code_img.aspx
BTW:
<deny users="?"/>
means don't allow unauthenticated users.
Hope this helps.
Inside your loginButton_click method, after you validate your user, you can simply use
FormsAuthentication.RedirectFromLoginPage
See here for more information and example . http://msdn.microsoft.com/en-us/library/ka5ffkce.aspx

Role based authorization

I am trying to use Role based authorization in declarative way, when unauthorized user attempt to access a page, it never fire an exception or show the user an error message. What I should do to show unauthorized message? is that possible in declarative way?
using coding is not a nice option sense I have several roles, and folder authorized for several roles while other folders are authorized for one role.
thanks
Use the following code in your Login page to redirect the user to either an unauthorized page or the default page.
protected void Page_Load( object sender, EventArgs e )
{
if( Page.IsPostBack )
return;
if( !Request.IsAuthenticated )
return;
if( !string.IsNullOrEmpty( Request.QueryString["ReturnUrl"] ) && !UrlAuthorizationModule.CheckUrlAccessForPrincipal(Request.QueryString["ReturnUrl"], User,"GET"))
{
// In Forms Authentication, authenticated but unauthorized requests are converted into a Redirect to the Login page.
// Redirect these to an error page instead.
Response.Redirect( "~/UnauthorizedAccess.aspx", false );
}
else
{
Response.Redirect( FormsAuthentication.DefaultUrl, false );
}
}
See this link for a picture of what's happening and more info:
http://www.asp.net/security/tutorials/user-based-authorization-cs
If it fails authorization it will throw an exception. It must be passing. What are you using for authentication? Have you disabled anonymous access?
Perhaps you could make use of a site map. More on those here, plus a bit about tying security to them here.
It's also possible to use web.config to set up permissions for various folders or files. Each folder could have a list of allows or denys like so:
<?xml version="1.0"?>
<configuration>
<system.web>
<authorization>
<allow roles="Administrators" />
<allow roles="Random Role" />
<deny users="*" />
<deny users="?" />
</authorization>
</system.web>
</configuration>
Then when someone hits the page that requires authorization that they don't have permission for it will redirect them to your login page. You could then check the query string for the page they came from and perhaps set up case specific responses, or at the very least if it has a returnURL page on it, say "You are not authorized to see this page."

Why Response.Redirect("Pagename.aspx") doesn't work

I have one application where after successful Login user will be redirected to Home.aspx.
Now if I try Response.Redirect("Home.aspx") it doesnt work, But if I try
FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, false);..its working.
Now my question is why Response.Redirect() is not working?
I know FormsAuthentication.RedirectFromLoginPage do much more than Login, it also sets cookie,and also redirects to Login Page, but why Redirct() is not working?
web.config:
<authentication mode="Forms">
<forms loginUrl="LogIn.aspx" defaultUrl="Home.aspx" path="/"></forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
Can somebody help?
You already have the answer pretty much.
Response.Redirect does not set the authentication cookie so when Home.aspx is loading it fails authentication and will redirect you back to the login page.
To use response.redirect, you will have to manage the cookie yourself, an example from https://web.archive.org/web/20210513002246/https://www.4guysfromrolla.com/webtech/110701-1.3.shtml is:
Dim cookie As HttpCookie = FormsAuthentication.GetAuthCookie(UserName.Text, _
chkPersistCookie.Checked)
Response.Cookies.Add (cookie)
Response.Redirect(FormsAuthentication.GetRedirectUrl (UserName.Text, _
chkPersistCookie.Checked))
EDIT:
To answer the question in your comment, if you pass true as the second parameter to RedirectFromLoginPage then the cookie will be set to never expire, and you won't need to login again.
FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, true)

Resources