C# Role-based security
I have a class library which contains my data base access layer, and i use it in all my projects which works with this DB, now i want to integrate security in this library so i can return different data for different security roles. What is the best way to achieve this with .NET build-in security? I was thinking about using System.Security.Permissions.PrincipalPermission but i can't see how it can help me out, because anyone using my library can write client application like this
GenericIdentity genericIdentity = new GenericIdentity("User");
GenericPrincipal genericPrincipal = new GenericPrincipal(genericIdent开发者_JS百科ity, new[] { "Administrator" });
Thread.CurrentPrincipal = genericPrincipal;
And they will pass all my principal permission demands
PrincipalPermission principalPermission = new PrincipalPermission(null, "Administrator");
principalPermission.Demand();
without even authenticating. Either i don't understand this security model, or it just doesn't secure anything.
Role-based security is intended as a way for library code to consume the client's chosen security model without needing to know the implementation; the key here being that you are already at a point where it is reasonably to trust the client's security model, and you just want to offer appropriate options based on decisions made by the client (for example as part of a login process).
If you don't trust the client, all bets are off anyway, as they could just use reflection to rip your internals to shreds. In that scenario, it would be better to keep that implementation code private, for example via a web-service that accepts the user's credentials in some fashion. Then they can only be accounts that they have the credentials for.
public class Example
{
// Will enforce that the user have the administrator role
[PrincipalPermission(XXXX, Role="Administrator")]
public void Remove(int userId)
{
}
public void Add(int userId)
{
if (!Thread.CurrentPrincipal.IsInRole("User"))
throw new UnauthorizedAccessException("Only registered users may add users");
}
}
How the actual principal/identity configuration is setup is up to the user of your library.
精彩评论