User not logged in when WWW. is on URL - c#

If I visit my site with out the www. prefix, login and then add the www., my user is not logged in any more, but if I remove the www., the user is logged in. It acts the same way if I do the Opposite. go to the web site with the www., login, and then remove the www. the user will not be logged in.
Here is the Login method and the authentication at the web.config.
public static void LogIn(userId)
{
Item user = Framework.Business.Item.Load(userId);
var _ticket = new FormsAuthenticationTicket(1, _usrItm.ID, DateTime.Now, DateTime.Now.AddDays(30), true, _usrItm.ID);
string encTicket = FormsAuthentication.Encrypt(_ticket);
HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
}
<authentication mode="Forms">
<forms name="k_Authentication" protection="All" timeout="120" cookieless="UseCookies" loginUrl="default.aspx" path="/" defaultUrl="/myweb.aspx"/>
</authentication>

I'll bet you a shilling to a guinea that the two answers about the domain setting of the cookies are correct +1s all around from me.
However. Most often the two sites are the same or they are not. If they're not, then you usually want the user to no longer be logged in, so don't change anything. If they are the same, then set one to permanently redirect to the other. As well as making this problem go away, you also gain some SEO benefits, benefits for people's history records being more consistent, and reduced pressure on shared caches. So I'd suggest that approach. I'd only deal with the matter of the domain set on the cookie if the two are separate-but-related, and sharing the log-in between them is appropriate.

There is probably a problem with the domain of your cookie. www.example.com and example.com are not the same domain.
You'll have to set the Domain property to www.yourdomain.com manually to share the cookies.

Related

Stop session from expiring when browser closes in MVC

I am facing a session issue After I close my browser my session expires, and after re-open browser, I have to log in again.
I don't want to expire my session on browser close.
I am using this in my web.config file:
<authentication>
<forms loginUrl="~/account/login" name="astroswamig" slidingExpiration="true" timeout="1000"></forms>
</authentication>
<sessionState mode="StateServer" cookieless="false" timeout="1000" />
and this in my controller:
string str = JsonConvert.SerializeObject(user);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.CustEmail, DateTime.Now, DateTime.Now.AddDays(120), true, str);
string enctryptTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authCustCookie = new HttpCookie(FormsAuthentication.FormsCookieName, enctryptTicket);
authCustCookie.Domain = "xyz.com";
Response.Cookies.Add(authCustCookie);
The web.config sample in the question is using StateServer mode, so the out-of-process ASP.NET State Service is storing state information. You will need to configure the State Service; see an example of how to do that in the "STATESERVER MODE(OUTPROC MODE)" section here:
https://www.c-sharpcorner.com/UploadFile/484ad3/session-state-in-Asp-Net/
Also be sure to read the disadvantages section of the above linked article to make sure this approach is acceptable for your needs.
Another way to manage user session is using the InProc mode to manage sessions via a worker process. You can then get and set HttpSessionState properties as shown here:
https://www.c-sharpcorner.com/UploadFile/3d39b4/inproc-session-state-mode-in-Asp-Net/
and also here:
https://learn.microsoft.com/en-us/dotnet/api/system.web.sessionstate.httpsessionstate?view=netframework-4.8#examples
Again be sure to note the pros and cons of InProc mode in the above linked article to determine what approach best fits your needs.

How do I log a user out when they close their browser or tab in ASP.NET MVC?

I need to sign out a user when the user closed the tab or browser, how do I do that in ASP.NET MVC?
There are a few things you can do to make sure the user is signed out when the browser is closed, but it depends on how you're setting the FormsAuthentication cookie:
Use Cookieless=True.
Set a FormsAuthenticationTicket to not be persistent
Use FormsAuthentication.SetAuthCookie to set Persistence to false
Use a JavaScript approach to remove the cookie on window.unload.
Cookieless=True approach:
<system.web>
<authentication mode="Forms">
<forms loginUrl="/Account/Login"
protection="All"
cookieless="true" //set to true
</authentication>
</system.web>
This appends the cookie value to the querystring in each request. The problem with this approach is it's not very secure and it messes with SEO. If a user sends anyone the URL they're using, that person can log in as the original user (probably not what you want). As far as 'messing with SEO', it causes the same page to look different to a googlebot based on what URL is passed in. Each QueryString change makes it a new URL, and if anyone uses this for posting a link; it will dilute the search results for a given actual URL.
FormsAuthenticationTicket Approach
When you set an Authentication cookie for the user, set Persistent to False.
If you're doing this in the FormsAuthentication.SetAuthCookie, this is default. If you use the FormsAuthenticationTicket class, you have to specify the cookie expiration.
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, //version
"blah", //Cookie Name
);
FormsAuthentication.SetAuthCookie() Approach
By default, if you don't set persistent, the authentication cookie will expire at the end of the session (when the user closes the browser).
FormsAuthentication.SetAuthCookie("CookieValue", false); //second argument is persistent'
JavaScript approach:
There are no foolproof methods; all you can do is set the cookie expiration date to before now and hope the user's browser co-operates. If you really, really, really, want the cookie gone, you can always try a JavaScript approach, but that won't work if the user has JavaScript disabled.
window.addEventListener('unload', function(event) {
document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
});
Other caveats
It also matters which browser you use. Chrome has the ability to run in the background, and that keeps Session Cookies around until their timeout is hit -- they are not dropped when the browser is closed (I found this out the hard way).

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.

HttpContext.Current.User.Identity.IsAuthenticated returns false

I have a strange issue.
I have a page with the following code.
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
Server.Transfer(#"~/Views/Public/Unauthorised.aspx");
return;
}
For some reason, with one user (and we've narrowed it down to his single machine and windows logon profile), IsAuthenticated always returns false. Even though he is logged into the website, and can navigate to other pages that require authenticated user. Except this one page.
We checked that the machine accepts all cookies and we still get the same issue. I'm not sure where to go from here... any suggestions?
There are at least two known cases that can make this behavior.
First case when you have set requireSSL="true" on the Authentication session on web.config and you call that function from a non secure page. So double check if the page is secure or not, if you use the requireSSL="true"
Debug.Assert(Request.IsSecureConnection, "The IsAuthenticated will fail.");
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
Server.Transfer(#"~/Views/Public/Unauthorised.aspx");
return;
}
Second case when you do not have set the domain="site.com" again on authentication session inside the web.config, and you try to request a cookie the one time from the www.yoursitename.com and the other from yoursitename.com. In that case the authentication cookies are different and it will fail. So set that parameter among others on web.config.
<authentication mode="Forms">
<forms domain="yoursitename.com" />
</authentication>

Categories