I'm integrating my WPF application with 2 WCF applications (one is an "Authentication Application" and the other is a "real" application that requires authentication). The "Authentication Application" returns 3 Set-Cookie
headers, and I need to add them to the request header of the "real" application. But I'm unsure of how to get those headers (only the result) I can get:
AuthenticationApplicationService.SoapClient authenticationSoapClient = new AuthenticationApplicationService.SoapClient("AuthenticationApplicationServiceSoap");
bool loggedInSuccess = await authenticationSoapClient.PerformLoginAsync();
// how do I get the cookie headers from this call and set them on the next?
RealService.SoapClient realSoapClient = new RealService.SoapClient("RealServiceSoap");
realSoapClient.PostAsync("hello");
That first call to PerformLoginAsync
returns true or false for successfully logged in, and the headers inclue Set-Cookie
. How can I grab those headers and set Cookie
headers on the next request to PostAsync
?
If there are further questions, please let me know!
You should use OperationContext, it has properties that could send cookie. To enable cookie , you should set the allowcookie property to true in your binding configuration.
<bindings>
<basicHttpBinding>
<binding name="AuthSoap" allowCookies="true" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:63599/Auth" binding="basicHttpBinding"
bindingConfiguration="AuthSoap" contract="Auth.AuthSoap" name="AuthSoap" />
</client>
Then you could call the login method as follows.
Auth.AuthSoapClient authSoapClient = new Auth.AuthSoapClient();
using (new OperationContextScope(authSoapClient.InnerChannel))
{
// please put the call of method in OperationContextScope
authSoapClient.Login("admin", "admin");
// the following code get the set-cookie header passed by server
HttpResponseMessageProperty response = (HttpResponseMessageProperty)
OperationContext.Current.IncomingMessageProperties[
HttpResponseMessageProperty.Name];
string header = response.Headers["Set-Cookie"];
// then you could save it some place
}
After you get the cookie, you should set it in your header every time you call your method.
Auth.AuthSoapClient authSoapClient = new Auth.AuthSoapClient();
using (new OperationContextScope(authSoapClient.InnerChannel))
{
//below code sends the cookie back to server
HttpRequestMessageProperty request = new HttpRequestMessageProperty();
request.Headers["Cookie"] = please get the cookie you stored when you successfully logged in
OperationContext.Current.OutgoingMessageProperties[
HttpRequestMessageProperty.Name] = request;
// please put the call of method in OperationContextScope
string msg = authSoapClient.GetMsg();
}
If you feel it troublesome to send cookie every time after successfully logging in. You could consider using MessageInspector, refer to the link's last piece of code https://megakemp.com/2009/02/06/managing-shared-cookies-in-wcf/