我一直在网上阅读大量关于身份验证和授权的资料,最后确定了一些似乎正在工作的代码……但我并不完全理解它所做的一切(就 FormsAuthenticationTicket 而言)。
我正在使用的 MVC 应用程序将处理一些敏感数据,我想对我所做的与身份验证和授权相关的所有事情进行三次检查。
我正在使用 Windows 身份验证;
<authentication mode="Windows" />
<authorization>
<deny users="?"/>
</authorization>
我在 SQL Server 中有一组表,其中包含其他用户和权限信息。
- 用户
- 角色
- 用户角色
- 定义应用程序中的对象和相关权限的其他表。
在我的 Global.asax 中,我有以下方法的灵感来自
http://www.codeproject.com/Articles/5182/Insight-into-Security-Model-using-Principal-and-Id
protected void WindowsAuthentication_OnAuthenticate(object sender, WindowsAuthenticationEventArgs e)
{
if (e.Identity == null || !e.Identity.IsAuthenticated)
{
//Redirect to error or access denied page
}
string userData = e.Identity.AuthenticationType;
var cachedUser = HttpContext.Current.Cache[e.Identity.Name] as User;
if (cachedUser == null)
{
var user = repo.GetUserByFullUserName(e.Identity.Name);
HttpContext.Current.Cache.Insert(e.Identity.Name, user, null, DateTime.Now.AddMinutes(2), Cache.NoSlidingExpiration);
cachedUser = HttpContext.Current.Cache[e.Identity.Name] as User;
}
var userIdentity = e.Identity.Name;
var formsAuthTicket = new FormsAuthenticationTicket(1, e.Identity.Name, DateTime.Now, DateTime.Now.AddMinutes(2), false, userData);
var encryptedTicket = FormsAuthentication.Encrypt(formsAuthTicket);
var httpcook = new HttpCookie("authCookie", encryptedTicket);
Response.Cookies.Add(httpcook);
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
var httpcook = Context.Request.Cookies["authCookie"];
var formsAuthTicket = FormsAuthentication.Decrypt(httpcook.Value);
var cachedUser = GetCachedUser(formsAuthTicket.Name);
if (cachedUser == null)
{
cachedUser = CreateCachedUser(formsAuthTicket.Name);
}
var genIdentity = new GenericCustomIdentity(cachedUser, Request.IsAuthenticated, formsAuthTicket.UserData);
var genPrincipal = new GenericCustomPrincipal(genIdentity, cachedUser);
HttpContext.Current.User = genPrincipal;
}
}
所以这是我的问题:
为什么在 WindowsAuthentication_OnAuthenticate 方法中有一个 FormsAuthenticationTicket?我不能只在 WinAuth 方法中构建我的 Identity 和 Principal 对象吗?
将用户数据存储在 HttpContext.Current.Cache 中是否存在安全风险?由于这些方法被多次调用,我不想每次请求都访问数据库。有更好/更安全的选择吗?
我不熟悉使用 FormsAuthenticationTickets、Identity 和 Principal,因此非常感谢任何意见或建议。抱歉,这不是问题。