Friday, July 6, 2012

Creating And Setting Custom Principal

Authenticating a user internaly sets SecurityPrincipal Object at Thread level this patteren is used almost in every .net application e.g Web Application/Web Services/ Desktop applications and even Console Applications. What i needed was to set a custom defined object as security principal so that i can access additional parameters from it. This is what i came accross :

This is how i can get/set principal object using a Factory classs.

PrincipalFactory pf = new PrincipalFactory();
            pf.SetCurrentUser(new User() {UserID=1,Name="asasd" });
            var user = pf.GetCurrentUser();



Factory Class Code:

 public class PrincipalFactory
    {
        public MyCustomPrincipal GetCurrent()
        {
            return Thread.CurrentPrincipal as MyCustomPrincipal;
        }

        public User GetCurrentUser()
        {
            var principal = GetCurrent();
            return (principal != null ? principal.User : null);
        }

        public void SetCurrentUser(User user)
        {
            Thread.CurrentPrincipal = new MyCustomPrincipal(user);
        }
    }




My Custom Object that i want to be saved in Principle

 public class User
    {
        public int UserID { get; set; }
        public string Name { get; set; }
    }


Finally this is my Custom Principal that implements IPrincipal interface
 public class MyCustomPrincipal:IPrincipal
    {
        public MyCustomPrincipal(User user)
        {
            this.User = user;
        }
        public User User { get; set; }

        #region IPrincipal Members

        public IIdentity Identity
        {
            get { return WindowsIdentity.GetCurrent(); }
        }

        public bool IsInRole(string role)
        {
            return true;
        }

        #endregion
    }


No comments: