我可能过度简化了这一点,但我阅读的方式如下:
- 如果用户未通过身份验证,则您有一个收集用户名/密码的表单
- 该表单的结果将传递给 Web 服务以进行授权
- 如果该授权成功,您需要一种方法让 Web 应用程序知道他们已经登录。
- 如果他们经过身份验证,请做一些事情
如果以上是正确的,您不需要会员提供商。[Authorize] 属性只是查看表单身份验证 cookie 以查看它是否已设置并且在 cookie 的当前生命周期内有效。此身份验证 cookie 存储用户的用户名和 cookie 的到期时间(以及其他内容,但在这里并不重要)。
鉴于此,您只需要设置 web.config 配置元素并具有设置身份验证 cookie 的方法。
网络配置
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
</system.web>
登录 URL GET 操作
public ActionResult Logon(){
//if the user is logged in, send the to the home page
if(httpContext.User.Identity.IsAuthenticated_{
Return RedirectToAction("Index", "Home");
}
Return this.View(new LoginViewModel());
}
登录 URL POST 操作
[HttpPost]
public ActionResult Logon(LoginViewModel model){
//Check for model errors
if(!ModelState.IsValid()){
Return this.View(model);
}
//Validate against web service - return error if false
if(!CheckClientsWebService(model.UserName, model.Password)){
ModelState.AddModelError("","The username or password is invalid");
Return this.View(model);
}
//Manually set the authentication cookie
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
//Send them on to the home page, they now have a authorization cookie
Return RedirectToAction("Index", "Home");
}
调用该.SetAuthCookie()
函数后,用户现在将拥有一个身份验证票,并且HttpContext.User.Identity.IsAuthenticated
只要 cookie 未过期,调用 to 就会为真,并且您可以从中获取用户名HttpContext.User.Identity.Name