最简单的方法是使用 asp.net 用户名作为角色名。
您可以编写自己的授权属性来处理授权:
public class CustomAuthorizationAttribute:AuthorizeAttribute
{
public CustomAuthorizationAttribute():base()
{
Users = "registereduser";
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
//You must check if the user has logged in and return true if he did that.
return (bool)(httpContext.Session["started"]??false);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.HttpContext.Response.Redirect("SessionManagement/Index/?returningURL=" +
filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.Url.ToString()));
}
}
如果用户已启动会话,代码必须处理 AuthorizeCore 以返回 true,并处理 HandleUnauthorizedRequest 以将用户重定向到登录页面(可选地,您可以附加返回的 url)。
在需要授权的控制器方法中,为其设置属性:
public class SecretPageController {
[CustomAuthorizationAttribute]
ActionResult Index() {
//Method that requires authorization
return View();
}
}
在 web config 中也将授权方式设置为“Forms”。
Web.config:
<authentication>
<forms timeout="120"></forms>
</authentication>
控制器:
public SessionManagementController:Controller {
public ActionResult Index(string returningURL)
{
return View("Index", new SessionModel() { ReturningURL = returningURL});
}
[HttpPost]
public ActionResult Index(SessionModel mod)
{
if (UserAuthenticated(mod.UserName, mod.Password))
{
FormsAuthentication.SetAuthCookie("registereduser", false);
if (mod.UrlRetorno != null)
{
return Redirect(mod.ReturningURL);
}
return RedirectToAction("Index", "StartPage");
}
mod.Error = "Wrong User Name or Password";
return View(mod);
}
bool UserAuthenticated(string userName, string password) {
//Write here the authentication code (it can be from a database, predefined users,, etc)
return true;
}
public ActionResult FinishSession()
{
HttpContext.Session.Clear();//Clear the session information
FormsAuthentication.SignOut();
return View(new NotificacionModel() { Message = "Session Finished", URL = Request.Url.ToString() });
}
}
在 Controller 中,当用户输入用户名和密码时,将表单身份验证 cookie 设置为 TRUE (FormsAuthentication.SetAuthCookie("registereduser",true)),指示用户名(示例中为 registereduser)进行身份验证.然后用户退出,告诉 ASP.NET 这样做调用 FormsAuthentication.SignOut()。
型号:
class SessionModel {
public string UserName {get;set;}
public string Password {get;set;}
public string Error {get;set;}
}
使用模型来存储用户数据。
视图(表示 SessionModel 类型):
<div class="editor-label">
<%: Html.LabelFor(model => model.UserName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.UserName) %>
<%: Html.ValidationMessageFor(model => model.UserName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Password) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Password) %>
<%: Html.ValidationMessageFor(model => model.Password) %>
</div>
<div class="field-validation-error"><%:Model==null?"":Model.Error??"" %></div>
<%:Html.HiddenFor(model=>model.ReturningURL) %>
<input type="submit" value="Log In" />
使用视图获取数据。在这个例子中,有一个隐藏字段来存储返回的 URL
我希望这会有所帮助(我必须翻译代码,所以我不确定它是否 100% 正确)。