ASP.NET HeadLoginView Logout Click. Logs out of other local websites too - c#

I have 2-3 web projects ( beginner ones). In all the websites I have a login control where a user can log in. When the user logins with correct info, I set the
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
if (CHUser.AunthencateLogin(Login1.UserName, Login1.Password))//Checks with database
e.Authenticated = true;
else
e.Authenticated = false;
}
Up to here is fine, but the problem occurs when I login into 2 separate websites (local) at same time, and log out at any one of them. When I log out at one the other website is also logged out ( when refreshed). Following is the code I use when logging out.
protected void LoginStatus1_LoggingOut(object sender, LoginCancelEventArgs e)
{
Session.Clear(); //though logout works without this code. It is for other
//sessions that are manually created by me
}
I can't see to find out what's the cause of it. I am also new to web development.
I would also like to know if this is the right way of logging in a user.

(Answered in a question edit. converted to a community wiki answer. See What is the appropriate action when the answer to a question is added to the question itself? )
The OP wrote:
Thanks #Aristos. the problem was solved by using the following code on web.config 1st project
<authentication mode="Forms">
<forms name=".Cookie1" ... />
</authentication>
2nd project
<authentication mode="Forms">
<forms name=".Cookie2" ... />
</authentication>

Related

Session Start Global.asax C# ASP.NET

I have the following code:
protected void Session_Start(object sender, EventArgs e)
{
WindowsPrincipal p = Thread.CurrentPrincipal as WindowsPrincipal;
string sUserAccount = HttpContext.Current.User.Identity.Name.ToString();
HttpContext.Current.Session["WinAccount"] = sUserAccount;
}
The code is to get the windows user name. From the session_start, I want to create a session which called WinAccount. But, when I tried to call the session from one of my page (default.aspx) which is has master page on it.
Let say, on page_load:
string sWinAccount = Session["WinAccount"].ToString();
Label1.Text = sWinAccount.ToString();
The web.config looks like:
<authentication mode="Windows"/>
<identity impersonate="false"/>
<authorization>
<deny users="?"/>
</authorization>
Also, the properties of the project has been enabling the windows authentication mode.
When I run, it blanks.
Please advise.
Thank you.
Verify if the application is using Windows Authentication (check web.config). If you are providing custom or forms authentication, you will need to set user details on success handler, not the session start; and use CustomPrincipal rather than WindowsPrincipal .
If windows authentication is enabled, the user credential will be available on the very first request (session start) and can be retrieved are you mentioned in your code. Place a debugger in session start and verify if you are retrieving it properly or not.
try
string sUserAccount =System.Security.Principal.WindowsIdentity.GetCurrent().Name.Tostring();
Session_Start event fired when a new client start their very first request to the app, not when the user is logged in. So in your case, the HttpContext.Current.User.Identity.Name is empty at the time Session_Start is called. It worked as expected.

asp.net c# - setting session then redirecting users via global.asax

hello I'm trying so hard for this, I cant understand most question since this is my first time developing in ASP.NET here is my problem.
Im declaring session variable when the user click the submit in the login page then redirecting them to somepage.aspx
if (dt.Rows.Count > 0)
{
Session["usersId"] = usersId;
Session["usersLevel"] = usersLevel;
Session["usersRegion"] = usersRegion;
Session["notification"] = "";
Response.Redirect("pages/Dashboard.aspx");
}
So after that that I put something in my Web.config
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<sessionState timeout = "1" mode = "InProc" />
</system.web>
So ofcourse the session will expire?/timeout? then in my Global.asax I put this
void Session_End(object sender, EventArgs e)
{
Response.Redirect("Login.aspx");
}
However an HttpExeception rises, that says
Response is not available in this context.
Why did the response is not available? when it said that the sessionstate mode must be set to InProc? I just want the user to be redirected in that page when the session expires/timeout(I dont know their difference but looks same to me)
thank you
You may consider to do the redirect in AuthenticateRequest event. Only inProc sessionstate provider supports session end event and it may happen any time(even after the relevant request is responsed, that's why you saw that exception).

Proper way to make the expiration of the FormAuthentication Cookie redirect to login

I am using Form
Web.Config:
<authentication mode="Forms">
<forms loginUrl="~/Login/LogOn" timeout="2880" />
</authentication>
within the LogOn Method:
FormsAuthentication.SetAuthCookie(userName, isPersistanceCookie);
My understanding is that when the cookie is deleted, it could automatically redirect to the login page (calling the LogOn method), but this does not work.
Within Global.asax.cs, within the
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
....
....
....
if (!currentPage.Contains("login"))
{
HttpCookie loginCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (loginCookie == null)
{
Response.Redirect("/login");
}
}
}
I don't believe this is the right way to approach it as it seems very prone to security flaws.
Any help is much appreciated!

