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.");
}
}