我正在嘗試學習ASP MVC的基本安全和訪問限制。關於我的Web應用程序的身份驗證和角色的澄清和同行評審
到目前爲止,我看過/看過的教程,但他們都看起來不同。如果我會搜索一些東西,它會導致我與另一個完全不同的實現。
我實施了Authentication
和custom role provider
,我對於事情的工作方式有一些疑問。我從互聯網上找到的大多數解釋似乎過於複雜或過時。
這是我如何實現我的authentication
。
登錄控制器:
[HttpGet]
[ActionName("login")]
public ActionResult login_load()
{
return View();
}
[HttpPost]
[ActionName("login")]
public ActionResult login_post(string uname,string pword)
{
using (EmployeeContext emp = new EmployeeContext())
{
int success = emp.login.Where(x => x.username == uname && x.password == pword).Count();
if (success == 1)
{
FormsAuthentication.SetAuthCookie(uname, false);
return RedirectToAction("Details", "Enrollment");
}
return View();
}
}
然後我保護我的大多數控制器與[Authorize]
問題#1 什麼的FormsAuthentication.SetAuthCookie(uname, false);
的宗旨,我應該typicalfly使用它呢?存放username
是否可以。我以後需要它來進行比較嗎?(進一步的安全性?)。它在這裏說Authentication ticket
將被賦予用戶名。那些是隨機字母嗎?
-
在那之後,我決定深入瞭解並實施了custom role provider
從roleprovider.cs (我只執行2種方法至今)
public override string[] GetRolesForUser(string username)
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
return null;
}
var cacheKey = username;
if (HttpRuntime.Cache[cacheKey] != null)
{
return (string[])HttpRuntime.Cache[cacheKey];
}
string[] roles = new string[] { };
using (MvcApplication6.Models.EmployeeContext emp = new MvcApplication6.Models.EmployeeContext())
{
roles = (from a in emp.login
join b in emp.roles on a.role equals b.id
where a.username.Equals(username)
select b.role).ToArray<string>();
if (roles.Count() > 0)
{
HttpRuntime.Cache.Insert(cacheKey, roles, null, DateTime.Now.AddMinutes(_cacheTimeoutInMinute), Cache.NoSlidingExpiration);
}
}
return roles;
}
問題#2 我有點困惑在這裏,我需要一個深入的說明:那麼基本上的目的是什麼,從我的例子來看,我只是把它等於uname
,因爲我不知道發生了什麼。
問題#3 爲什麼返回(string[])HttpRuntime.Cache[cacheKey];
如果該值爲空?何時返回以及誰收到了?
問題4 所獲得的價值的角色列表從數據庫之後,該函數將被調用HttpRuntime.Cache.Insert(cacheKey, roles, null, DateTime.Now.AddMinutes(_cacheTimeoutInMinute), Cache.NoSlidingExpiration);
。所以從我看到的角色被插入到緩存中?是否用於稍後檢查登錄類型?
問題#5
從該行的代碼:
public override bool IsUserInRole(string uname, string roleName)
{
var userRoles = GetRolesForUser(uname);
return userRoles.Contains(roleName);
}
當他們恰好觸發,誰提供的參數?是從緩存中的roleName
?
我很難想象引擎蓋下發生了什麼。解釋/推薦將非常有幫助。
我也想補充說,我需要在'Role Providers'之前實現'Authentication'嗎?我覺得在用戶成功登錄後會觸發'RP'。 –