Ответ 1
Конечно, Identity
настолько мощный и гибкий, что вы можете настроить его. Используйте свое право пользователя в качестве претензии, а затем напишите индивидуальный AuthorizeAttribute
, чтобы проверить претензии, например, рассмотрите этот код:
[HttpPost]
public ActionResult Login(string username, string password)
{
if (_userManager.IsValid(username, password)) // your own user manager
{
var ident = new ClaimsIdentity(
new[]
{
// adding following 2 claim just for supporting default antiforgery provider
new Claim(ClaimTypes.NameIdentifier, username),
new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),
new Claim(ClaimTypes.Name, username),
// populate assigned user rightID form the DB and add each one as a claim
new Claim("UserRight","FirstAssignedUserRightID"),
new Claim("UserRight","SecondAssignedUserRightID"),
},
DefaultAuthenticationTypes.ApplicationCookie);
HttpContext.GetOwinContext().Authentication.SignIn(
new AuthenticationProperties { IsPersistent = false }, ident);
return RedirectToAction("MyAction"); // auth succeed
}
// invalid username or password
ModelState.AddModelError("", "invalid username or password");
return View();
}
И напишите атрибут авторизации, основанный на претензии:
public class ClaimsAccessAttribute : AuthorizeAttribute
{
// in the real world you could get claim value form the DB,
// I simplified the example
public string ClaimType { get; set; }
public string Value { get; set; }
protected override bool AuthorizeCore(HttpContextBase context)
{
return context.User.Identity.IsAuthenticated
&& context.User.Identity is ClaimsIdentity
&& ((ClaimsIdentity)context.User.Identity).HasClaim(x =>
x.Type == ClaimType && x.Value == Value);
}
}
В конце вам просто нужно добавить свой атрибут к своим действиям:
[ClaimsAccess(CliamType="UserRight",Value="YourRightID"]
public ActionResult MyAction()
{
// also you have access the authenticated user claims
// simply by casting User.Identity to ClaimsIdentity
// ((ClaimsIdentity)User.Identity).Claims
}
Я пропустил группу пользователей, чтобы упростить этот пример, а также я жестко закодировал некоторые части, которые вам нужно написать поставщику для извлечения из БД.