ASP.NET Identity
首先建立Net的Ticket
//建立FormsAuthentication ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
"xxxx",//使用者帳號
DateTime.Now, //核發日期
DateTime.Now.AddMinutes(60), //到期時間 30分鐘
true, // 是否記住我
"001", //使用者身份可自定義(多筆用','串接)
FormsAuthentication.FormsCookiePath);
//加密
string encTicket = FormsAuthentication.Encrypt(ticket);
//加入Cookies
HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
接著產生一個新的CustomAuthorize類別繼承 AuthorizeAttribute
public class CustomAuthorize : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new HttpUnauthorizedResult();
}
//驗證失敗時導頁至自定義錯誤畫面
else
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new RouteValueDictionary(new
{
action = "NotFound",
controller = "Error",
area = ""
})));
}
}
}
最後只需要在Action上加入CustomAuthorize的Attribute,並指定該Action給那些Role使用
[CustomAuthorize(Roles = "001")]
public ActionResult Index()
以上作法為本魯目前使用,若有地方錯誤請大神不吝說明了