简体   繁体   中英

Basic Authentication for WCF

I am trying to do a very basic but secure username/password authentication with wcf.

However when I look at the value of the ServiceSecurityContext.Current.PrimaryIdentity; it contains the credentials of my windows machine and claims it is authorised (even though I have not yet done any authorisation) instead of the username and password I provided to the service.

My web.config of the service is as follows

<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <wsHttpBinding>
        <binding name="WsHttpBindingConfig">
          <security mode="TransportWithMessageCredential">
            <transport clientCredentialType="None" />
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </wsHttpBinding>

    </bindings>
    <protocolMapping>
        <add binding="wsHttpBinding" scheme="http" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

and the app.config of the client app is as follows

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <system.serviceModel>
        <bindings>
            <wsHttpBinding>
                <binding name="WSHttpBinding_IService1" />
            </wsHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost/WcfSecuredService/Service1.svc"
                binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService1"
                contract="ServiceReference1.IService1" name="WSHttpBinding_IService1">
            </endpoint>
        </client>
    </system.serviceModel>
</configuration>

I call the service with the following code

ServiceReference1.Service1Client clnt = new ServiceReference1.Service1Client();
            clnt.ClientCredentials.UserName.UserName = "peter";
            clnt.ClientCredentials.UserName.Password = "grr";

            string result=clnt.GetSecuredData();

What am I doing wrong?

Please note that both the client app and the service are both running on the same machine. I do not know if the identity is that of the machine running the service or the one passed to it from the client as they are both the same credentials.....

I suppose the other question is possibly "How do I get the username and password that were passed to the service?"

I have worked this out now

I needed to create a custom validation class which I found here How to: Use a Custom User Name and Password Validator

I also needed to make a few changes to the web.config

<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceCredentials>
            <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WcfService1Secure.Auth,WcfService1Secure" />
          </serviceCredentials>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <wsHttpBinding>
        <binding name="WsHttpBindingConfig">
          <security mode="TransportWithMessageCredential">
            <transport clientCredentialType="None" />
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </wsHttpBinding>

    </bindings>
    <protocolMapping>
        <add binding="wsHttpBinding" scheme="https" bindingConfiguration="WsHttpBindingConfig" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

and the app.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>

    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IService1" />
            </basicHttpBinding>
            <wsHttpBinding>
                <binding name="WSHttpBinding_IService1">
                    <security mode="TransportWithMessageCredential">
                        <transport clientCredentialType="None" />
                        <message clientCredentialType="UserName" />
                    </security>
                </binding>
            </wsHttpBinding>
        </bindings>
        <client>
            <endpoint address="https://localhost/WcfService1Secure/Service1.svc"
                binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService1"
                contract="ServiceReference1.IService1" name="WSHttpBinding_IService1" />
        </client>
    </system.serviceModel>
</configuration>

Now the user is validated on the request and the username is available using

ServiceSecurityContext.Current.PrimaryIdentity;

hi you should add a method that can accept login and password on your server side and store them in a variables or db
your method should look like this

ServiceReference1.Service1Client clnt = new ServiceReference1.Service1Client();
clnt.ClientCredentials.UserName.UserName = "peter";
clnt.ClientCredentials.UserName.Password = "grr";

clnt.SignUp(clnt);  

or

clnt.SignUp(login,password); 

what you are doing can work on a standalone application but not in a webcall your call to method service will have something like

http://MyService/IMyContract/MyAction1

Hope this help

If you are using PerSession instance then you can call first Authenticate on server and on successful maintain a flag on server, subsequent call will check for the flag before executing. that means client need to make first call to Authenticate method and then only call other methods.

If not using PerSession instance you can create own proxy class for the server and while creating proxy instance accept LoginName/Password which it can pass in header on each call and on server side implement custom ServiceAuthorizationManager, it can retrieve credential from OperationContext.Current.IncomingMessageHeaders and validates it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM