Log out asp.net incomplete - asp.net

I'm having this annoying problem that when i log out from asp mvc web application it's not working to
logging again.
Log out method looks like:
private static void LogOut()
{
FormsAuthentication.SignOut();
Session.Clear();
Session.Abandon();
Response.Cookies.Clear();
Response.Redirect("~/Login.aspx");
}
is that cookies does not allow to login again?

You set the cookie expiry date to past to make the cookie invalid.
FormsAuthentication.SignOut();
Session.Abandon();
// clear authentication cookie using expiration date
HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
cookie1.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie1);
// clear session cookie, if needed
HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
cookie2.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie2);
FormsAuthentication.RedirectToLoginPage();
Forms Authentication Methods

Related

GenericPrincipal IsInRole returns false for HttpContext.User

I have a credential method to set user credentials via GenericPrincipal. I am using asp.net MVC
public void SetCredentials(HttpContextBase context, string username, bool createPersistenceCookie)
{
FormsAuthentication.SetAuthCookie(username, createPersistenceCookie);
IIdentity identity = new GenericIdentity(username);
IPrincipal principal = new GenericPrincipal(identity,new []{"standart"});
context.User = principal;
}
I want to check User.IsInRole("standart") in controller action, but it returns false.
context.User.IsInRole("standart") //returns false
I want to use context.User in my application, but it returns always false.
I think you used asp.net membership api before. And now you want to create custom principal in your application.
When you send request to server, server uses a new clean HttpContext. So you lost your old informations. If you want to use old session informations is application, you shuld save your data in server or client side. You can do this two way.
Client cookie
Server session
I recommand you to use client cookies. Because data is being stored to client side, so you save server resources.
public void SetCredentials(HttpContextBase context, string username, bool createPersistenceCookie)
{
var formsAuthenticationTicket = new FormsAuthenticationTicket(
1,
username,
DateTime.Now,
DateTime.Now.AddMilliseconds(FormsAuthentication.Timeout.TotalMilliseconds),
createPersistenceCookie,
roles
);
var encryptedTicket = FormsAuthentication.Encrypt(formsAuthenticationTicket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
HttpContext.Current.Response.AppendCookie(authCookie);
}
I sended encrypted cookie to client side. And I should check this cookie all incoming request to server application.
And now in Global.asax file:
protected void Application_AuthenticateRequest(object sender, System.EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null) return;
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
IIdentity identity = new GenericIdentity(ticket.Name);
IPrincipal principal = new GenericPrincipal(identity, ticket.UserData.Split('|'));
HttpContext.Current.User = principal;
}
I hope solve your issue.

ASP.NET Formauthentication.Signout() not working

I am using forms authentication for a web site I am building and it works out pretty well except I cannot get the auth cookie to delete or expire. I have tried any number of methods and none of them seem to work. Here is what I create the cookie.
FormsAuthentication.SetAuthCookie(model.userName, false);
HttpCookie cookie = new HttpCookie("user");
Response.Cookies["user"].Value = model.userName;
Now the second cookie isn't an actual authcookie, that is used for some of the inner workings of the site per client request. This next part are various things I have tried to delete the cookie.
FormsAuthentication.SignOut();
Roles.DeleteCookie();
Session.Clear();
//Response.Cache.SetExpires(DateTime.Now);
//foreach (var cookie in Request.Cookies.AllKeys)
//{
// Request.Cookies.Remove(cookie);
//}
//foreach (var cookie in Response.Cookies.AllKeys)
//{
// Response.Cookies.Remove(cookie);
//}
//Session.Abandon();
//// clear authentication cookie
HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
cookie1.Path = FormsAuthentication.FormsCookiePath;
cookie1.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie1);
HttpCookie cookie = Request.Cookies["user"];
string userName = cookie.Value;
cookie.Expires.AddDays(-30);
//HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
//cookie2.Expires = DateTime.Now.AddYears(-1);
//Response.Cookies.Add(cookie2);
//HttpCookie cookie = Request.Cookies["user"];
//cookie.Expires = DateTime.Now.AddDays(-1d);
//HttpCookie user = Request.Cookies["user"];
//role.Expires = DateTime.Now.AddDays(-1d);
//Response.Cookies["user"].Value = null;
Session.Abandon();
I just cut and paste the entire thing in there, some of it is commented out now but at some point and time I have attempted to use each method in that code to remove the cookie. Some of these attempts were just guesses since I have been at this for a while. Last here is the auth section of my web.config
<authentication mode="Forms" >
<forms loginUrl="~/login" timeout="90" name=".ASPXFORMS" />
</authentication>
Any input as to what I am doing wrong is appreciated.
Try calling
FormsAuthentication.SignOut()
Before calling session. I generally place this in a separate method to make it easy to call from multiple places. Something like this:
internal void SignOut(HttpContext context)
{
FormsAuthentication.SignOut();
HttpSessionState session = context.Session;
if(session != null)
{
session.Abandon();
}
}

Asp.net form login Impossible when client date time differ from server

