Delete htaccess credentials in Safari - macos

I have an app that logs in via .htaccess. When the person wants to logout, I use:
function logout2()
{ try{
var agt=navigator.userAgent.toLowerCase();
if (agt.indexOf("msie") != -1) {
// IE clear HTTP Authentication
document.execCommand("ClearAuthenticationCache");
}
else {
var xmlhttp = createXMLObject();
xmlhttp.open("GET",".force_logout_offer_login_mozilla",true,"logout","");
xmlhttp.send("");
xmlhttp.abort();
}
} catch(e) {
alert("there was an error");
}
function createXMLObject() {
try { if (window.XMLHttpRequest) { xmlhttp =
new XMLHttpRequest(); } // code
for IE else if
(window.ActiveXObject) {
xmlhttp=new
ActiveXObject("Microsoft.XMLHTTP");
} } catch (e) { xmlhttp=false }
return xmlhttp;
}
The problem is that this is not working for Safari, the person is always logged in using the initial credentials, even closing and reopening the browser. Does anybody know how to handle this?

It is an undocumented quirk of Mozilla's XMLHttpRequest implementation that sending bad auth in an XMLHttpRequest affects the auth used by the main browser in the future. Leveraging this to provide logout is a reasonable hack for now, but I wouldn't count on it working in the future, let alone on other browsers.
The only reliable cross-browser way I know of to allow a logout function is to redirect the user to a page that will 401 them when they pass in valid auth credentials, instead of invalid ones. Then a logged-in user will be greeted with an auth prompt, which they can put bad auth in (normally you tell them to just leave the user/pass fields blank). The script responds positively (eg 302) to the bad auth and the browser remembers it for the future, overwriting the previous good auth.
Unfortunately this process does require some significant user interaction. This is one of the drawbacks of HTTP Authentication.

Related

AJAX Newbie , POSTing data on server

I started learning AJAX recently and am trying a very simple project which involves capturing some form data and sending it to two servers.
The first server is the one which hosts the website and server side php handling. This worls fine
The second server is a python basic http server which handles only the POST operation request send from AJAX. This functionality works but is a bit weird.
Let me explain
Here is my AJAX code which is absolutely straight forward.
function xml_http_post(url, data) {
var req = false;
try {
// Firefox, Opera 8.0+, Safari
req = new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
req.onreadystatechange = function() {
if (req.readyState == 4) {
// callback(req);
}
}
req.open("POST", url, true);
req.setRequestHeader("Content-type","text/plain");
req.send(data);
}
Since I do not intend to send back any response , my callback function on ready state change is empty.
But when I execute this code ( triggered by onclick on a button) , the POST doesnt work and server doesnt seem to receive anything.
But the most surprising thing is that if I keep a breakpoint at req.open( ) and then do a manual step execution then it works always. Which means , I guess that there is some timing issue which needs to be resolved.
It works fine without breakpoints if the third parameter "async" is set to false but that is anyway undesirable so I want to make it work with async = true.
Any help would be greatly appreciated.
Thanks
Shyam
As I figured out, the form page was getting unloaded by a php script which was invoked as a action of the form b the first server. This resulted in the javascript code being partially or not executed.
So I figured out that sync XHR is the only way for my.

ASP.NET MVC3 - Anti-CSRF and Session timeout

I am implementing Anti-Forgery framework as described here:
http://weblogs.asp.net/srkirkland/archive/2010/04/14/guarding-against-csrf-attacks-in-asp-net-mvc2.aspx
Plus, to minimize the coding effort, I did the token insertion part at client side handling form.onsumit and ajaxsend events. Everything works fine – until the session expires.
In my application, I display a popup when the user session gets timed out where the user can re-login and continue without refreshing the current page so that the work-in-progress will be safe. But this doesn't go well with the Anti-CSRF logic. When the user tries to re-login after a timed-out session, this throws a CSRF exception as the cookie (__RequestVerificationToken_Lw__) is already expired and all the future POSTs will be invalid until next page refresh.
Is there any way to set the cookie end time to a future date rather than 'session'? I tried to edit Response.Cookie but that made the cookie invalid.
Any help would be appreciated.
Thanks
At the time of user session out (when displaying a popup) is it possible for you to set the httpcookie with expiry in server side.
I have extracted some code from the microsofts antiforgery token implementation.
internal static string GetAntiForgeryTokenName(string appPath)
{
if (string.IsNullOrEmpty(appPath))
{
return "__RequestVerificationToken";
}
return "__RequestVerificationToken_" + Base64EncodeForCookieName(appPath);
}
private static string Base64EncodeForCookieName(string s)
{
byte[] bytes = Encoding.UTF8.GetBytes(s);
string text = Convert.ToBase64String(bytes);
return text.Replace('+', '.').Replace('/', '-').Replace('=', '_');
}
Below code which set the cookie in server side.
string antiForgeryTokenName = GetAntiForgeryTokenName(HttpContext.Request.ApplicationPath);
HttpCookie httpCookie = HttpContext.Request.Cookies[antiForgeryTokenName];
HttpCookie httpCookie2 = new HttpCookie(antiForgeryTokenName, httpCookie.Value)
{
HttpOnly = true
//// your domain Domain = ,
//// path Path = ,
//// set path Expires =
};
HttpContext.Response.Cookies.Set(httpCookie2);
Please note that I haven't tested this code, just give a try if you dont have any other options.

Response code 401 triggering basic authentication before the jquery ajax error handler

I have a scenario where I have to handle authentication of ajax requests using "Forms Authentication". Based on some search and help from my earlier stackoverflow post, I had decided to use the method described at here.
The idea is to send back a 401 response for unauthenticated requests, and then handle that in the AJAX error handler. So I have an AJAX error handler in my ASP.net MVC3 Layout page that redirects the browser to the login page when it receives 401 response on unauthenticated ajax requests. Here is the ajax error handler.
$(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
if (jqXHR.status == "401") {
window.location.replace(loginUrl);
}
....
});
This all works well on my local IIS 7.5 Server. But on the server where my site is hosted, unfortunately, I get a basic authentication popup on unauthenticated ajax requests (for example session timed out), before the AJAX error handler runs and redirects the browser to the login page. When I cancel the "Authentication Required" popup by pressing the Cancel button, the AJAX error handler then runs and I am redirected to the login page.
So, why does the browser show the authentication popup before running the AJAX error handler?
Edit: The Hosting Server is running IIS 6.
as Softlion said
This is a common question with an easy answer. the 401 is transformed into a 302 to the login >page by the .net authorization module. The browser never see the 401 only the 302.
if you are using .net 4 and later, you use code below
HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
it work's fine for me.
This is a common question with an easy answer.
the 401 is transformed into a 302 to the login page by the .net authorization module. The browser never see the 401 only the 302.
Of course this is not playing nicely with ajax calls.
The best solution i tryed and i'm currently using involve writing a new attribute which is catching 401 and tranform it into ... 409 which is catched by the jquery ajax handler.
It is part of a paid product so i can not give any code.
Try to remove WWW-Authenticate header from response.
IIS 6 in integrated mode? I don't believe there is any such thing, unless you're talking about integrated authentication.
My guess is that you're using a non-aspx extension, so on IIS6 this means that it's not even hitting the .net process. So, IIS is using it's own 401 error response page.
Likely, the solution is to force all requests to be handled by the .net process.
Your host will have to go into IIS properties > configuration > wildcard mappings - and map everything to the .net process.
.net won't catch the 401 errors. What I did was to set the IIS error page from the default 401 page to my own static 401 page. From that page I used javascript to redirect to another handler.
The solution here is to write a custom HttpModule to workaround the MVC frameworks default behavior. Once I was finally able to register the module (cheers David Ebbo) it worked for me. You may want to choose your own criteria for calling SuppressAuthenticationRedirect.
public class SuppressFormsAuthenticationRedirectModule : IHttpModule {
private static readonly object SuppressAuthenticationKey = new Object();
public static void SuppressAuthenticationRedirect(HttpContext context) {
context.Items[SuppressAuthenticationKey] = true;
}
public static void SuppressAuthenticationRedirect(HttpContextBase context) {
context.Items[SuppressAuthenticationKey] = true;
}
public void Init(HttpApplication context) {
context.PostReleaseRequestState += OnPostReleaseRequestState;
context.EndRequest += OnEndRequest;
}
private void OnPostReleaseRequestState(object source, EventArgs args) {
var context = (HttpApplication)source;
var response = context.Response;
var request = context.Request;
if (response.StatusCode == 401 && request.Headers["X-Requested-With"] ==
"XMLHttpRequest") {
SuppressAuthenticationRedirect(context.Context);
}
}
private void OnEndRequest(object source, EventArgs args) {
var context = (HttpApplication)source;
var response = context.Response;
if (context.Context.Items.Contains(SuppressAuthenticationKey)) {
response.TrySkipIisCustomErrors = true;
response.ClearContent();
response.StatusCode = 401;
response.RedirectLocation = null;
}
}
public void Dispose() {
}
public static void Register() {
DynamicModuleUtility.RegisterModule(
typeof(SuppressFormsAuthenticationRedirectModule));
}
}
For me this ended up being simple. Most IIS web sites with anonymous authentication also have a default Windows Auth enabled
Turn off the Windows Authentication which is what pops up the login screen when the site detects the 401 even from an ajax call.
<security>
<authentication>
<anonymousAuthentication enabled="true" />
<windowsAuthentication enabled="false" />
</authentication>
</security>
Wait ! I thought you said Ajax request, how can you get a popup on ajax request ? I am pretty sure somewhere else you are triggering the call to the URL even before AJAX call. From your scenario its proved that when you cancel the popup, your actual ajax request is being made and hence you can do a ajax redirect.
The idea is to send back a 401 response for unauthenticated requests, and then handle that in the AJAX error handler
You can get an ajax response only if you send a ajax request, if you send normal http request then you will get a popup. This has nothing to do with .Net or Java :)

