在每个请求asp.net mvc上具有基于角色的自定义auth查询数据库的正确方法 [英] right way to have role based custom auth query database on every request asp.net mvc
问题描述
这可能是一个有点无知的问题,但是我是mvc的新手,所以我很抱歉!
This may be a slightly ignorant question but Im new to mvc so Im sorry!
我研究了书呆子晚餐身份验证模型,但是在我的应用程序中,我有一个基于角色的复杂身份验证.所以我要做的是:
I studied the nerd dinner auth model but In my app I have a complicated role based authentication. So What I do is this:
void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
HttpCookie authCookie = HttpContext.Current.Request
.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
string encTicket = authCookie.Value;
if (!String.IsNullOrEmpty(encTicket))
{
FormsAuthenticationTicket ticket =
FormsAuthentication.Decrypt(encTicket);
CustomIdentity id = new CustomIdentity(ticket.Name);
GenericPrincipal prin = new GenericPrincipal(id, id.Roles);
HttpContext.Current.User = prin;
}
}
}
在LogOn上,我使用FormsAuth验证用户名/密码,然后创建cookie.
On LogOn I authentication the username/pass with FormsAuth and then I create the cookie.
这里的问题是,每次创建自定义标识时,我必须在数据库中查询用户角色.是否有正确的解决方法,还是我在每个传入请求上查询数据库都做对了?我应该将角色列表保存在Cookie或其他内容中吗?
The problem here is every time I create the custom identity, I have to query the database for the users roles. Is there a correct way around this or am I doing the right thing to query the DB on every incoming request? Should I save the roles list in a cookie or something?
我也不太了解表单auth如何处理身份验证的整个生命周期?我使用与书呆子晚餐用户相同的IFormsAuthentication
设计模式,并且在登录期间调用了FormsAuth.SignIn()
,又依次调用了FormsAuthentication.SetAuthCookie
,它什么时候可以调用membershipservice.validateuser()
方法?同样,如果设置了 auth cookie ,为什么书呆子晚餐会创建票证,然后将其添加到请求中,然后在PostAuthenticationRequest
期间读取该票证以检查是哪个用户.票证操作像会话吗?
I also don't really understand the whole life cycle of how forms auth takes care of the authentication? I use the same IFormsAuthentication
design pattern that nerd dinner users and during a sign-in I call FormsAuth.SignIn()
which in turn calls FormsAuthentication.SetAuthCookie
, When does it manage to call the membershipservice.validateuser()
method ?? Also if the auth cookie has been set why would nerd dinner create a ticket, then add it into the request, and then read it during PostAuthenticationRequest
to check which user it was. Does the ticket operation like a session?
谢谢!圣诞快乐!
更新:此链接使我对以下内容有了更好的理解形成身份验证票.
Update : This link gave me a slightly better understanding about forms authentication ticket.
推荐答案
另一种方法是在对用户进行身份验证时将用户的角色存储在身份验证票证中.然后,对于每个请求(global.asax文件的Application_AuthenticateRequest
方法),您都可以从身份验证票证中提取角色并创建GenericPrincipal
.
An alternative approach is to store your user's roles in the authentication ticket when your user is authenticated. Then for every request (Application_AuthenticateRequest
method of the global.asax file) you can extract the roles from the authentication ticket and create a GenericPrincipal
.
查看此答案有关更多详细信息.
这篇关于在每个请求asp.net mvc上具有基于角色的自定义auth查询数据库的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!