FormsAuthenticationUserData userData = new FormsAuthenticationUserData(member.Id, member.Role, member.Gender);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, member.UserName, DateTime.Now, DateTime.Now.AddHours(24), true, userData.Serialize());
string encTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
faCookie.Expires = DateTime.Now.AddHours(25);
Response.Cookies.Add(faCookie);
string redirectUrl = FormsAuthentication.GetRedirectUrl(member.UserName, false);
Response.Redirect(redirectUrl, true);
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
try
{
WebIdentity identity = new WebIdentity(authTicket.Name, authTicket.UserData);
WebPrincipal currentMember = new WebPrincipal(identity);
Context.User = currentMember;
}
catch
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
Response.End();
}
}
}
the user cannot login when client date time is greater than server date time (make cookie null and cannot login)
what is solution?
thanx a lot!
After reading your comment, this is expected behaviour that cannot be changed. The system is doing what it is meant to. You could set the cookie expire later or use a rolling timeout, however, I see no reason for the machine datetime to be out by so far.
This technique avoids using the browser's date/time completely.
Set the FormsAuthentication cookie to never expire, or to expire after 100 years.
Store the actual expiration based on server time in the authenticationTicket.Expiration property. See here.
After the server authenticates a request, it should check the authenticationTicket.Expiration to see if it has expired. I'm not 100% sure the system does this automatically, you may have to hook into the Application_AuthenticateRequest event and do it yourself.
If it has expired, the web server should deny the request; render an HTTP 403 status code and a set-cookie header to remove the cookie at that point.

How to intercept an authentication request in ASP.net webform

I have user's who are losing their data because they sit on a page too long, then are asked to log back in. I want to do the following:
1) Instead of redirecting them to a login page, I want to cancel the current request and give the user a popup dialog box to login with.
2) When the login is successful, I want the user to be sent back to their form, with all data intact. (Even better if the request could go through without sending them back to that form, but this is optional).
How can I intercept these authentication requests, and present the user with a popup login?
I am using ASP.net forms authentication.
You can intercept this event on Application_AuthenticateRequest in Global.asax
But, you need be more specific, are you using the ASP.NET Forms Authentication?
Added:
Try this and reply me
In Global.asax
void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.User == null)
{
FormsAuthenticationTicket ticket = new
FormsAuthenticationTicket(1, "Anonymous", DateTime.Now, DateTime.Now.AddMinutes(30), false, "Anonymous");
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie =
new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(cookie);
FormsIdentity id = new FormsIdentity(ticket);
System.Security.Principal.GenericPrincipal principal = new System.Security.Principal.GenericPrincipal(id, ticket.UserData.Split(new char[] { '|' }));
Context.User = principal;
}
}
In a web form
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket.UserData == "Anonymous")
{
//Throw the login popup
}
else
{
//Some Code
}
Are you using a master page? You could redirect to there when login is required, not a separate login page. In the login code in the master page you then decided whether to redirect to a proper, standalone login page, or make a login div visible as a popup.

ASP.NET Updating the FormsAuthenticationTicket

When a user logins into my site i create the following authenticate ticket:
// Create the authentication ticket
var authTicket = new FormsAuthenticationTicket(1, // Version
userName, // Username
DateTime.UtcNow, // Creation
DateTime.UtcNow.AddMinutes(10080), // Expiration
createPersistentCookie, // Persistent
user.Role.RoleName + "|~|" + user.UserID + "|~|" + user.TimeZoneID); // Additional data
// Encrypt the ticket
var encTicket = FormsAuthentication.Encrypt(authTicket);
// Store the ticket in a cookie
HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) { Expires = authTicket.Expiration });
Then in my Global.asax.cs file i have the following:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
// Get the authentication cookie
var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
// If it exists then decrypt and setup the generic principal
if (authCookie != null && !string.IsNullOrEmpty(authCookie.Value))
{
var ticket = FormsAuthentication.Decrypt(authCookie.Value);
var id = new UserIdentity(ticket); // This class simply takes the value from the cookie and then sets the properties on the class for the role, user id and time zone id
var principal = new GenericPrincipal(id, new string[] { id.RoleName });
HttpContext.Current.User = principal;
}
}
protected void Session_Start(object sender, EventArgs e)
{
// If the user has been disabled then log them out
if (Request.IsAuthenticated)
{
var user = _userRepository.Single(u => u.UserName == HttpContext.Current.User.Identity.Name);
if (!user.Enabled)
FormsAuthentication.SignOut();
}
}
So far so good. The problem i have is that if an administrator changes a user's role or time zone then the next time they return to the site their ticket is not updated (if they selected remember me when logging in).
Here's my authentication settings incase it helps:
<authentication mode="Forms">
<forms timeout="10080" slidingExpiration="true" />
</authentication>
<membership userIsOnlineTimeWindow="15" />
I've been reading up on slidingExpiration but as far as i can tell it only increases the expiration time and doesn't renew the contents of the cookie. I'd really appreciate it if someone could help. Thanks
I simply changed my Session_Start to:
// If the user is disabled then log them out else update their ticket
if (Request.IsAuthenticated)
{
var user = _userRepository.Single(u => u.UserName == HttpContext.Current.User.Identity.Name);
if (!user.Enabled)
FormsAuthentication.SignOut();
else
RenewTicket(); // This calls the same code to create the cookie as used when logging in
}
My proposal would be to do another cookie for the remember.
This way session info can be in-memory cookie, while remember me cookie can be set to persist.

Resources