Benutzer:MovGP0/Basic HTTP Auth

  MovGP0    Über mich    Hilfen    Artikel    Weblinks    Literatur    Zitate    Notizen    Programmierung    MSCert    Physik   


Basic HTTP Auth

Classes

Client Credentials

/// <summary>/// http://stackoverflow.com/questions/3725294/set-wcf-clientcredentials-in-app-config/// </summary>public class UserNameClientCredentials : ClientCredentialsElement{    private ConfigurationPropertyCollection _properties;    public override Type BehaviorType    {        get { return typeof(ClientCredentials); }    }    /// <summary>    /// Username (required)    /// </summary>    public string UserName    {        get { return (string)base["userName"]; }        set { base["userName"] = value; }    }    /// <summary>    /// Password (optional)    /// </summary>    public string Password    {        get { return (string)base["password"]; }        set { base["password"] = value; }    }    protected override ConfigurationPropertyCollection Properties    {        get        {            if (_properties == null)            {                var baseProps = base.Properties;                baseProps.Add(new ConfigurationProperty("userName", typeof(String), null, null, new StringValidator(1), ConfigurationPropertyOptions.IsRequired));                baseProps.Add(new ConfigurationProperty("password", typeof(String), String.Empty));                _properties = baseProps;            }            return _properties;        }    }    protected override object CreateBehavior()    {        var creds = (ClientCredentials)base.CreateBehavior();        Debug.Assert(creds != null, "creds != null");        creds.UserName.UserName = UserName;        if (Password != null)            creds.UserName.Password = Password;        ApplyConfiguration(creds);        return creds;    }}

Message Inspector

/// <summary>/// http://msmvps.com/blogs/paulomorgado/archive/2007/04/27/wcf-building-an-http-user-agent-message-inspector.aspx /// </summary>public class BasicHttpAuthClientMessageInspector : IClientMessageInspector{    public object BeforeSendRequest(ref Message request, IClientChannel channel)    {        var creds = channel.Extensions.Find<UserNameClientCredentials>();        if (creds != null)        {            var httpRequestProperty = new HttpRequestMessageProperty();            httpRequestProperty.Headers[HttpRequestHeader.Authorization] = new BasicAuthHelper(creds.UserName, creds.Password).AuthHeader;            request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestProperty);        }        return null;    }    public void AfterReceiveReply(ref Message reply, object correlationState)    {    }}

Endpoint Behaviour

/// <summary>/// http://stackoverflow.com/questions/6309367/how-do-you-configure-a-messageinspector-when-using-standardendpoints-in-wcf-rest /// </summary>public class BasicHttpAuthEndpointBehavior : IEndpointBehavior{    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)    {        clientRuntime.MessageInspectors.Add(new BasicHttpAuthClientMessageInspector());    }    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)    {    }    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)    {    }    public void Validate(ServiceEndpoint endpoint)    {    }}

Configuration Section

public class BasicHttpAuthConfigurationSection : BehaviorExtensionElement, IServiceBehavior{    protected override object CreateBehavior()    {        return new BasicHttpAuthEndpointBehavior();    }    public override Type BehaviorType    {        get { return typeof (BasicHttpAuthEndpointBehavior); }    }    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)    {    }    public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)    {    }    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)    {    }}

Web.config

Behavior Extensions

<system.serviceModel>    <extensions>      <behaviorExtensions>        <add name="userNameClientCredentials" type="MyNamespace.UserNameClientCredentials, MyDllName, Version=1.0.0.0, Culture=neutral" />        <add name="basicHttpAuth" type="MyNamespace.BasicHttpAuthConfigurationSection, MyDllName, Version=1.0.0.0, Culture=neutral" />      </behaviorExtensions>    </extensions></system.serviceModel>

Endpoint

<system.serviceModel>    <standardEndpoints>      <webHttpEndpoint>        <standardEndpoint name="MyServiceEndpoint">          <security mode="Transport">            <transport clientCredentialType="Basic" proxyCredentialType="Basic" />          </security>        </standardEndpoint>      </webHttpEndpoint>    </standardEndpoints></system.serviceModel>

Behavior

<system.serviceModel>    <behaviors>      <endpointBehaviors>        <behavior name="MyServiceBehavior">          <userNameClientCredentials userName="********" password="********"> <!-- custom -->            <serviceCertificate>              <authentication certificateValidationMode="None" revocationMode="NoCheck" />            </serviceCertificate>          </userNameClientCredentials>          <dispatcherSynchronization asynchronousSendEnabled="true" maxPendingReceives="10" />          <basicHttpAuth /> <!-- custom -->        </behavior>    </behaviors></system.serviceModel>

Binding

<system.serviceModel>    <bindings>      <basicHttpBinding>        <binding name="MyServiceBinding"                  maxBufferPoolSize="41943040"                  maxBufferSize="5242880"                  maxReceivedMessageSize="5242880">          <security mode="Transport">            <transport clientCredentialType="Basic" proxyCredentialType="Basic" />          </security>          <readerQuotas maxDepth="2147483647"                         maxStringContentLength="2147483647"                         maxArrayLength="2147483647"                         maxBytesPerRead="2147483647"                         maxNameTableCharCount="2147483647" />        </binding>      </basicHttpBinding>    </bindings></system.serviceModel>

Client Configuration

<system.serviceModel>    <client>      <endpoint address="https://localhost:7777/MyService"                 behaviorConfiguration="MyServiceBehavior"                 binding="basicHttpBinding"                 bindingConfiguration="MyServiceBinding"                 contract="Namespace.MyContractClass"                 name="kabelplusOnlineServicesPort" />    </client>  </system.serviceModel>