Is there a browser equivalent to IE's ClearAuthenticationCache? - asp.net

I have a few internal .net web application here that require users to "log out" of them. I know this may seem moot on an Intranet application, but nonetheless it is there.
We are using Windows authentication for our Intranet apps, so we tie in to our Active Directory with Basic Authentication and the credentials get stored in the browser cache, as opposed to a cookie when using .net forms authentication.
In IE6+ you can leverage a special JavaScript function they created by doing the following:
document.execCommand("ClearAuthenticationCache", "false")
However, for the other browsers that are to be supported (namely Firefox at the moment, but I strive for multi-browser support), I simply display message to the user that they need to close their browser to log out of the application, which effectively flushes the application cache.
Does anybody know of some commands/hacks/etc. that I can use in other browsers to flush the authentication cache?

I've come up with a fix that seems fairly consistent but is hacky and I'm still not happy with it.
It does work though :-)
1) Redirect them to a Logoff page
2) On that page fire a script to ajax load another page with dummy credentials (sample in jQuery):
$j.ajax({
url: '<%:Url.Action("LogOff401", new { id = random })%>',
type: 'POST',
username: '<%:random%>',
password: '<%:random%>',
success: function () { alert('logged off'); }
});
3) That should always return 401 the first time (to force the new credentials to be passed) and then only accept the dummy credentials (sample in MVC):
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LogOff401(string id)
{
// if we've been passed HTTP authorisation
string httpAuth = this.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(httpAuth) &&
httpAuth.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
{
// build the string we expect - don't allow regular users to pass
byte[] enc = Encoding.UTF8.GetBytes(id + ':' + id);
string expected = "basic " + Convert.ToBase64String(enc);
if (string.Equals(httpAuth, expected, StringComparison.OrdinalIgnoreCase))
{
return Content("You are logged out.");
}
}
// return a request for an HTTP basic auth token, this will cause XmlHttp to pass the new header
this.Response.StatusCode = 401;
this.Response.StatusDescription = "Unauthorized";
this.Response.AppendHeader("WWW-Authenticate", "basic realm=\"My Realm\"");
return Content("Force AJAX component to sent header");
}
4) Now the random string credentials have been accepted and cached by the browser instead. When they visit another page it will try to use them, fail, and then prompt for the right ones.

A couple of notes. A few people have said that you need to fire off a ajax request with invalid credentials to get the browser to drop it's own credentials.
This is true but as Keith pointed out, it is essential that the server page claims to accept these credentials for this method to work consistently.
On a similar note: It is NOT good enough for your page to just bring up the login dialog via a 401 error. If the user cancels out of the dialog then their cached credentials are also unaffected.
Also if you can please poke MOZILLA at https://bugzilla.mozilla.org/show_bug.cgi?id=287957 to add a proper fix for FireFox. A webkit bug was logged at https://bugs.webkit.org/show_bug.cgi?id=44823. IE implements a poor but functional solution with the method:
document.execCommand("ClearAuthenticationCache", "false");
It is unfortunate that we need to go to these lengths just to log out a user.

Mozilla implemented the crypto object, available via the DOM window object, which has the logout function (Firefox 1.5 upward) to clear the SSL session state at the browser level so that "the next private operation on any token will require the user password again" (see this).
The crypto object seems to be an implementation of the Web Crypto API, and according to this document, the DOMCrypt API will add even more functions.
As stated above Microsoft IE (6 upward) has:
document.execCommand("ClearAuthenticationCache", "false")
I have found no way of clearing the SLL cache in Chrome (see this and this bug reports).
In case the browser does not offer any API to do this, I think the better we can do is to instruct the user to close the browser.
Here's what I do:
var agt=navigator.userAgent.toLowerCase();
if (agt.indexOf("msie") !== -1) {
document.execCommand("ClearAuthenticationCache","false");
}
//window.crypto is defined in Chrome, but it has no logout function
else if (window.crypto && typeof window.crypto.logout === "function"){
window.crypto.logout();
}
else{
window.location = "/page/to/instruct/the/user/to/close/the/browser";
}

