SetAuthCookie Setting Cookie, but not IsAuthenticated on Subsequent Requests - asp.net

I have some code where we create an authentication ticket. After creating the ticket, we call SetAuthCookie to set the cookie such as:
FormsAuthentication.SetAuthCookie(username, true);
Response.Redirect("/", true);
If I check on the root page to see if the user is authenticated, it returns false. However, if I hard code the username in and do:
FormsAuthentication.GetAuthCookie("jason", true).value);
I get the appropriate cookie value. So, the cookie exists. But the name and the flag are not modified. Any ideas as to what my issue could be? I'm using ASP.NET 4 and MVC.

Solved
I was missing the forms section in the web.config. It was removed for local testing as the login form resides on another server. So, adding the following to web.config solved my issue:
<authentication mode="Forms" />

Related

FormsAuthentication.SignOut() does not expire the FormsAuthenticationTicket

First off, this is not a problem with the ASP.NET session not expiring, we clear, abandon, and delete every cookie on logout.
This is about FormsAuthentication.SignOut() not expiring the ticket when called and allowing someone who copies the content of the cookie to manually create the cookie somewhere else and still be able to acces everything that is meant to now be blocked off after the logout.
Here is the gist of our logout method:
HttpContext.Current.User = null;
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Session.Clear();
HttpContext.Current.Session.Abandon();
HttpContext.Current.Session.RemoveAll();
HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
We also let ASP manage the creation of the ticket and the authentication via our Web.config and whatever else manages FormsAuthentication. Here is what is in the config:
<authentication mode="Forms">
<forms name="COOKIENAME" loginUrl="~/PAGE_THAT_REDIRECTS_TO_LOGIN.aspx" defaultUrl="~/PAGE_THAT_REDIRECTS_TO_LOGIN_OR_PROPER_PAGE_IF_LOGGED_IN.aspx" cookieless="UseCookies" timeout="60" />
</authentication>
Now, why is this an issue? simple, it's a security concern as if someone gets the cookie and keeps it alive, they can access whatever the user matching the cookie can, even though the user has been disconnected.
Is there is a proper way to force the FormsAuthenticationTicket to expire?
I tried decrypting it, but everything is readonly, and I also tried to create a new expired ticket and encrypting it, but it doesn't overwrite the old one.
Thanks
Versions: .NET 4.5.1, ASP.NET (not Core)
The basic problem is with Microsoft .net Core cookie Managemnt, it does not handle the lifetime of cookies correctly.
I had face this issue several times, and mostly with .Net core now.
To solve this issue we need to override their cookie management class, and implement ITicketStore interface.
https://github.com/aspnet/Security/blob/master/src/Microsoft.AspNetCore.Authentication.Cookies/CookieAuthenticationOptions.cs#L136
Below article can help you with detail implementation.
https://mikerussellnz.github.io/.NET-Core-Auth-Ticket-Redis/
I hope it helps.

Forms Authentication in IE

I have seem a few of these asking the same question but none of the solutions have worked for me thus far so I wanted to see if I am doing something wrong. I have a site that I am using asp.net MVC to create, at current I am using forms authentication to prevent anonymous users from browsing the site. That bit of code is as follows.
<authentication mode="Forms" >
<forms loginUrl="~/login" timeout="15"/>
</authentication>
Then I have a login controller that has the user enter their userName and password then creates an authcookie if the information is accurate.
if (password == encryptedPassword)
{
FormsAuthentication.SetAuthCookie("user", true, model.userName);
}
All of this works in Firefox and Chrome and after the user has logged in he is able to browse the site. However in IE it keeps returning to the log in screen because it keeps recognizing the user as an anonymous user. I checked and the Auth cookie is either never created or doesn't persist as soon as you enter the next page. Some of my attempts to fix this involved using cookieless in the web.config. The only one that works was the one that actually puts the cookie in the URI and we can't have that for the site. Then I tried setting ticketCompatibilityMode="Framework40" but there was no luck there either.
I did see a bug with domain names having non-alpha numerica characters. I currently use the IP to access the domain directly, so I don't know if periods run this problem but even my local host suffers from the same issues. Any input would be appreciated.
Parameters should be in the following order.
FormsAuthentication.SetAuthCookie(model.userName, true, ...);
OR
FormsAuthentication.SetAuthCookie(model.userName, true);
http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.setauthcookie.aspx

asp.net forms authentication redirect problem