ASP.NET login form authentication without login control

I am using ASP.NET membership and on registration page trying to login without a login control.
When user clicks on the register button, the control goes to redirect.aspx page.
But in that page, while I am trying to redirect to the members homepage its throwing the following error.
ERROR -
Unable to evaluate expression because the code is optimized or a native frame
is on top of the call stack.
Web.config -
<authentication mode="Forms">
<forms name=".SSOAuth" loginUrl="login.aspx" defaultUrl="Redirect.aspx"
protection="Validation" timeout="30000"/>
</authentication>
RegistrationPage code -
protected void btnRegister_Click(object sender, EventArgs e)
{
MembershipUser userMemb = Membership.CreateUser(
txtemail.Text.Replace("'", "''").ToString(),
txtPassword.Text.Replace("'", "''").ToString(),
txtemail.Text.ToString());
Roles.AddUserToRole(txtemail.Text.ToString(), "Member");
FormsAuthentication.RedirectFromLoginPage(txtemail.Text.Trim(), false);
}
Redirect.aspx.cs code -
try
{
if (User.IsInRole("Member"))
{
string UserName = User.Identity.Name;
Response.Redirect("~/Member/MembeHome.aspx");
}
}
catch(Exception ex) {}
Read this document (issue and solution) ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer
Use Response.Redirect(url,false)
Response.Redirect("~/Member/MembeHome.aspx",false);

exception catching in Global.ascx app_error

I have web application in asp.net and C#
I am trying to handle exceptions if they occur anywhere within this application.
like suppose the behaviour should be if and exception like this occurs
//generate your fictional exception
int x = 1;
int y = 0;
int z = x / y;
it should catch it in the app_error of the global.ascx file and redirect it to the Default.aspx page. i got the logging part but the redirect is not working as i still get the
Server Error in '/' Application.
page. or may be it is redirecting and getting killed in the middle..
this is what is there in global.ascx
protected void Application_Error(object sender, EventArgs e)
{
logger.Fatal(this.Server.GetLastError().GetBaseException());
logger.Info("FatalLogger Passed");
//get reference to the source of the exception chain
Exception ex = Server.GetLastError().GetBaseException();
Response.Redirect("~/Default.aspx?error=MessageHere");
}
this in the code in web.config
<authentication mode="Forms">
<forms loginUrl="Login.aspx" defaultUrl="~/Default.aspx" name="GUI" slidingExpiration="true" timeout="30" path="/">
</forms>
</authentication>
any ideas.. ill; be happy to provide more information.
Thanks
ok i want this approach for a reason because whenever there is an error the user get logged out and i dont want that to happen instead go to the default page
Have you tried calling Server.ClearError() before the redirect in Application_Error? It's been a while since I played with this, but I believe that if you don't call ClearError then the framework still thinks the error is unhandled.
Configure custom error pages
BTW, I recommend ELMAH for the logging part...
Try using Server.Transfer(page)
Also be wary of passing the error message via the Query String as it can open you up to XSS problems. Pass an error code and then display the message dependent on the code (using a switch statement)

Categories