Wcf over https authentication with aspnet membership
In last article I explained how to configure WCF to secure a service with https, with no authentication, now I want to show you the configuration needed to enable role and user membership using a standard asp.net provider.
Here is the service definition on the server
the binding is wsHttpBinding, because we need to specify credentials, so we cannot use a basicHttpBinding, also the mex uses mexHttpsBinding because we are in https and not http. The interesting stuff is in the behavior and binding configuration.
As you can see you need to use httpsGetEnabled if you want to enable http get, but the interesting part is the serviceAuthorization node, that contains the principalPermissionMode attribute where you need to specify UseAspNetRoles, then the roleProviderName where you specify the name of the roleprovider. For serviceCredentials we have a similar configuration, you need to specify that userNamePasswordValidationMode is MembershipProvider and you need also to specify the membership provider name. These settings are needed to instruct wcf to use asp.net membership provider.
Finally you need to configure binding
The important part is the <security> tag, where you need to specify witch security mode you want to use, in my situation is TransportWithMessageCredential. This specify that the security is given by transport (https) and there are credentials in the message. Then you need to configure <transport> and <message>, since I want to transfer my credentials in message and not in transport, I specify clientCredentialType to none for <transport>, and to userName in <message> node.
Transport credential is used for windows login, and if you want to specify custom user name and password to validate against asp.net membership, you need to pass them into message part.
Now goes for the client configuration, first of all the binding
The important stuff is the <security> mode that is set again to TransportWithMessageCredential, and you need to specify in the trasport part that you have no credential and in message part you have UserName credential. Once you gets the server up and running you can simply use svcutil.exe to generate this one, so it is quite an automated task to do and does not worth further explanation. Now I can use the client in this way.
As you can see you need to specify credential in the wcf proxy client (in real code I use Castle Windsor to dynamically create proxy), and then in server you can write stuff like this.
If you call this method with a user that is not in role Superadministrator a SecurityException get raised. And clearly you can also access the Principal attached to current thread to verify roles programmatically if you need. All is gained for free, with no code, because wcf can use memberhsip api to validate user and password you specified in the message :) and since you use https, you does not need to deal with certificates, as I explained in older posts.