The default document feature is turned off in IIS and here's the situation...
My start page for my project say is A.aspx. I run the project and sure enough, A.aspx appears in the url of the browser. Like it should though, A.aspx finds no user logged in and redirects to Login.aspx like it should.
A.aspx:
if (Session["UserStuff"] == null)
Response.Redirect("~/Account/Login.aspx");
The login.aspx shows up BUT when the user Logs in, the code:
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, true);
always redirects to "Default.aspx" and not "A.aspx"
I've examined FormsAuthentication.GetRedirectUrl and sure enough it returns "Default.aspx"
I'm stumped????
In web.config you could set the default page using the defaultUrl attribute:
<authentication mode="Forms">
<forms
loginUrl="login.aspx"
defaultUrl="a.aspx"
protection="All"
timeout="30"
/>
</authentication>
http://www.codeproject.com/KB/aspnet/custom_authentication.aspx Follow this
If you're using FormsAuthentication, your settings should be defined in the web.config. It sounds like you have a default setting in the web.config for DefaultUrl. You shouldn't need the session redirect though. FormsAuthentication should perform this for you. It doesn't hurt to check the session and force a SignOut() if you don't find it, but FormsAuthentication should perform this redirect.
From my understanding, when the user is redirectoed to your login screen, the Forms Authentication mechanism will add the url of the page that the user was originally tring to access, to the login url that that they user tried to access. For example, if you had a login page: http;//bob/login.aspx, and a user tried to access http;//bob/showmethemoney.aspx, then they would get redirected to http;//bob/login.aspx?ReturnUrl=showmethemoney.aspx. So, if you use the ReturnUrl to redirect the user after the user logs in, the user will always be returned to the resource that they were originally trying to get to.

Single Sign-on SignOut problem : FormsAuthentication.SignOut() is not working

I used the Single Sign-on demo from: http://www.codeproject.com/KB/aspnet/SingleSignon.aspx
And I add a SignOut function for this demo, but found a problem:
when I set the cookie.Domain, FormsAuthentication.SignOut() is not working and the cookie can not be cleared.
If the cookie has not been set the cookie.Domain, FormsAuthentication.SignOut() works.
I used C# asp.net.
And could anybody tell me some simple and practical Single Sign-On and Single Sign-Off solutions using asp.net ?
In case you are using the authentication for the same domain and subdomain, try adding the domain name in the web.config instead of adding the domain through code. you will no have to code anything if you use this web.config entry
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" domain="abc.com"/>
</authentication>
This entry tells the asp.net engine that the authentication cookie will be used for all subdomains of abc.com . Try using this and see if it works.
This worked for me:
In the Logout event/ method of each site, use Cookies collection in Request object & delete the relevant cookies as below:
enter code hereHttpCookie cookie = Request.Cookies.Get(".CommonCookieName");
cookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Add(cookie);
If all the sites in SSO use same cookie, then this is simple as described above.
If few or each site participating in SSO use their own cookie/ user name for same subject (person), then u need to remove all the cookies. (perhaps establish a central location with just the mapping of the usernames & cookie names in each site in SSO collection of sites.
This works for me
public virtual ActionResult LogOff()
{
FormsAuthentication.SignOut();
foreach (var cookie in Request.Cookies.AllKeys)
{
Request.Cookies.Remove(cookie);
}
foreach (var cookie in Response.Cookies.AllKeys)
{
Response.Cookies.Remove(cookie);
}
return RedirectToAction(MVC.Home.Index());
}

ASP.NET: Authenticating user in code

I'm playing around with authentication and authorization to prepare for some task. I've created two pages: Login.aspx and Default.aspx. In config file i've set authentication to forms and denied unauthenticated users access:
<authentication mode="Forms">
<forms name="aaa" defaultUrl="~/Login.aspx" />
</authentication>
<authorization>
<deny users="?"/>
</authorization>
Then I've written some simple code to authenticate my user in Login.aspx:
protected void Page_Load(object sender, EventArgs e)
{
GenericIdentity identity = new GenericIdentity("aga", "bbb");
Context.User = new GenericPrincipal(identity, new String[] { "User" }); ;
Response.Redirect("~/Default.aspx");
}
When i run it, the redirection doesn't take place. Instead Login.aspx is called over and over because the user is not authenticated (Context.User.Identity.IsAuthenticated is false at every load). What am i doing wrong?
Context.User only sets the principal for the current request. Once the redirect takes place, the current request ends and a new one begins with the non-overridden principal again (which is apparently not authenticated). So, setting Context.User doesn't actually authenticate anything.
Using FormsAuthentication.SetAuthCookie() will set the user's cookie to a valid value accepted by the FormsAuthentication provider, or put the token in the URL. You can redirect to your heart's content because the cookie obviously sticks with the user for future requests.
From MSDN (em added):
With forms authentication, you can use the SetAuthCookie method when you want to authenticate a user but still retain control of the navigation with redirects.
As stated, this does not necessarily require cookies - the name is a little misleading, because it will still work via the URL if FormsAuthentication is in cookieless mode:
The SetAuthCookie method adds a forms-authentication ticket to either the cookies collection, or to the URL if CookiesSupported is false.
Use FormsAuthentication.SetAuthCookie(..). Or FormsAuthentication.RedirectFromLoginPage(..).
You need to actually set the user as authenticated. All of the following methods will work and let you actually get away from your login screen.
FormsAuthentication.Authenticate()
FormsAuthentication.RedirectFromLoginPage()
FormsAuthentication.SetAuthCookie()
Lots of ways to get to the same result.
You need to actually make a call to the formsAuthentication provider to set the login.
FormsAuthentication.RedirectFromLoginPage(txtUser.Text, chkPersistLogin.Checked)
is a simple example
After creating the dummy Context.User, you need to perform a FormsAuthentication.SetAuthCookie or RedirectFromLoginPage method.

Resources