简单的授权与MVC3窗体身份验证 [英] Simple Authorization in MVC3 with Forms Authentication
问题描述
我想要做什么应该在MVC3一件简单的事情。
I'm trying to do what should be a simple thing in MVC3.
我已经得到了使用窗体身份验证与第三方SSO来验证用户的应用程序。该SSO,在成功登录后,回发到我的应用程序的特定控制器动作。然后,我打电话 FormsAuthentication.SetAuthCookie(用户,FALSE);
I've got an application that uses forms authentication to authenticate users with a 3rd party SSO. The SSO, on successful login, posts back to a specific controller action on my application. I then call FormsAuthentication.SetAuthCookie(user,false);
.
我想实现授权的某种程度。简单地说,一个用户可以用许多不同的角色的存在,例如管理
和开发
。有些控制器动作应该只提供给某些角色。该角色的用户属于细节,是通过向其他外部API,它返回一个简单的JSON响应指示调用中获得。
I'm trying to implement some level of authorization. Simply, a user can exist in a number of different roles, e.g. Admin
and Developer
. Some controller actions should only be available to certain roles. Details of which roles a user belongs to is obtained by making a call to another external API, which returns a simple JSON response indicating.
在理论上,这应该是为做这样的事情的简单经过我设置FormsAuthentication饼干:
In theory, this should be as simple as doing something like this after I set the FormsAuthentication cookie:
string[] rolelist = GetRoleListForUserFromAPI(User.Identity.Name);
HttpContext.User = new GenericPrincipal(User.Identity, rolelist);
不过,我不能打电话后直接调用此 SetAuthCookie
,因为 HttpContext.User中
不是什么有意义此时
However, I can't call this directly after calling SetAuthCookie
, because HttpContext.User
isn't anything meaningful at this point.
我可以尝试在每次请求设置这一点,但以往任何时候都请求我的应用程序将意味着往返API调用。
I could try setting this on every request, but ever request to my app would mean a roundtrip API call.
到目前为止我见过的最有前途的方法是创建一个自定义的授权属性并重写 OnAuthorization
做这样的事情:
The most promising approach I've seen so far is to create a custom Authorization attribute and override OnAuthorization
to do something like this:
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (<some way of checking if roles have already been set for this user, or role cache has timed out>)
{
string[] rolelist = GetRoleListForUserFromAPI(filterContext.HttpContext.User.Identity.Name);
filterContext.HttpContext.User = new GenericPrincipal(filterContext.HttpContext.User.Identity,rolelist);
}
}
我可以再使用 [MyCustomAuthorization(角色=管理员)]
在控制器动作前,使魔术发生。
I could then use [MyCustomAuthorization(Roles="Admin")]
in front of controller actions to make the magic happen.
不过,我不知道如何来检测电流 HttpContext.User中
对象是否有其角色设置,还是它被设置在一定时间以前,需要另一个API之旅。
However, I've no idea how to detect whether or not the current HttpContext.User
object has had its roles set, or whether it was set over a certain time ago and another API trip is needed.
什么是最好的办法了吗?
What's the best approach for this?
推荐答案
我首先想到的是,你应该调查实施自定义角色提供程序。这可能是矫枉过正,但似乎适合与基于角色的管道。
My first thought is that you should investigate implementing a custom role provider. This might be overkill but seems to fit in with the role-based plumbing.
从MSDN 这里更多信息。
More info from MSDN here.
这篇关于简单的授权与MVC3窗体身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!