How do you implement Roles and Security in your C# Domain Driven Design projects? We have some debate raging on whether it should be implemented by the calling application (ASP.
Don't forget that the runtime already has an abstracted security/user system built in - the principal (see this existing answer - note that GenericIdentity
is just one option; it is pretty trivial to write your own).
Your UI can handle creating and assigning the principal based on the specific implementation (indeed, IIRC ASP.NET and WCF do this automatically, or for winforms/wpf you can use the windows identity, or (via a web-service) the same ASP.NET login).
Your business logic then just checks Thread.CurrentPrincipal
; from this you can get the name, the authentication method, and check for roles (without needing to know how roles are implemented).
The runtime also provides inbuilt checks:
[PrincipalPermission(SecurityAction.Demand, Role = Roles.Admin)]
public void Foo() {...}
(where Roles.Admin
is a string constant of your role name) This will check access automatically, throwing a SecurityException
if not in the role. You can also check via code (useful if the role isn't fixed at compile time).
Obviously your UI should check roles (to disable/hide functionality), but it is good to have the business code enforce the roles without needing to know about the UI.
(added)
I should mention that GenericIdentity
is handy for unit tests. Of course, you could role your own security API, and nobody will stop you...