简体   繁体   中英

Authentication of external requests - how to pass user credentials in the SOAP header?

There is a simple WCF Web service. All external requests to the web service must be authenticated.

The contract of the Web- service:

namespace SimpleCustomService
{
    [ServiceContract]
    public interface UsrIService
    {
        [OperationContract]
        string SayHello();
    }
}

The implementation of the Web- service:

namespace SimpleCustomService
{
    public class UsrService : UsrIService
    {
        public string SayHello()
        {
            return "Hello";
        }
    }
}

By using the wsdl.exe utility I generate proxy class to invoke methods of the Web service.

The generated code looks as follows:

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Serialization;

// 
// This source code was auto-generated by wsdl, Version=4.6.1055.0.
// 


/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.6.1055.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="BasicHttpBinding_UsrIService", Namespace="http://tempuri.org/")]
public partial class UsrService : System.Web.Services.Protocols.SoapHttpClientProtocol {

    private System.Threading.SendOrPostCallback SayHelloOperationCompleted;

    /// <remarks/>
    public UsrService() {
        this.Url = "http://localhost:8080/0/ServiceModel/SimpleCustomService.svc/soap";
    }

    /// <remarks/>
    public event SayHelloCompletedEventHandler SayHelloCompleted;

    /// <remarks/>
    [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/UsrIService/SayHello", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
    [return: System.Xml.Serialization.XmlElementAttribute(IsNullable=true)]
    public string SayHello() {
        object[] results = this.Invoke("SayHello", new object[0]);
        return ((string)(results[0]));
    }

    /// <remarks/>
    public System.IAsyncResult BeginSayHello(System.AsyncCallback callback, object asyncState) {
        return this.BeginInvoke("SayHello", new object[0], callback, asyncState);
    }

    /// <remarks/>
    public string EndSayHello(System.IAsyncResult asyncResult) {
        object[] results = this.EndInvoke(asyncResult);
        return ((string)(results[0]));
    }

    /// <remarks/>
    public void SayHelloAsync() {
        this.SayHelloAsync(null);
    }

    /// <remarks/>
    public void SayHelloAsync(object userState) {
        if ((this.SayHelloOperationCompleted == null)) {
            this.SayHelloOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSayHelloOperationCompleted);
        }
        this.InvokeAsync("SayHello", new object[0], this.SayHelloOperationCompleted, userState);
    }

    private void OnSayHelloOperationCompleted(object arg) {
        if ((this.SayHelloCompleted != null)) {
            System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
            this.SayHelloCompleted(this, new SayHelloCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
        }
    }

    /// <remarks/>
    public new void CancelAsync(object userState) {
        base.CancelAsync(userState);
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.6.1055.0")]
public delegate void SayHelloCompletedEventHandler(object sender, SayHelloCompletedEventArgs e);

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.6.1055.0")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class SayHelloCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {

    private object[] results;

    internal SayHelloCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : 
            base(exception, cancelled, userState) {
        this.results = results;
    }

    /// <remarks/>
    public string Result {
        get {
            this.RaiseExceptionIfNecessary();
            return ((string)(this.results[0]));
        }
    }
}

I found this discussion and, I think, it is what is needed in my case:

I want to pass credentials in the SOAP header of the message. How to do it?

If I use this code:

using (UsrService client = new UsrService())
{
    client.ClientCredentials.UserName.UserName = "user";
    client.ClientCredentials.UserName.Password = "password";
    client.SayHello();
}

I get this error message:

"UsrService does not contain a difinition for ClientCredentials"

Should I include the missing code to the generated proxy class?

You should pass it the credential from the credential cache like so:

client.Credentials = System.Net.CredentialCache.DefaultCredentials;

or give it explicitly:

client.Credentials = new System.Net.NetworkCredential("username", "password");

Also I like to use client.PreAuthenticate = true; , but there may be issues around that, that I'm ignoring.

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