我是ASP.NET MVC的新手,并学习如何使用本教程中的FormAuthentication自定义角色link
以下代码存储在角色中。当我在控制器
中执行此[Authorize(Roles="admin")]
时,它工作正常
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
if (FormsAuthentication.CookiesSupported == 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 (userDbEntities entities = new userDbEntities())
{
User user = entities.Users.SingleOrDefault(u => u.username == username);
roles = user.Roles;
}
//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)
{
//somehting went wrong
}
}
}
}
有没有办法根据当前的User.Identity获取实际的角色名称?像下面的伪代码。
[Authorize]
public ActionResult Index()
{
bool isAdmin = System.Web.HttpContext.Current.User.IsInRole("admin"); // This also works correctly.
Response.Write("role: " + isAdmin);
string roleName = // The Code of How to get the actual Role Name
Response.Write("roleName: " + roleName); //e.g Admin, User...
return View();
}
答案 0 :(得分:1)
来自评论:你知道关于OWIN cookie的任何好文章吗? 用户名和角色的自定义表的身份验证?
它很少,所以我在GitHub中创建了一个示例项目AspNetMvcActiveDirectoryOwin。 原始资源是通过AD进行身份验证,但您只需要修改查询自定义表的ActiveDirectoryService类。
以下三个是主要类别 -
OwinAuthenticationService取代FormsAuthentication。