FBA login page issue in SharePoint - c#

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.

Related

Asp.Net Form Authentication : Session change to other recently login user session automatically

My asp.net webform application Hosted on IIS8 in intranet with Form authentication. For a single user at a time, this application is working completely fine. But problem is with more than one user. Taking example of two users to explain the problem.
The problem is when UserA login to the application and perform any navigation. At the same time other UserB login to the application and perform any navigation. Now at the same time if userA refresh there browser then UserA realize that his session converted into the UserB session(loggedin recently), which is strange and odd as well. Both user on different machine/system and location. I don't know what should i call this problem.
I think there is some point that i am missing in my configuration/code. My code and configuration given below.
In C#, after validating the user credentials, i am using below piece of code
FormsAuthentication.RedirectFromLoginPage(UserId, false);
In Web.config
<sessionState mode="InProc" timeout="20"></sessionState>
<authentication mode="Forms">
<forms name=".ASPXFORMSAUTH" loginUrl="LogIn.aspx" cookieless="UseCookies" requireSSL="false" path="/" timeout="30" defaultUrl="Welcome.aspx" protection="All"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
I am accessing my Hosted application with the following URL:
http://SERVER_NAME:8020/LogIn.aspx
Please suggest, what i am doing wrong or missing any important step.
Try to log the SessionID after logged on successfully so that verify these sessions are the same.
Besides, there is a possibility that generating same authentication ticket during the redirection logic. It depends on how we control cookie generation.
private void cmdLogin_ServerClick(object sender, System.EventArgs e)
{
if (ValidateUser(txtUserName.Value,txtUserPass.Value) )
{
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chkPersistCookie.Checked)
ck.Expires=tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
string strRedirect;
strRedirect = Request["ReturnUrl"];
if (strRedirect==null)
strRedirect = "default.aspx";
Response.Redirect(strRedirect, true);
}
else
Response.Redirect("logon.aspx", true);
}
Check this for more details.
https://support.microsoft.com/en-us/help/301240/how-to-implement-forms-based-authentication-in-your-asp-net-applicatio
Feel free to let me know if the problem still exists.

Correct redirect after log in | ASP.NET

When user requests a page that is only for authenticated users he/she is redirected to login page. I also use authorization based on user role in my nested web.config.
<authorization>
<allow roles="Administrator"/>
<deny users="*"/>
</authorization>
Former solution to this was if user is authenticated redirect him to the page he/she requested, but because user could request a page he/she was not authorized to see website kept returning him to login page over and over.
if (_user != null)
{
HttpContext.Current.Session["UserId"] = _user.Id;
FormsAuthentication.RedirectFromLoginPage(_user.Id.ToString(), false);
}
I do not like this so I did change the code to use Response.Redirect() to route user to his/her login page. Unfortunately I did not realized user can't reach the page he/she requested in the first place and always ends up on "welcome page".
if (_user != null)
{
HttpContext.Current.Session["UserId"] = _user.Id;
var role = _userAuth.GetUserRole(_user.Id); //Gets correct role for a user
if (role == "admin")
{
Response.Redirect("~/adm/Default.aspx");
}
else if (role == "service")
{
Response.Redirect("~/service/Default.aspx");
}
else
{
Response.Redirect("~/user/Welcome.aspx");
}
}
Is there a way how to route the user to the page he/she requested in case he/she is authenticated and authorized and route him/her to page saying "You are not authorized to see this" otherwise?

How to set time logout in MVC

one user login in attendance that user can logout only in after 8 hours.
How should code in MVC Jquery.
var usrtime = ctx.Attendances.Select(s => s.Time && s.Id == Id);
This way i get user login time.
Try
if (logoutTime > usrtime) {
window.location.href = '#Url.Action("ActionName", "ControllerName")';
}
then in the action log the user out and redirect them to login
Please clarify your scenario in a better way. A user logout depends on cookie expiration or token expiration or other ways. Control timeout time of cookie.
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" slidingExpiration="true" timeout="480" />
</authentication>

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

How can I expire the session when the user doesn't work with website?

Hello, I created a web site application with asp.net 4.5 and asp.net membership. I want user session to be expire if the user doesn't work with site (like Facebook).
I have set the timeout in web.config for the session but this time gets finished (times out), either if user works or doesn't work. Is there something I'm missing?
<authentication mode="Forms">
<forms loginUrl="~/Pages/Login.aspx" slidingExpiration="true" timeout="1"></forms>
</authentication>
While setting the forms auth cookie you need to set an expiry time for the cookie and create a http module in your application where you check the auth cookie in the request headers and if its not present you logout the user and redirect to the login page. And if the cookie exists just reset the expiry time for the cookie in the response.
Refer to this link. This is an answered that I'm currently help with another user. This should show you how to make the session start once the user logs in.
Edit: Not sure why the downvote, but here is code then.
Change the timeouts on each of the forms authentication and sessionState like below.
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" defaultUrl="~/Dashboard.aspx" timeout="60"/>
</authentication>
<sessionState timeout="60" mode="InProc" cookieless="false" />
Then, put this into your Site.Master.cs under the page load.
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
// Handle the session timeout
string sessionExpiredUrl = Request.Url.GetLeftPart(UriPartial.Authority) + "/DealLog/Account/SessionExpired.aspx";
StringBuilder script = new StringBuilder();
script.Append("function expireSession(){ \n");
script.Append(string.Format(" window.location = '{0}';\n", sessionExpiredUrl));
script.Append("} \n");
script.Append(string.Format("setTimeout('expireSession()', {0}); \n", this.Session.Timeout * 60000)); // Convert minutes to milliseconds
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "expirescript", script.ToString(), true);
}
The session will only expire if the user is authenticated. The user logs in, becomes inactive, and then session times out. Once it times out, goes to an SessionExpired page. On the session expired page, place
FormsAuthentication.SignOut();
in the page load so it signs out the user. Then you can set up a redirect from there. The Authentication and SessionState timeouts are both in minutes. 60 = 1 hour.
Edit 2: It looks like the user of the question that was linked in my answer was deleted by the user. Sorry for that. Hope this helps though.

Categories