How to set time logout in MVC - c#

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>

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.

Handle User Session Logout Time With Authentication Forms

I have session table in database where datetime values of login and logout are stored. In my MVC application I am using authentication Forms. Where the cookie is persistent for example 20 minutes with slidingExpiration = true. What is the good practice to ping the session in database and to set accurate logout time. For example when the slidingExpiration fires and reset the expire time of cookie to plus 20 minutes in the same session key. How to handle this in databse to update the logout time of user session ? My end point is to keep accurate logout time of user session in database.
Web.config
<forms loginUrl="/KJH/Account/SignIn" protection="All" timeout="20" name="FedCookie" path="/" requireSSL="false" slidingExpiration="true" defaultUrl="/NCB/Home/Index" cookieless="UseDeviceProfile" enableCrossAppRedirects="false" />
SQL script to update user session
UPDATE dbo.tSession SET LogoutTime = DATEADD(mi, 20, GETDATE()) WHERE Ukey = #Session and LogoutTime > GETDATE()

Increase timeout of an already started session

I want to add a "keep me logged in" option to my custom login control.
This is how I'm currently using the session:
I'm saving and reading values from HttpContext.Current.Session["key"] manually. Works fine.
Relevant parts of web.config:
<sessionState mode="StateServer" useHostingIdentity="true" cookieless="false" timeout="120" stateConnectionString="tcpip=127.0.0.1:42424" />
<authentication mode="Forms">
<forms loginUrl="/login" name="AuthCookie" timeout="120" slidingExpiration="true" path="/" />
</authentication>
<authorization>
<allow users="*" />
</authorization>
As you can see, the default duration of a session is 120 minutes.
"Logout":
Session.Clear();
Session.Abandon();
Through a custom login control with textboxes, I grant access to a member area. (I don't use System.Web.Security.FormsAuthentication)
After entering valid credentials and a checked checkbox "keep logged in", I want to increase the duration of the already active session to ~30 days.
So far I've found solutions like
FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1, "username", DateTime.Now, DateTime.Now.AddMinutes(1), false, "username");
string encTicket = FormsAuthentication.Encrypt(fat);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) { Expires = fat.Expiration });
which don't work, because System.Web.Security.FormsAuthentication.Timeout is still at 120 minutes.
The same goes for setting
Session.Timeout = 666;
Any suggestions?
You can't really approach it this way. You can't persist a session over days - it's just not going to scale well.
What most people do is provide a means for automatic login, so that when their session expires, they are seamlessly logged back in on the next action/reload. Most people do this with a cookie that contains a unique hash, which is checked at the server. If you want the person to be logged in for 30 days, you just set the cookie to expire in 30 days time.
I decided to give a short summary how I ended up doing it, because #David Haney asked me to:
I added a column to my usertable, which contains a GUID that is used for "relogging in" / giving credentials again. That GUID is created upon login and stored in the database.
It's also stored as an ecrypted value in a cookie. (My site doesn't use SSL)
Added to Login routine (if a user checked the "remeber me" checkbox):
HttpCookie aCookie = new HttpCookie("Session");
Guid sessionGuid = // Buisiness layer call to generate value
String sessionID = sessionGuid.ToString();
aCookie.Value = Helper.Protect(sessionID, "sessionID");
aCookie.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(aCookie);
where Helper.Protect and Helper.Unprotect are used from here How to use MachineKey.Protect for a cookie? to store an encrypted and MAC signed value in a cookie.
Relogging is done by having every content page inherit from a class, that implements that logic and inherits from System.Web.UI.Page.
public class BasePage : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Request.Cookies["Session"] != null && !CustomIsLoggedInCheckMethod)
{
String unprotected = Helper.Unprotect(Request.Cookies["Session"].Value, "sessionID");
Guid sessionID = Guid.Parse(unprotected);
// Calls to buisiness layer to get the user, set sessions values et cetera
}
}
}
If a user was banned after the last session or logs out, the cookie value expiration date will be set to a date in the past:
HttpCookie myCookie = new HttpCookie("Session");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
Edit:
Ah I forgot to mention this. I've also added a notification bar, that tells the user that he has been logged back in. It's based on http://blog.grio.com/2012/11/a-copypaste-ble-jquery-notification-bar.html
See Demo

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.

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.

Categories