[英]Custom form authentication / Authorization scheme in ASP.net MVC
我正在嘗試使用表單身份驗證在ASP.NET MVC中創建自定義身份驗證方案。 我可能會在站點上具有將要管理的不同區域的想法-批准人區域和一般用戶區域,這些區域將使用不同的登錄頁面,依此類推。 所以這就是我要發生的事情。
非常感謝您的幫助!!!
這是我到目前為止所擁有的,並且不起作用:
public class AdministratorAccountController : Controller
{
public ActionResult Login()
{
return View("Login");
}
[HttpPost]
public ActionResult Login(AdministratorAccountModels.LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
if (model.UserName == "admin" && model.Password == "pass") // This will be pulled from DB etc
{
var ticket = new FormsAuthenticationTicket(1, // version
model.UserName, // user name
DateTime.Now, // create time
DateTime.Now.AddSeconds(30), // expire time
false, // persistent
""); // user data
var strEncryptedTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strEncryptedTicket);
Response.Cookies.Add(cookie);
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
// If we got this far, something failed, redisplay form
return View(model);
}
[AdministratorAuthorize]
public ActionResult MainMenu()
{
return View();
}
public class AdministratorAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authenCookie = httpContext.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
if (authenCookie == null) return false;
var ticket = FormsAuthentication.Decrypt(authenCookie.Value);
var id = new FormsIdentity(ticket);
var astrRoles = ticket.UserData.Split(new[] { ',' });
var principal = new GenericPrincipal(id, astrRoles);
httpContext.User = principal;
return true;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
var model = new AdministratorAccountModels.LoginModel();
var viewData = new ViewDataDictionary(model);
filterContext.Result = new ViewResult { ViewName = "Login", ViewData = viewData };
}
}
}
我結合使用minus4建議的代碼和上面的我自己的代碼來創建此簡化的場景,可能會對其他人有所幫助。 一開始我添加了一些讓我感到困惑的評論。
public class AdministratorAccountController : Controller
{
public ActionResult Login()
{
return View("Login");
}
[HttpPost]
public ActionResult Login(AdministratorAccountModels.LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
// Here you would call a service to process your authentication
if (model.UserName == "admin" && model.Password == "pass")
{
// * !!! *
// Creating a FromsAuthenticationTicket is what
// will set RequestContext.HttpContext.Request.IsAuthenticated to True
// in the AdminAuthorize attribute code below
// * !!! *
var ticket = new FormsAuthenticationTicket(1, // version
model.UserName, // user name
DateTime.Now, // create time
DateTime.Now.AddSeconds(30), // expire time
false, // persistent
""); // user data, such as roles
var strEncryptedTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strEncryptedTicket);
Response.Cookies.Add(cookie);
// Redirect back to the page you were trying to access
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
// If we got this far, something failed, redisplay form
return View(model);
}
[AdminAuthorize]
public ActionResult MainMenu()
{
return View();
}
public class AdminAuthorize : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.RequestContext.HttpContext.Request.IsAuthenticated)
{
// Redirect to the needed login page
// This can be pulled from config file or anything else
filterContext.HttpContext.Response.Redirect("/AdministratorAccount/Login?ReturnUrl="
+ HttpUtility.UrlEncode(filterContext.HttpContext.Request.RawUrl));
}
base.OnActionExecuting(filterContext);
}
}
}
好的,這里您去了代碼
在其中有ActionFilters文件夾(AuthAccess.cs)插件文件夾(security.cs(加密/解密cookie),SessionHandler.cs(所有登錄問題))Controllers文件夾(BaseController.cs和exampleController(向您展示如何使用)和loginTable SQL文件。
我使用mysql,所以您可能需要進行修改,同時我也使用subsonic,因此我的模型將來自該模型,並將位於空的models文件夾中。
真的很簡單,會為您留下一陣子,享受
nope cookie模型在這里對不起:
using System;
namespace TestApp.Models
{
public class CookieModel
{
public string CurrentGuid { get; set; }
public DateTime LoginTime { get; set; }
public Int32 UserLevel { get; set; }
public Int32 LoginID { get; set; }
public bool isValidLogin { get; set; }
public string realUserName { get; set; }
public string emailAddress { get; set; }
}
}
這不是什么角色嗎? 看看使用角色的asp.net mvc授權或一般看一下角色
我在上課前要先解決這個問題
例程是登錄,讀取cookie,檢查cookie,並且它們的模型包含
名稱,電子郵件,ID,用戶級別
那么你只有自己的自定義actionFilter
例如[CustomAuth(MinAllowedLevel = 10)]
我為所有控制器使用了基類,因此我可以更輕松地鏈接到所有會話內容,然后可以像這樣獲取信息
var model = pictures.all().where(x => x.userid == users.ReadCookie.userID)
當我回到英國白天時,如果您願意,我會取消代碼明天
說10個小時,我將為您提供所有會話內容的類以及您可以使用的自定義操作過濾器,那么您所需要的只是一個帶有用戶級別字段的登錄表,最好是10,20,30,40個級別您需要一個介於1和2之間的水平
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.