I am working on asp.net mvc application and mongodb as database. Now i want to implement role based security and permissions. e.g we have roles "user" and "admin". Now one user "A" with role "user" have permission to view pages while some other user say "B" can have permission to view and edit content of page and user with role "admin" can have all rights view, edit, add and delete. So basically i want access control listing. Please let me know best way to acheive this using mongodb.
Thanks
There are lot of steps, so I could only give you a direction.
Easiest way is to use OWIN Authentication Middle-ware, and store each access as a claim inside Principle Object, so that you can use ASP.Net's build in Authorize Attribute.
Sample code -
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();
}
}