分享

asp.net FormsAuthentication表单认证时如何弹出Windows登录窗口

 A_POST 2013-12-16
asp.net FormsAuthentication表单认证时如何弹出Windows登录窗口

asp.net 表单认证模式下,如何能够使用 浏览器 的登录窗口进行登录(IE使用Windows内置的验证窗口,Firefox、Chorme会弹出自带的小窗口进行登录)。

首先,修改Web.Config文件,设置为表单登录方式

<authentication mode="Forms">

  <forms loginUrl="~/Account/Login" defaultUrl="~/">

    <credentials passwordFormat="SHA1">

      <user name="admin" password="e9fe51f94eadabf54dbf2fbbd57188b9abee436e" />

    </credentials>

  </forms>

</authentication>

 

接下来,我们需要告诉浏览器,让其弹出登录小窗口,代码如下:

// Force the browser to pop up the login prompt

        Response.StatusCode = 401;

        Response.AppendHeader("WWW-Authenticate", "Basic");

        TempData["allowLogin"] = true;

 

我们已ASP.NET MVC来讲看一下完成代码;

下面是登录相关的Controller示例代码:

public class AccountController : Controller

{

    public void Login()

    {

        // Ensure there's a return URL

        if (Request.QueryString["ReturnUrl"] == null)

            Response.Redirect(FormsAuthentication.LoginUrl + "?ReturnUrl=" + Server.UrlEncode(FormsAuthentication.DefaultUrl));

 

        if (TempData.ContainsKey("allowLogin"))

        {

            // See if they've supplied credentials

            string authHeader = Request.Headers["Authorization"];

            if ((authHeader != null) && (authHeader.StartsWith("Basic")))

            {

                // Parse username and password out of the HTTP headers

                authHeader = authHeader.Substring("Basic".Length).Trim();

                byte[] authHeaderBytes = Convert.FromBase64String(authHeader);

                authHeader = Encoding.UTF7.GetString(authHeaderBytes);

                string userName = authHeader.Split(':')[0];

                string password = authHeader.Split(':')[1];

 

                // Validate login attempt

                if (FormsAuthentication.Authenticate(userName, password))

                {

                    FormsAuthentication.RedirectFromLoginPage(userName, false);

                    return;

                }

            }

        }

 

        // Force the browser to pop up the login prompt

        Response.StatusCode = 401;

        Response.AppendHeader("WWW-Authenticate", "Basic");

        TempData["allowLogin"] = true;

 

        // This gets shown if they click "Cancel" to the login prompt

        Response.Write("You must log in to access this URL.");

    }

}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多