gpt4 book ai didi

authentication - ASP.NET MVC4 覆盖 OnAuthorization 以允许角色白名单

转载 作者:行者123 更新时间:2023-12-05 08:01:36 26 4
gpt4 key购买 nike

我有一个具有两种类型角色的 ASP.NET MVC4 站点:管理员和合作伙伴。

基本上,对站点的所有访问都需要用户进行身份验证并具有管理员角色。因此我在 FilterConfig.cs(从 Global.asax 调用)中这样做:

public class FilterConfig {
public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
filters.Add(new HandleErrorAttribute());
filters.Add(new AuthorizeAttribute { Roles = "Administrator" }); // default deny
}
}

然而,对于一个 Controller ,我想向具有合作伙伴角色但没有管理员角色的用户授予访问权限。我知道我可以通过不使用全局过滤器而是在每个 Controller 或操作上设置授权属性来做到这一点,但我想要一种白名单方法,而不是默认情况下所有访问都需要“管理员”角色,然后使用某种形式的白名单.

我试过使用一个 Controller ,我像这样覆盖 OnAuthorization:

public class MyController : Controller {
protected override void OnAuthorization(AuthorizationContext filterContext) {
if (User.Identity.IsAuthenticated) {
var attributes = new List<AllowRolesAttribute>();
attributes.AddRange(filterContext.ActionDescriptor.GetCustomAttributes(true).OfType<AllowRolesAttribute>());
attributes.AddRange(filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(true).OfType<AllowRolesAttribute>());
foreach (var authorizationAttribute in attributes) {
foreach (var role in authorizationAttribute.Roles.Split(',')) {
if (User.IsInRole(role))
return; // Skip authorization because user has one of the allowed roles.
}
}
}
base.OnAuthorization(filterContext);
}
}

然后我这样定义 Controller :

[AllowRoles(Roles = "Partner")]
public class HomeController : MyController
{
...

但这行不通。当我使用角色为“合作伙伴”的用户访问此 Controller 时,我可以按照代码进入内部返回语句,但用户仍被重定向到登录页面而不是被授权。我在这里缺少什么?

最佳答案

不确定您是否使用表单例份验证。可能需要这样的东西?

[AllowRoles(Roles = "Partner")]
public class HomeController : MyController
{
FormsAuthentication.RedirectFromLoginPage( "User", false );
.
.
.
}

关于authentication - ASP.NET MVC4 覆盖 OnAuthorization 以允许角色白名单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12803139/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com