HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

IIdentity and IPrincipal Interfaces

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
andinterfacesiidentityiprincipal

Problem

I've always seen the IPrincipal and IIdentity interfaces separately, but I haven't seen any compelling reason for it, so I have my own interface that combines the two:

public interface IUser : System.Security.Principal.IIdentity, System.Security.Principal.IPrincipal {
    string Role { get; set; }
}


Then I implement the interface as:

public class User : IUser {
    public string Role { get; set; }

    public System.Security.Principal.IIdentity Identity {
        get { return this; }
    }

    public string AuthenticationType {
        get { throw new System.NotImplementedException(); }
    }

    public bool IsAuthenticated {
        get { throw new System.NotImplementedException(); }
    }

    public string Name {
        get { throw new System.NotImplementedException(); }
    }

    public bool IsInRole(string role) {
        throw new System.NotImplementedException();
    }
}


Does this smell? Do I have a security issue here?

Solution

While there are circumstances where you need to decouple the Principal from the Identity, in many applications this is not the case, and the distinction will only complicate the code. The way security is best handled in an application depends very much on the individual needs of the particular app.

Martin Fowler's article Dealing with Roles provides an in depth analysis on to the different patterns that can be used to implement role-based security, and the indications of necessity for each pattern.

In general, you can't make an assumption that a solution that separates the principal from the identity is the optimal solution for all applications. I have encountered many scenarios where it was unnecessary and added nothing but additional classes. In that case, it is better to merge the two interfaces.

Furthermore, these are interfaces not classes. An interface denotes a "has a" relationship between the instance and the definition, where as a class denotes an "is a" relationship. An instance of a User in the OP's example is an object that has both an Identity and a Principal (Security Context). You can always break things down to further levels of complexity, but if the application functionality doesn't indicate a reasonable need to separate the class, then Why would you do it?

Context

StackExchange Code Review Q#1442, answer score: 9

Revisions (0)

No revisions yet.