Sunday, May 10, 2015

Role Based Security in .NET

In .NET prior to 4.5 was based out of IIdentity and IPrincipal which is an abstraction over how you would do authentication and authorization whether it is

  • Custom - GenericIdentity and GenericPrincipal
  • Windows - WindowsIdentity and WindowsPrincipal

Like Forms Authentication and <authorization /> (ASP.NET web.config) is SQL implementation of custom with membership and roles. But now we have a better way with Claims implementing ClaimsIdentity and ClaimsPrincipal (next blog post).

interface IIdentity
{
   string name;
   bool isAutheticated;
  string AuthencticatedType;
}

interface IPrincipal
{
   IIdentity identity;
   bool IsInRole();
}

Once the current user principal object is created, attach it to the Thread.CurrentPrincipal static property from where you can access it anywhere in your code. Though static, it is per thread so no thread collisions here and you can always get your correct security context in the thread.

TIP: Never check for Role using string role name as it can change, literal strings will not work with Globalization and will break your code. Instead use the SID (SecurityIdentifer id) values - those never change. also, unless the user is in the domain admin group, if UserAdmin is activated (windows 2003 and above?) then a user in the Builtin Admins group will not be automatically in the group unless explicitly/manually assigned! So that's why you need to execute some apps with Run As Administrator otherwise you might get thrown a security exception!(even though you are in the admin group)



No comments:

Post a Comment