我正在使用MVC3并将用户身份验证放在web.config文件中。这是为了绕过sqlserver身份验证。
代码如下所示:web.config:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" >
<credentials passwordFormat="Clear">
<user name="test123" password="test123" />
</credentials>
</forms>
</authentication>
我尝试使用提到的用户ID和密码登录,我在页面中收到错误
登录失败。请更正错误,然后重试。
* The user name or password provided is incorrect.
当我调试到AccountController.cs文件时,失败了MembershipService.ValidateUser(model.UserName, model.Password)
方法。
答案 0 :(得分:30)
如果您检查标准的ASP.NET MVC 3 AccountController.cs 和 AccountModels.cs 文件,您将了解内部使用的MembershipProvider.ValidateUser方法(通过Membership.Provider)。如果要在web.config中存储密码,则应使用FormsAuthentication.Authenticate方法。
例如:
public class AuthorizationController : Controller
{
public ActionResult LogOn()
{
return View("LogOn");
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LogOn(string userName, string password,
bool rememberMe, string returnUrl)
{
if (!ValidateLogOn(userName, password))
return View("LogOn");
FormsAuthentication.SetAuthCookie(userName, rememberMe);
if (!string.IsNullOrEmpty(returnUrl))
return Redirect(returnUrl);
else
return RedirectToAction("Index", "News");
}
private bool ValidateLogOn(string userName, string password)
{
if (string.IsNullOrEmpty(userName))
ModelState.AddModelError("username", "User name required");
if (string.IsNullOrEmpty(password))
ModelState.AddModelError("password", "Password required");
if (ModelState.IsValid && !FormsAuthentication.
Authenticate(userName, password))
ModelState.AddModelError("_FORM", "Wrong user name or password");
return ModelState.IsValid;
}
public RedirectToRouteResult LogOff()
{
FormsAuthentication.SignOut();
return RedirectToAction("LogOn");
}
}