I've been searching for a similar solution and came across a patch for Trac (an issue management system) that does this.
I've looked through the code (and I'm tired, so I'm not explaining everything); basically you need to do an AJAX call with guaranteed invalid credentials to your login page. The browser will get a 401 and know it needs to ask you for the right credentials next time you go there. You use AJAX instead of a redirect so that you can specify incorrect credentials and the browser doesn't popup a dialog.
On the patch (http://trac-hacks.org/wiki/TrueHttpLogoutPatch) page they use very rudimentary AJAX; something better like jQuery or Prototype, etc. is probably better, although this gets the job done.

Why not use FormsAuth, but against ActiveDirectory instead as per the info in this thread. It's just as (in)secure as Basic Auth, but logging out is simply a matter of blanking a cookie (or rather, calling FormsAuthentication.SignOut)

Well, I've been browsing around Bugzilla for a bit now and seemingly the best way you can go for clearing the authentication would be to send non-existant credentials.
Read more here: https://bugzilla.mozilla.org/show_bug.cgi?id=287957

Hopefully this will be useful until someone actually comes along with an explicit answer - this issue was discussed two years ago on a message board.
HTH

Related

AAD Graph API returns 404 after call to AcquireTokenAsync, but not after call to AcquireTokenSilentAsync

So I have an application that's calling the graph API.
See the following snippet:
When the try (AquireTokenSilent) is called, the Web Request completes successfully no problem.
However, when make the same web request with the token I get from AcquireTokenAsync, I'm getting a 404 error and an exception thrown.
1) Can you recommend some good tools to analyze the HTTP request (so I can compare the difference and identify a problem). The Visual Studio debugger is helpful, but I can't see the whole picture, which obfuscates a possible problem here.
2) Can you help me identify why exactly one is successful and one fails? Both tokens seem to be acquired successfully, so I'm not sure what the problem is.
So I have figured out what was the underlying cause here.
In our authentication scenario, we have multiple products using azure AD SSO in the ecosystem. Since 'OnAuthorizationCodeReceived' is only called on login, and NOT when a valid login cookie is already held, the token cache will not be populated with the authorization code. So in this case, the Microsoft code samples for this scenario are dead wrong. Issuing an authentication challenge wont cause 'OnAuthorizationCodeReceived' to be called, as you already hold a valid login token.
So, while it's a litte ugly, the fix is dead simple. Force a logout, so that the token cache can be populated.
catch (AdalSilentTokenAcquisitionException e)
{
//in this case, it's possible there's no authorization code because the login cookie is from another session in
//the ecosystem. So in this scenario, force a logout so we can get a token into the tokencache
context.GetOwinContext().Authentication.SignOut(OpenIdConnectAuthenticationDefaults.AuthenticationType,
CookieAuthenticationDefaults.AuthenticationType);
sessionState.Abandon();
}
Now, because we're using this code outside the Controllers, and we call await, HttpContext will be null. Some serious voodoo going on in HttpContext, but I digress. We can use this little workaround to hang onto the context:
var context = HttpContext.Current;
var sessionState = context.Session;
EDIT: Came across one more problem when deploying the application to an azure app-service. You want to make sure Azure AD Authentication is toggle on in the 'Authentication' panel on Azure. We had some infinite login loop problems until I toggled this.
EDIT:
So, forcing a logout in this scenario really didn't sit well with me. BUT, I came across this question:
Azure Active Directory Graph API - access token for signed in user
And what we can do is follow the answer, and call AcquireTokenByAuthorizationCodeAsync(...), and make sure to use the 4 parameter method overload, where the last param is "https://graph.windows.net/"
Now, as long as we store the authorization code somewhere (in my case stored in a DB table). We should be able to get the authorization code for a given user, and get a new GraphAPI token, in the case where AcquireTokenSilentAsync(...) fails.
Now your statefull tokencache can be backed up by a stateless database call!
catch (AdalSilentTokenAcquisitionException e)
{
//in this case, the stateful cache is empty, so lets get the codeId from the DB
PersistentTokenCache pt = db.PersistentTokenCaches.Find(userObjectId);
if (pt != null && pt.token != null)
{
try
{
result = await ath.AcquireTokenByAuthorizationCodeAsync(pt.token,
new Uri(Startup.hostUri),
cc,
"https://graph.windows.net");
}
catch (AdalException ex)
{
Debug.WriteLine(ex.StackTrace);
//both authentication types have failed
pt.token = null;
await db.SaveChangesAsync();
context.GetOwinContext().Authentication.SignOut(OpenIdConnectAuthenticationDefaults.AuthenticationType,
CookieAuthenticationDefaults.AuthenticationType);
sessionState.Abandon();
return -1;
}
}
}

