ASP.NET login form authentication without login control - c#

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);

Related

Forms Authentication: How to handle unauthorized authenticated user

I am trying to setup a very basic Forms authentication example.
It is correctly redirecting unauthenticated users to the login page
and on submit verifying the credentials and if correct calling:
FormsAuthentication.RedirectFromLoginPage(username.Text, false);
If the user is one named in the authorization section they get their page.
If not it bounces them back to the login page with no error.
How can I redirect correctly authenticated but unauthorized users to a specific error page or detect the authorization error to display an error message on the login page bounce back?
Here is my web.config
<authentication mode="Forms">
<forms name=".ASPXAUTH" loginUrl="/forms/Login" />
</authentication>
<authorization>
<deny users="?" />
<allow users="username1, username2" />
<deny users="*" />
</authorization>
Update:
Based on the answers / comments / research I've got two working solutions.
Put the following in the Page_Load method of your Login form:
if (Request.IsAuthenticated && !string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
{
// This is an unauthorized, authenticated request...
Response.Redirect("FailedAuthorization.aspx");
}
OR
Put the following in your Global.aspx file:
protected void Application_EndRequest(object sender, EventArgs e)
{
if (Response.StatusCode == 401)
{
//Use the built in 403 Forbidden response
Response.StatusCode = 403;
//OR redirect to custom page
//Response.Redirect("FailedAuthorization.aspx");
}
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
// Requires ASP.NET >= 4.5
Response.SuppressFormsAuthenticationRedirect = true;
}
}
Thank you for all the help with this!
Unfortunately, this is one of those things that ASP.NET continually gets wrong. Even though MS and the .NET framework team full well understand the difference between authentication and authorization, they still insist on treating unauthorized as unauthenticated. I don't know why that is.
This is just a quirk of the FormsAuthentication module handler, in that it returns a 401 Unauthorized instead of a 403 Forbidden. (it doesn't help that the HTTP standard confuses Authentication with authorization as well in this manner).
This is not something you can easily override, so your only recourse would be to do something like checking in your Login page to see if they are already logged in, and if they were redirected... it's not foolproof, but it's one way to handle it.
You don't say what version of .NET you're using, but if you are using .net 4.5 then you have another option, which is to use the SuppressFormsAuthenticationRedirect option as in this article:
Forms authentication: disable redirect to the login page
2 checks: if they're authenticated && if there is a return url (which will be there if sent to the log-in page).
if (Request.IsAuthenticated && !string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
{
// This is an unauthorized, authenticated request...
Response.Redirect("~/somewhere.aspx");
}
The Unauthorized redirect Status Code is 302 but this overrides with status 200 when it's redirected to the login page.
In order to redirect the user to Unauthorize Page rather than to the login page, the Hack is to implement Application_EndRequest in Global and check for Response Status Code 302, which is a temporary redirect from the current called to action.
protected void Application_EndRequest(object sender, EventArgs e)
{
if(HttpContext.Current.Response.StatusCode == 302 && User.Identity.IsAuthenticated)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Redirect("/UnauthorizedPageUrl");
}
}

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 HeadLoginView Logout Click. Logs out of other local websites too

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>

FBA login page issue in SharePoint

I have FBA sharepoint site with custom login code (see below). When the user login out side system and I passing Cookie value to FormsAuthentication.RedirectFromLoginPage(userName, false);. It works fine till here.
The issue is, If user goes out side the system and signed out and logged in with different user id and comes to my SharePoint site the login process is skipped and the user is logged in with old id (not with new login id).
Is there any way we can go through login process if user type sharepoint site url and redirected to shareoint site.
Please gurus help me out.
try
{
if (Request.Cookies[authCookie].Value.Length > 0 || Request.Cookies[authCookie].Value != null || Request.Cookies[authCookie].Value != "")
{
userName = Request.Cookies[authCookie].Value;
}
}
catch (Exception ex)
{
Response.Redirect("https://qa.company.com/appssecured/login/servlet/LoginServlet?TARGET_URL=" + Request.Url);
}
if (true)
{
userName = Request.Cookies[authCookie].Value;
FormsAuthentication.RedirectFromLoginPage(userName, false);
}
Web.Config
<authentication mode="Forms">
<forms loginUrl="LoginAuth.aspx" timeout="2880" enableCrossAppRedirects="false" />
<!-- <forms loginUrl="/_layouts/login.aspx" />-->
</authentication>
Why not use
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
This should clear the cookie properly and redirect to login page.

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