Related to this question, I’ve got a custom UserNamePasswordValidator that logs in to our internal API. As part of this logging-in, I can discover the user’s roles in our system.
I’d like to later use these in PrincipalPermissionAttribute demands on the service methods, e.g.:
[OperationContract]
[PrincipalPermission(SecurityAction.Demand, Role = "System Administrator")]
public string HelloWorld()
{ /* ... */ }
To expand on Ladislav’s answer:
No. A custom UserNamePasswordValidator cannot be used as a role provider. The UserNamePasswordValidator runs in a separate context (or thread, or something) from the OperationContext that you want to mess with.
What you need to do instead is implement custom authorization. I found this page most useful for doing this. Warning: there’s a lot of plumbing before you get to the interesting bits.
Essentially, you start with a
ServiceCredentials-derived class, registered inApp.config, as follows:Associate the behavior with your service.
Override
ServiceCredentials.CreateSecurityTokenManagerto return aMySecurityTokenManager, derived fromServiceCredentialsSecurityTokenManager. On that, overrideCreateSecurityTokenAuthenticator, returning aMySecurityTokenAuthenticator. That should be derived fromCustomUserNameSecurityTokenAuthenticator. In that, overrideValidateUserNamePasswordCore. Call the base class, which will return a list of authorization policies.To that list, add a new one:
MyAuthorizationPolicy, which implementsIAuthorizationPolicy. In that, you merely (hah) need to do the following:And then, having done that lot, you can mark up your service operations with
PrincipalPermission: