Reading, watching videos, googling around, I am very confused about how to connect WCF with an ASP.NET app that uses forms authentication with a MembershipProvider. I've seen a suggestion where you have use a specialized service host, explained here (http://msdn.microsoft.开发者_StackOverflow中文版com/en-us/library/bb398990.aspx][1]):
<%@ ServiceHost Language="C#"
Service="System.Web.ApplicationServices.AuthenticationService" %>
I've also seen an implementation that does it in a ServiceFactory:
ServiceHost serviceHost = new ServiceHost (typeof(MyServices), baseAddresses)
{
Credentials =
{
UserNameAuthentication =
{MembershipProvider = Membership.Provider}
},
Authorization =
{
PrincipalPermissionMode = PrincipalPermissionMode.UseAspNetRoles
}
};
serviceHost.Credentials.ServiceCertificate.SetCertificate(HttpContext.Current.Request.ServerVariables["HTTP_HOST"]);
Both methods are confusing to me. For the first one, where do I specify my specific service contract and what if I have several services? The second method is clearer. But in both cases what happens if I try to access a forms authentication protected directory, for instance, mysite/admin/myservice.svc? Does the security mechanism kick in on both the Service and directory access level? What if you wanted to use two different membership providers, one for the file access and another for the actual WCF service? This wouldn't be an unusual scenario.
Any help would be great, feeling dazed and confused.
The beauty of WCF is that this can be done in the web.config or via code-behind (whichever is your preference). The authentication for WCF is handled in the behavior. I've found it much easier to use the web.config for my bindings. Here is a quick example of how the server configuration would look.
<system.serviceModel>
<bindings>
<wsHttpBinding> <!-- required since BasicHttpBinding has no security model -->
<binding name="FormsAuthProvider">
<security mode="Message">
<message clientCredentialType="UserName" negotiateServiceCredentials="true"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="FormsAuthProvider">
<serviceCredentials>
<usernameAuthetication userNamePasswordValidationMode="MembershipProvider" membershipProviderName="formsProvider"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.web>
<membership>
<providers>
<add name="formsProvider" type="..."/>
</providers>
</membership>
</system.web>
This example configuration works on message security - not transport security (security mode). If you had directory security on the service itself it would be required to have been authenticated prior to consuming the service endpoint.
MSDN doesn't have this option listed as a common security scenario for some reason.
精彩评论