有很多步骤,所以我只能给你一个方向。
最简单的方法是使用 OWIN Authentication Middle-ware,并将每个访问作为一个声明存储在 Principle Object 中,这样您就可以使用 ASP.Net 的 Authorize Attribute 构建。
示例代码 -
OWIN Authentication Middle-ware
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "ApplicationCookie",
LoginPath = new PathString("/Account/Login")
});
}
}
Store access as role claim in Principle object
public void SignIn(User user, IList<string> roleNames)
{
IList<Claim> claims = new List<Claim>
{
new Claim(ClaimTypes.Sid, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.GivenName, user.FirstName),
new Claim(ClaimTypes.Surname, user.LastName),
};
foreach (string roleName in roleNames)
{
claims.Add(new Claim(ClaimTypes.Role, roleName));
}
ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType);
IOwinContext context = _context.Request.GetOwinContext();
IAuthenticationManager authenticationManager = context.Authentication;
authenticationManager.SignIn(identity);
}
用法
[Authorize(Roles = "CanViewHome")]
public class IndexController : Controller
{
[Authorize(Roles = "CanEditHome")]
public ActionResult Edit()
{
return View();
}
}