IIS Conditional authentication with the Windows Authentication module

I have an unusual situation in which authentication isn't necessary but where learning the user-id via windows authentication under certain conditions would be useful.
To give some context, I want to be able to require windows authentication when the user-agent matches certain conditions, but not require authentication in other conditions. With only some familiarity with asp.net and iis I suspect I am missing an easy way of accomplishing this. So far I've looked into writing a module that checks the user-agent and then adds the WindowsAuthenticationModule if the conditions are met - but I can't figure out how to do this.
Any suggestions the best way to auth or not auth on the value of the user-agent?
If you setup IIS to use windows authentication, you should be able to do something like the following code snippet.
However, as you may guess from the comments in the code, I would advise against it. The User Agent is easily spoofed - so any authentication checks you do based on it can also easily be bypassed. The same holds true for pretty much anything that comes across in an http header (e.g., basing authentication on http referrer is also a bad idea).
string windowsUserName = null;
var currentContext = System.Web.HttpContext.Current;
//NOT SECURE - easily spoofed!
if (currentContext.Request.UserAgent == "Some special user agent")
{
if (!currentContext.User.Identity.IsAuthenticated
|| currentContext.User.Identity.AuthenticationType != "Windows")
{
throw new SecurityException(#"You are not authorized, but you can easily
hack this application by modifying the user agent that you send to the server.")
}
windowsUserName = User.Identity.Name;
}
So in short, even if the above works, don't do it. You really need to completely rethink how you are authenticating your application.
If, as you seem to indicate in the first sentence of your question, this is purely informational, then it may be ok (e.g. if it is just for debugging purposes). However, it would not be suitable e.g. for auditing or restricting access to any resources, and you must be extremely careful that this code doesn't get reused in any real security context.

ASP.NET: Session.SessionID changes between requests

Why does the property SessionID on the Session-object in an ASP.NET-page change between requests?
I have a page like this:
...
<div>
SessionID: <%= SessionID %>
</div>
...
And the output keeps changing every time I hit F5, independent of browser.
This is the reason
When using cookie-based session state, ASP.NET does not allocate storage for session data until the Session object is used. As a result, a new session ID is generated for each page request until the session object is accessed. If your application requires a static session ID for the entire session, you can either implement the Session_Start method in the application's Global.asax file and store data in the Session object to fix the session ID, or you can use code in another part of your application to explicitly store data in the Session object.
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.sessionid.aspx
So basically, unless you access your session object on the backend, a new sessionId will be generated with each request
EDIT
This code must be added on the file Global.asax. It adds an entry to the Session object so you fix the session until it expires.
protected void Session_Start(Object sender, EventArgs e)
{
Session["init"] = 0;
}
There is another, more insidious reason, why this may occur even when the Session object has been initialized as demonstrated by Cladudio.
In the Web.config, if there is an <httpCookies> entry that is set to requireSSL="true" but you are not actually using HTTPS: for a specific request, then the session cookie is not sent (or maybe not returned, I'm not sure which) which means that you end up with a brand new session for each request.
I found this one the hard way, spending several hours going back and forth between several commits in my source control, until I found what specific change had broken my application.
In my case I figured out that the session cookie had a domain that included www. prefix, while I was requesting page with no www..
Adding www. to the URL immediately fixed the problem. Later I changed cookie's domain to be set to .mysite.com instead of www.mysite.com.
my problem was that we had this set in web.config
<httpCookies httpOnlyCookies="true" requireSSL="true" />
this means that when debugging in non-SSL (the default), the auth cookie would not get sent back to the server. this would mean that the server would send a new auth cookie (with a new session) for every request back to the client.
the fix is to either set requiressl to false in web.config and true in web.release.config or turn on SSL while debugging:
Using Neville's answer (deleting requireSSL = true, in web.config) and slightly modifying Joel Etherton's code, here is the code that should handle a site that runs in both SSL mode and non SSL mode, depending on the user and the page (I am jumping back into code and haven't tested it on SSL yet, but expect it should work - will be too busy later to get back to this, so here it is:
if (HttpContext.Current.Response.Cookies.Count > 0)
{
foreach (string s in HttpContext.Current.Response.Cookies.AllKeys)
{
if (s == FormsAuthentication.FormsCookieName || s.ToLower() == "asp.net_sessionid")
{
HttpContext.Current.Response.Cookies[s].Secure = HttpContext.Current.Request.IsSecureConnection;
}
}
}
Another possibility that causes the SessionID to change between requests, even when Session_OnStart is defined and/or a Session has been initialized, is that the URL hostname contains an invalid character (such as an underscore). I believe this is IE specific (not verified), but if your URL is, say, http://server_name/app, then IE will block all cookies and your session information will not be accessible between requests.
In fact, each request will spin up a separate session on the server, so if your page contains multiple images, script tags, etc., then each of those GET requests will result in a different session on the server.
Further information: http://support.microsoft.com/kb/316112
My issue was with a Microsoft MediaRoom IPTV application. It turns out that MPF MRML applications don't support cookies; changing to use cookieless sessions in the web.config solved my issue
<sessionState cookieless="true" />
Here's a REALLY old article about it:
Cookieless ASP.NET
in my case it was because I was modifying session after redirecting from a gateway in an external application, so because I was using IP instead on localhost in that page url it was actually considered different website with different sessions.
In summary
pay more attention if you are debugging a hosted application on IIS instead of IIS express and mixing your machine http://Ip and http://localhost in various pages
In my case this was happening a lot in my development and test environments. After trying all of the above solutions without any success I found that I was able to fix this problem by deleting all session cookies. The web developer extension makes this very easy to do. I mostly use Firefox for testing and development, but this also happened while testing in Chrome. The fix also worked in Chrome.
I haven't had to do this yet in the production environment and have not received any reports of people not being able to log in. This also only seemed to happen after making the session cookies to be secure. It never happened in the past when they were not secure.
Update: this only started happening after we changed the session cookie to make it secure. I've determined that the exact issue was caused by there being two or more session cookies in the browser with the same path and domain. The one that was always the problem was the one that had an empty or null value. After deleting that particular cookie the issue was resolved. I've also added code in Global.asax.cs Sessin_Start method to check for this empty cookie and if so set it's expiration date to something in the past.
HttpCookieCollection cookies = Response.Cookies;
for (int i = 0; i < cookies.Count; i++)
{
HttpCookie cookie = cookies.Get(i);
if (cookie != null)
{
if ((cookie.Name == "ASP.NET_SessionId" || cookie.Name == "ASP.NET_SessionID") && String.IsNullOrEmpty(cookie.Value))
{
//Try resetting the expiration date of the session cookie to something in the past and/or deleting it.
//Reset the expiration time of the cookie to one hour, one minute and one second in the past
if (Response.Cookies[cookie.Name] != null)
Response.Cookies[cookie.Name].Expires = DateTime.Today.Subtract(new TimeSpan(1, 1, 1));
}
}
}
This was changing for me beginning with .NET 4.7.2 and it was due to the SameSite property on the session cookie. See here for more info: https://devblogs.microsoft.com/aspnet/upcoming-samesite-cookie-changes-in-asp-net-and-asp-net-core/
The default value changed to "Lax" and started breaking things. I changed it to "None" and things worked as expected.
Be sure that you do not have a session timeout that is very short, and also make sure that if you are using cookie based sessions that you are accepting the session.
The FireFox webDeveloperToolbar is helpful at times like this as you can see the cookies set for your application.
Session ID resetting may have many causes. However any mentioned above doesn't relate to my problem. So I'll describe it for future reference.
In my case a new session created on each request resulted in infinite redirect loop. The redirect action takes place in OnActionExecuting event.
Also I've been clearing all http headers (also in OnActionExecuting event using Response.ClearHeaders method) in order to prevent caching sites on client side. But that method clears all headers including informations about user's session, and consequently all data in Temp storage (which I was using later in program). So even setting new session in Session_Start event didn't help.
To resolve my problem I ensured not to remove the headers when a redirection occurs.
Hope it helps someone.
I ran into this issue a different way. The controllers that had this attribute [SessionState(SessionStateBehavior.ReadOnly)] were reading from a different session even though I had set a value in the original session upon app startup. I was adding the session value via the _layout.cshtml (maybe not the best idea?)
It was clearly the ReadOnly causing the issue because when I removed the attribute, the original session (and SessionId) would stay in tact. Using Claudio's/Microsoft's solution fixed it.
I'm on .NET Core 2.1 and I'm well aware that the question isn't about Core. Yet the internet is lacking and Google brought me here so hoping to save someone a few hours.
Startup.cs
services.AddCors(o => o.AddPolicy("AllowAll", builder =>
{
builder
.WithOrigins("http://localhost:3000") // important
.AllowCredentials() // important
.AllowAnyMethod()
.AllowAnyHeader(); // obviously just for testing
}));
client.js
const resp = await fetch("https://localhost:5001/api/user", {
method: 'POST',
credentials: 'include', // important
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
Controllers/LoginController.cs
namespace WebServer.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
[HttpPost]
public IEnumerable<string> Post([FromBody]LoginForm lf)
{
string prevUsername = HttpContext.Session.GetString("username");
Console.WriteLine("Previous username: " + prevUsername);
HttpContext.Session.SetString("username", lf.username);
return new string[] { lf.username, lf.password };
}
}
}
Notice that the session writing and reading works, yet no cookies seem to be passed to the browser. At least I couldn't find a "Set-Cookie" header anywhere.

Adobe air http auth

I have a question about HTTP auth in a non browser env.
If i have an Air app which takes user/pass to "login" to a web app.
THe login action would be done with a request from Air to http://foo.bar/session/create and the uname/pass as POST var.
Now i can keep the answer and add it to the headers for my next requests ?
If then i do a call to http://foo.bar/links which is protected to get a bunch of links, it should work and return me the links.
How can i be automaticaly authentified in the browser (firefox/ie) opening one of this link ?
My first guess is i can't.
Thanks for your feedbacks.
Greg
You need to add some logic on your serverside. In /session/create
if (passed) { session["user"] = username }
And in /links
if (session["user"] == null) { redirect('/login') }
// Do the rest of your stuff here
THis isn't real code. It's just supposed to give you an idea. You CAN send a token back and forth on each request, but it's a lot easier to have your serverside check the session.
Yes you can login in the background and it will keep your authentication as you copy links. Unfortunately you can't keep that authentication when opening a web browser as they don't share cookies.

Logoff button IIS6 ASP.NET Basic Authentication

I have a requirement for an explicit logout button for users in a ASP.NET web app. I am using IIS6 with Basic Authentication (SSL). I can redirect to another web page but the browser keeps the session alive. I have googled around and found a way to do it by enabling an active x control to communicate with IIS and kill the session. I am in a restricted environment that does not allow forms authentication and active x controls are not forbidden as well. Has anyone else had this requirement and how have you handled it?
Okay that is what I was afraid of. I have seen similar answers on the net and I was hoping someone would have a way of doing it. Thanks for your time though. I guess I can use javascript to prevent the back button like the history.back()
I was struggling with this myself for a few days.
Using the IE specific 'document.execCommand('ClearAuthenticationCache');' is not for everyone a good option:
1) it flushes all credentials, meaning that the user will for example also get logged out from his gmail or any other website where he's currently authenticated
2) it's IE only ;)
I tried using Session.Abandon() and then redirecting to my Default.aspx. This alone is not sufficient.
You need to explicitly tell the browser that the request which was made is not authorized. You can do this by using something like:
response.StatusCode = 401;
response.Status = "401 Unauthorized";
response.AddHeader("WWW-Authenticate", "BASIC Realm=my application name");
resp.End();
This will result in the following: the user clicks the logout button ==> he will get the basic login window. HOWEVER: if he presses escape (the login dialog disappears) and hits refresh, the browser automagically sends the credentials again, causing the user to get logged in, although he might think he's logged out.
The trick to solve this is to always spit out a unique 'realm'. Then the browser does NOT resend the credentials in the case described above. I chose to spit out the current date and time.
response.StatusCode = 401;
response.Status = "401 Unauthorized";
string realm = "my application name";
response.AddHeader("WWW-Authenticate", string.Format(#"BASIC Realm={0} ({1})", realm, DateTimeUtils.ConvertToUIDateTime(DateTime.Now)));
resp.End();
Another thing that you need to do is tell the browser not to cache the page:
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.MinValue);
Response.Cache.SetNoStore();
With all these things in place it works (for me) in IE, but until now I still wasn't able to prevent firefox from logging in the user when the user first presses escape (hides the basic login dialog) and then refresh (F5) or the browsers back button.
The Session.Abandon method destroys all the objects stored in a Session object and releases their resources. If you do not call the Abandon method explicitly, the server destroys these objects when the session times out.
Have you tried calling Session.Abandon in response to the button click?
Edit:
It would seem this is a classic back button issue.
There is very little you can do about the back button. Imagine the user has just opened the current page in a new window then clicked the logOut button, that page appears to log out but it will not immediately affect the content of the other window.
Only when they attempt to navigate somewhere in that window will it become apparent that their session is gone.
Many browsers implement the back button in a similar (although not identical) way. Going back to the previous page is not necessarily a navigation for a HTML/HTTP point of view.
This is a solution for this problem that works in IE6 and higher.
<asp:LinkButton ID="LinkButton1" runat="server" OnClientClick="logout();">LinkButton</asp:LinkButton>
<script>
function logout()
{
document.execCommand("ClearAuthenticationCache",false);
}
</script>
Found this from
http://msdn.microsoft.com/en-us/library/bb250510%28VS.85%29.aspx
Web Team in Short
Your Credentials, Please
Q: Jerry B. writes, "After the user has validated and processed his request, I now want to invalidate him. Assuming this machine is in an open environment where anyone could walk up and us it, I want to throw a new challenge each time a user accesses a particular module on the Web."
A: This is a frequently requested feature of the Internet Explorer team and the good people over there have given us a way to do it in Internet Explorer 6.0 SP1. All you need to do is call the execCommand method on the document, passing in ClearAuthenticationCache as the command parameter, like this:
document.execCommand("ClearAuthenticationCache");
This command flushes all credentials in the cache, such that if the user requests a resource that needs authentication, the prompt for authentication occurs again.
I put this on my logout link button and it works in IE6 sp1 and higher:
OnClientClick="document.execCommand('ClearAuthenticationCache');"

Resources