gpt4 book ai didi

c# - asp.net mvc 中基于角色的自定义用户授权

转载 作者:太空狗 更新时间:2023-10-29 21:39:09 26 4
gpt4 key购买 nike

我已经为我的用户创建了自定义身份验证和授权。我面临的问题是如何让 mvc 检查我的用户表中的角色是否与我的 Controller 上的 [Authorize(Role)] 相匹配,以便设置 httpauthorised为真。下面是我的 customauthorise 类。

 [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Controller.TempData["ErrorDetails"] = "You must be logged in to access this page";
filterContext.Result = new RedirectResult("~/User/Login");
return;
}

if (filterContext.HttpContext.Request.IsAuthenticated)
{
using (var db = new GManagerDBEntities())
{
var authorizedRoles = (from u in db.Users
where u.Username == filterContext.HttpContext.User.Identity.Name
select u.Role).FirstOrDefault();
Roles = String.IsNullOrEmpty(Roles) ? authorizedRoles.ToString() : Roles;
}
}

if (filterContext.Result is HttpUnauthorizedResult)
{
filterContext.Controller.TempData["ErrorDetails"] = "You do nat have necessary rights to access this page";
filterContext.Result = new RedirectResult("~/User/Login");
return;
}

}
public CustomAuthorizeAttribute(params object[] roles)
{
if (roles.Any(r => r.GetType().BaseType != typeof(Enum)))
throw new ArgumentException("roles");

this.Roles = string.Join(",", roles.Select(r => Enum.GetName(r.GetType(), r)));
}
}

下面是我的带装饰的 Controller

 [CustomAuthorize(Role.Administrator)]
[HttpGet]
public ActionResult CreateEmployees()
{
return View();
}

和我的角色枚举

public enum Role
{
Administrator = 1,
UserWithPrivileges = 2,
User = 3,
}

和模型

public class UserModel
{
public int UserID { get; set; }
[Required]
[Display(Name="Username:")]
public string Username { get; set; }
[Required]
public string Password { get; set; }
public int Role { get; set; }
}

查看馅饼以获得清晰 View pastie

我在尝试解决此问题时查看过链接,但我似乎无法将其拼凑起来 MVC 3 Authorize custom roles http://forums.asp.net/p/1573254/3948388.aspx

Customized authorization attribute in MVC 4 with Roles

最佳答案

使用@VikasRana 分享的链接 http://www.codeproject.com/Articles/578374/AplusBeginner-splusTutorialplusonplusCustomplusF

我摆脱了我的枚举角色和我的方法

public CustomAuthorizeAttribute(params object[] roles)
{ ...}

然后我将模型中的 Role 更改为一个字符串,例如User.Role="Admin"而不是 int。在我的 onAuthorization 方法中,我将其更改为:

` public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Controller.TempData["ErrorDetails"] = "You must be logged in to access this page";
filterContext.Result = new RedirectResult("~/User/Login");
return;
}
if (filterContext.Result is HttpUnauthorizedResult)
{
filterContext.Controller.TempData["ErrorDetails"] = "You don't have access rights to this page";
filterContext.Result = new RedirectResult("~/User/Login");
return;
}
}

并在我的 global.asax 中添加了这个。

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
if (FormsAuthentication.CookiesSupported == true && Request.IsAuthenticated== true)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
try
{
//let us take out the username now
string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
string roles = string.Empty;

using (GManagerDBEntities db = new GManagerDBEntities())
{
User user = db.Users.SingleOrDefault(u => u.Username == username);

roles = user.Role;
}
//let us extract the roles from our own custom cookie
//Let us set the Pricipal with our user specific details
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
}
catch (Exception)
{
//something went wrong
}
}
}
}

虽然上述方法并不理想。它会为每个简单的页面请求运行大约 3 次或更多。

所以这是解决方案 2:更好的解决方案实现自定义角色提供程序,因为我们已经在使用自定义角色实现。只需点击此链接 http://techbrij.com/custom-roleprovider-authorization-asp-net-mvc

关于c# - asp.net mvc 中基于角色的自定义用户授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25548545/

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