对于HTTP基本认证我前一篇文章也有所介绍,但是一次认证后浏览器将会把认证信息保存一段时间以避免在下一次打开时再次认证,也就是说认证成功后每次请求需要认证的页面时浏览器都会附加认证信息,一般在请求头的Authorization节点,但是如果用户需要注销当前登录就略显麻烦了。
不过在IE下比尔叔叔为我们提供了一个便捷的方式,那就是JavaScript执行下面的代码:
document.execCommand("ClearAuthenticationCache") |
试了下,IE下完全正常,如果说这么简单就解决这个问题的话,也太低估我们的浏览器大军了,FireFox和Chrome等非微软系的浏览器根本无视上面的代码,所以只有另辟蹊径了。
找到一篇文章《Bug 287957 – need a way for content to trigger a clearing of the HTTP auth session from script (.htaccess logout)》提供了解决的思路,那就是利用Ajax向需要认证的页面发送一个错误的用户名和密码组合,然后下次访问的时候认证页面就会再次请求你输入用户名和密码了,具体的代码如下,我从那个帖子转过来供大家参考:
try{ var agt=navigator.userAgent.toLowerCase(); if (agt.indexOf("msie") != -1) { // IE clear HTTP Authentication document.execCommand("ClearAuthenticationCache"); } else { // Let's create an xmlhttp object var xmlhttp = createXMLObject(); // Let's get the force page to logout for mozilla xmlhttp.open("GET",".force_logout_offer_login_mozilla",true,"logout","logout"); // Let's send the request to the server xmlhttp.send(""); // Let's abort the request xmlhttp.abort(); } // Let's redirect the user to the main webpage window.location = "/rest/"; } catch(e) { // There was an error 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; } |