[英]MVC 4 Application, Windows Authentication, and Custom roles stored in a database
Good morning everyone, 大家,早安,
I have the following requirement for my MVC 4 Application. 我的MVC 4应用程序具有以下要求。
EDIT 编辑
Here is what i have tried so far: 到目前为止,这是我尝试过的:
Put this in my Global.asax file 把它放在我的Global.asax文件中
if (HttpContext.Current.User != null) { string[] roles = { "testmyrole" }; 如果(HttpContext.Current.User!= null){字符串[]角色= {“ testmyrole”}; GenericPrincipal principal = new GenericPrincipal(HttpContext.Current.User.Identity, roles);
GenericPrincipal主体=新的GenericPrincipal(HttpContext.Current.User.Identity,角色); Thread.CurrentPrincipal = HttpContext.Current.User = principal;
Thread.CurrentPrincipal = HttpContext.Current.User =主体; bool test = User.IsInRole("testmyrole");
布尔测试= User.IsInRole(“ testmyrole”); }
}
But the HttpContext.Current.User is always null... 但是HttpContext.Current.User始终为null ...
The string[] roles will eventually be populated by calling the database ... the hard code is just for testing right now. 最终将通过调用数据库来填充string []角色...硬代码仅用于测试。
Any ideas of where i can put the above piece of code in my MVC app so that no matter what View is called this code gets run so i can populate the roles and then use the following code in my other controllers 关于将上述代码放在我的MVC应用程序中的位置的任何想法,以便无论调用哪种View,此代码都可以运行,因此我可以填充角色,然后在其他控制器中使用以下代码
[Authorize(Roles ="testmyrole")]
public ActionResult Index()
{
... do other fun stuff here
}
Thank you for your time. 感谢您的时间。
Corey 科瑞
I think i may have found a solution to my problem. 我想我可能已经找到解决问题的办法。
So here is what i did: 所以这就是我所做的:
@using SMTRApp.Business; @using SMTRApp.Business;
@using System.Security.Principal; @using System.Security.Principal;
@using System.Threading; @using System.Threading;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
string[] roles = BusinessLayer.BLGetUserRoles(User.Identity.Name).ToArray();
GenericPrincipal principal = new GenericPrincipal(User.Identity, roles);
Thread.CurrentPrincipal = System.Web.HttpContext.Current.User = principal;
}
I then was able to put the following code at the beginning of my controllers to implement SQL role based security: 然后,我能够将以下代码放在控制器的开头,以实现基于SQL角色的安全性:
[Authorize(Roles = "Accounting, Analyst, ETL")]
Is there a better approach than this to implement role based security no matter how the view is invoked? 无论如何调用视图,是否有比此更好的方法来实现基于角色的安全性?
Any thoughts would be much appreciated. 任何想法将不胜感激。
Corey 科瑞
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.