Recommended way to detect for Ajax support on mobile devices?

What is the standard method for detecting whether or not Ajax is supported on mobile devices? If it's not supported I need to replace Ajax content with static content. Did some Googling, but didn't find much.
Any suggestions or examples?
Thanks!
I don't know that there is necessarily a standard way--you can look at certain API/libraries/frameworks that use WURFL perhaps.
If WURFL is too heavyweight, here's what the UCLA Mobile Web Framework has developed thus far for it (ganked from https://github.com/ucla/mwf/blob/feature/core/root/assets/js/core/device.js):
/**
* Determine if device supports AJAX. This attempts to create an XHR object
* of the standard type and ActiveXObject varieties and, if any succeed, then
* it returns true.
*/
this.hasAJAX = function(){
var xhr = null;
try { xhr = new XMLHttpRequest(); } catch (e) {}
try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
return xhr != null;
}

With JavaScript Ajax polling for widget

I have the follow problem. I need to create a JS widget and set it on one blog, for example any blog from blogger.com. YOu can select there a box for javascript and I will post the JS in this box.
The problem what I have and don't know how to do this is, that the script should do an ajax polling for exmaple for 60 seconds. But how to execute an ajax call, when the host is not the same linke the host, where the JS is includet?
For example the easiest way to explai is: There is a search box and when enayone searches for anythign, then the JS script should streaming the results for 60 seconds from the server what I have set in the script and is different as the host, where the JS is includet, without to become a problem with the JS restriction for hosts.
Or for example a chat client, where the client is hosted on one other host and the server on another.
Can anyone tell me an idea, or send me an example how to do this?
Thanks
Nik
Well with this example is it possible but without JSONP?
function asyncreq(url) {
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
xmlhttp = false;
}
}
}
if (xmlhttp){
try {
xmlhttp.open("GET", url);
xmlhttp.onreadystatechange=function() {
document.getElementById('mydiv').innerHTML = xmlhttp.responseText;
}
xmlhttp.send(null);
}
catch (failed) {
xmlhttp = false;
}
}
}
If you send the response in chunks, then everything is fine. But here is the call in ajax again. And when I use it in a different host, then I can't call the url because of the same-origin policy.
Is there another way?
I found a very interesting example here.
Take a look at the bottom, there is a job search box. If you investigate a litte bit, then you will see there is a usage of a class RSL() which is doing the request. How this class is doing the request without ajax? I can't understand wow this class works. Can anyone show me a better example?
There are two main options:
Put an iframe where you want the widget to go. Its src URL would be on the same server that will receive the AJAX call.
Use JSONP, which consists of inserting a script tag into the page to bypass the same-origin policy. This requires that the AJAX server wrap its JSON output in ?(...), where the URL includes callback=?. Then, as soon as a response has been received, start another request.

Resources