65.9K
CodeProject 正在变化。 阅读更多。
Home

自定义基本 HTTP 身份验证

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1投票)

2016年4月8日

CPOL

3分钟阅读

viewsIcon

20624

基本 HTTP 身份验证的浏览器对话框的抑制和自定义。

引言

我将在这里描述的问题和解决方案是基本Http身份验证的基本对话框的解决方法。当我试图统一身份验证流程时,我遇到了这样的问题。像我们大多数人一样,我开始在互联网上浏览以找到一个解决方案,不幸的是,我发现的解决方案都无法用于我的情况。在这里,我想分享我的经验,希望有人能觉得它有用。

问题

一般来说,问题是抑制基本http身份验证对话框,并显示自定义UI而不是基本浏览器对话框,只是为了跨浏览器创建常见用户体验。例如,在Chrome、FF或Opera浏览器上输入错误的用户凭据时的用户体验将与Internet Explorer和Safari不同。例如,IE或Safari在几次尝试对服务器进行身份验证(如果错误)后将取消错误请求,并且Web应用程序可以显示类似“无法访问您的帐户”的页面。Chrome、FF和Opera将无限地这样做(请求将处于待处理状态),直到用户放弃并按下取消按钮。另一个问题是如何在基本身份验证的情况下注销。

我的实验围绕着Apache服务器的配置,但我认为它很容易为IIS或Nginx完成。因为那么一切都围绕着基本Http身份验证。

该解决方案通过了IE(10、11)、Chrome 49、FF 44、Opera 36的测试。

解决方案

首先,必须做的是配置Http服务器,在我的例子中是Apache。通常,所有不需要身份验证的静态内容,如图像、脚本、html,都无需身份验证即可使用。但对于该解决方案,我们需要一个图像(例如)进行身份验证。

  1. 我在服务器上创建了一个目录,将小图像放在那里,并配置了apache,使其需要对资源进行身份验证。

    这是一个名为“auth_required'

    Alias		/auth_required	/path/auth_required/
    <Location /auth_required>
    	Options Indexes
    	Order allow,deny
    	Allow from all
    	Include "/your/path/here/an_auth_config.conf"
    </Location>
  2. 我为自定义身份验证UI创建了一个免费的经过身份验证的目录。该目录有一个简单的HTML页面,不会破坏整个门户的安全性,并呈现一个简单的身份验证页面。

    这是一个Apache目录auth配置的示例。

    # Unprotected resources
    <Directory /path/auth>
    	AuthType None
    </Directory>
    
    Alias		/auth			/path/auth
    <Location /auth>
    	# No Auth
    	AuthType None
    	#Require all granted
    	DirectoryIndex auth_test.html
    </Location>

这就是我们在服务器端所要做的全部。

主要技巧在客户端实现。

在下面,您将找到带有内联注释的代码示例。该解决方案适用于Internet Explorer、Chrome、FF和Opera,但不幸的是不适用于Safari。

我设想,如果服务器在用户凭据错误的情况下提供403代码而不是401,Safari也会工作。现在,我还没有找到Safari的正确方法。

此外,我有一个未解决的问题,即在哪里保存用户名,以及在用户成功验证后,客户端是否应该在下次自动将他重定向到主页,而无需提示身份验证页面。现在,我将用户名保存在cookie中,如果它不为空,则会触发自动重定向到主页,而无需直接在url中提供用户名和密码。

function doLoad()
{
    //the method will be called on page load and in case 
    //if user previously was authenticated should redirect to main page
    //here we have to get logged in user somehow, probably from cookie or local storage.

    //we always have to provide user name to XMLHttpRequest even if it is not correct, 
    //because in case if user was not logged in before 
    //and we do not provide any user name for XMLHttpRequest.open method 
    //default authentication window will be prompted, but we want to suppress it

    var user = $.cookie('loggedas');
    if (user && user.length > 0)
    {
        authenticate();
    }
}

function doAuthenticate()
{
    //the method have to be called on user click on user credentials form
    var user = $('#useridUIID').val();
    var pswd = $('#pswdUIID').val();

    //it is main trick, default authenticated window will be 
    //prompted until ANY user name (even not correct) will be passed to XMLHttpRequest
    //but it doesn't work for Safari
    user = (user && user.length > 0 ? user : '' + Date.now().getTime())

    authenticate(user, pswd);
}

function authenticate(user, pswd)
{
    var warning = $('div.warning');
    if (!warning.hasClass('hidden'))
    {
        warning.addClass('hidden');
    }

    //path to resource which require authentication
    var img = location.protocol + '//' + location.host + 
    (location.port && location.port.length > 0 ? ':' + 
    location.port : '') + '/auth_required/favicon.ico';

    var xhr = new XMLHttpRequest();
    if (user)
    {
        xhr.open('GET', img, true, user, pswd);
    }
    else
    {
        xhr.open('GET', img, true);
    }

    xhr.onreadystatechange = function (e)
    {
        if (this.status !== 0) //work around for IE
        {
            if (this.status === 200)
            {
                //keep user name, in order to redirect automatically next time
                //from my perspective I dont see any security breach to keep user name at cookies, 
                //if it is not so, here should be another way to automatically redirecting next time
                $.cookie('loggedas', user);

                //redirect to main page
                if (user)
                {
                    try
                    {
                        document.location.href = location.protocol + '//' + 
                        user + ':' + pswd + '@' + location.host + 
                        (location.port && location.port.length > 0 ? ':' + 
                        location.port : '') + '/admin/';
                    }
                    catch (e)
                    {
                        document.location.href = location.protocol + '//' + 
                        location.host + (location.port && location.port.length > 0 ? 
                        ':' + location.port : '') + '/admin/';
                    }
                }
                else
                {
                    document.location.href = location.protocol + '//' + location.host + 
                    (location.port && location.port.length > 0 ? ':' + 
                    location.port : '') + '/admin/';
                }
            }
            else
            {
                //show error in case wrong credentials
                if (warning.hasClass('hidden'))
                {
                    warning.removeClass('hidden');
                }
            }
        }
    };

    xhr.send();
}

$(document).ready(function ()
{
    doLoad();
});

现在,您可以像这样对您的服务器进行身份验证

而不是默认的

结论

当然,如果您不想在服务器端实现自定义身份验证,而只想使用基本的身份验证,那么我说的一切都将起作用。

而且我仍然不知道Safari的合适解决方法。而且我没有测试它是否适用于旧版本的浏览器,该解决方案是否对它们有效?

我将感谢对此主题的任何评论。谢谢。

© . All rights reserved.