Can't get WCF WebCannelFactory BeforeSendRequest to work - wcf

The first code block returns a good request. The second returns a fault. Please advise.
The first code block returns information about a customer, and it uses OAuth2. The second block uses an interceptor. The problem is that when I use a WebChannelFactory and look at my request in trace, it shows (compared to a good request) that everything (the body of the request) is put into the message block. In a good request, the body of my request, is put into the soap message.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading.Tasks;
namespace Ahcccs.Isd.Aes.Breaz.Core.WCF.SOAP
{
public class ConsumeGetVendorLookup
{
public void Consume(string wso2token)
{
Header header = new Header();
header.Type = "?";
header.ReturnCode = "?";
header.Requestor = "?";
header.Recipient = "?";
header.Date = "?";
Requestor requestor = new Requestor();
requestor.UserID = "";
requestor.Password = "";
header.Subject = requestor;
Payload payload = new Payload();
GetVendorCustomerIn getVendorCustomer = new GetVendorCustomerIn();
getVendorCustomer.IncludeGeneralInfo = true;
getVendorCustomer.IncludeHeadquarters = true;
getVendorCustomer.IncludePrenote_EFT = true;
getVendorCustomer.IncludePrenote_EFTSpecified = true;
getVendorCustomer.Vendor_Customer = "{our customer number}";
payload.GetVendorCustomerIn = getVendorCustomer;
AdvMessage advMessage = new AdvMessage();
advMessage.Header = header;
advMessage.Payload = payload;
GetVendorCustomer customer = new GetVendorCustomer();
customer.AdvMessage = advMessage;
VendorServicesClient wcfClient = new VendorServicesClient();
var s = wcfClient.State;
wcfClient.Open();
using (new OperationContextScope(wcfClient.InnerChannel))
{
WebProxy wproxy = new WebProxy(new Uri("http://{our proxy server and port}"), true);
wproxy.BypassProxyOnLocal = true;
wproxy.UseDefaultCredentials = true;
WebRequest.DefaultWebProxy = wproxy;
// Add a HTTP Header to an outgoing request
HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();
requestMessage.Headers["Authorization"] = " Bearer " + wso2token;
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;
var result = wcfClient.getVendorCustomer(customer);
}
}
}
}
This one returns a fault:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;
namespace Ahcccs.Isd.Aes.Breaz.Core.WCF.SOAP
{
public class ConsumeGetVendorLookup
{
public void Consume(string wso2token)
{
Header header = new Header();
header.Type = "?";
header.ReturnCode = "?";
header.Requestor = "?";
header.Recipient = "?";
header.Date = "?";
Requestor requestor = new Requestor();
requestor.UserID = "";
requestor.Password = "";
header.Subject = requestor;
Payload payload = new Payload();
GetVendorCustomerIn getVendorCustomer = new GetVendorCustomerIn();
getVendorCustomer.IncludeGeneralInfo = true;
getVendorCustomer.IncludeHeadquarters = true;
getVendorCustomer.IncludePrenote_EFT = true;
getVendorCustomer.IncludePrenote_EFTSpecified = true;
getVendorCustomer.Vendor_Customer = "{our customer number}";
payload.GetVendorCustomerIn = getVendorCustomer;
AdvMessage advMessage = new AdvMessage();
advMessage.Header = header;
advMessage.Payload = payload;
GetVendorCustomer customer = new GetVendorCustomer();
customer.AdvMessage = advMessage;
getVendorCustomerRequest customerReq = new getVendorCustomerRequest();
customerReq.getVendorCustomer = customer;
//VendorServicesClient wcfClient = new VendorServicesClient();
//var s = wcfClient.State;
//wcfClient.Open();
var wcfClient = new WebChannelFactory<VendorServicesChannel>(
new Uri("{the target uri}"));
//var s = wcfClient.State;
//wcfClient.Open();
wcfClient.Endpoint.EndpointBehaviors.Add(new AuthenticationHeaderBehavior("txtUser", "txtPass", wso2token));
//using (new OperationContextScope(wcfClient.InnerChannel))
//{
// WebProxy wproxy = new WebProxy(new Uri("our proxy server and port"), true);
// wproxy.BypassProxyOnLocal = true;
// wproxy.UseDefaultCredentials = true;
// WebRequest.DefaultWebProxy = wproxy;
// // Add a HTTP Header to an outgoing request
// HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();
// requestMessage.Headers["Authorization"] = " Bearer " + wso2token;
// OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;
// var result = wcfClient.getVendorCustomer(customer);
//}
var proxy = wcfClient.CreateChannel();
using ((IDisposable)proxy)
using (OperationContextScope c = new OperationContextScope((IContextChannel)proxy))
{
//WebProxy wproxy = new WebProxy(new Uri("our proxy server and port"), true);
//wproxy.BypassProxyOnLocal = true;
//wproxy.UseDefaultCredentials = true;
//WebRequest.DefaultWebProxy = wproxy;
//Add a HTTP Header to an outgoing request
//HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();
//requestMessage.Headers["Authorization"] = " Bearer " + wso2token;
//OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;
var result = proxy.getVendorCustomer(customerReq);
}
}
}
public class AuthenticationHeader : IClientMessageInspector
{
#region Implementation of IClientMessageInspector
string itsUser;
string itsPass;
string itsToken;
public AuthenticationHeader(string user, string pass, string token)
{
itsUser = user;
itsPass = pass;
itsToken = token;
}
public object BeforeSendRequest(ref Message request,
IClientChannel channel)
{
//HttpRequestMessageProperty hrmp = request.Properties["httpRequest"] as HttpRequestMessageProperty;
//string encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(itsUser + ":" + itsPass));
//hrmp.Headers.Add("Authorization", "Basic " + encoded);
//return request;
//HttpRequestMessageProperty hrmp = request.Properties["httpRequest"] as HttpRequestMessageProperty;
//hrmp.Headers.Add("Authorization", " Bearer " + itsToken);
//HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();
//requestMessage.Headers["Authorization"] = " Bearer " + itsToken;
//OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;
//return request;
WebProxy wproxy = new WebProxy(new Uri("our proxy server and port"), true);
wproxy.BypassProxyOnLocal = true;
wproxy.UseDefaultCredentials = true;
WebRequest.DefaultWebProxy = wproxy;
//// Add a HTTP Header to an outgoing request
HttpRequestMessageProperty hrmp = request.Properties["httpRequest"] as HttpRequestMessageProperty;
hrmp.Headers["Authorization"] = " Bearer " + itsToken;
return request;
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
//Console.WriteLine("Received the following reply: '{0}'", reply.ToString());
}
#endregion
}
public class AuthenticationHeaderBehavior : IEndpointBehavior
{
#region Implementation of IEndpointBehavior
readonly string itsUser;
readonly string itsPass;
readonly string itsToken;
public AuthenticationHeaderBehavior(string user, string pass, string token)
: base()
{
itsUser = user;
itsPass = pass;
itsToken = token;
}
public void Validate(ServiceEndpoint endpoint) { }
public void AddBindingParameters(ServiceEndpoint endpoint,
BindingParameterCollection bindingParameters) { }
public void ApplyDispatchBehavior(ServiceEndpoint endpoint,
EndpointDispatcher endpointDispatcher) { }
public void ApplyClientBehavior(ServiceEndpoint endpoint,
ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(new AuthenticationHeader(itsUser, itsPass, itsToken));
}
#endregion
}
}

I think the answer is that I forgot the binding for my channel.

Related

Receiving error while fetching mails using Aspose Email dll and Microsoft Graph Client API

Below is the code part along with error being received
Error received
Aspose.Email.AsposeBadServerResponceException: 'Server error Status: ResourceNotFound
Description: Resource could not be discovered.
Details:
GET: https://graph.microsoft.com/v1.0/users/1234outlook.onmicrosoft.com/mailFolders
Authorization: Bearer xxxxxx
Accept: application/json
Code 1
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Aspose.Email.Clients;
using Aspose.Email.Clients.Graph;
using Aspose.Email.Mapi;
using Azure.Identity;
using EASendMail;
using Microsoft.Graph;
namespace Code
{
internal class Graph_API
{
private static string _clientId = ConfigurationManager.AppSettings["ClientId"];
private static string _tenantId = ConfigurationManager.AppSettings["TenantId"];
private static string _secretValue = ConfigurationManager.AppSettings["SecretValue"];
static string _postString(string uri, string requestData)
{
HttpWebRequest httpRequest = WebRequest.Create(uri) as HttpWebRequest;
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
using (Stream requestStream = httpRequest.GetRequestStream())
{
byte[] requestBuffer = Encoding.UTF8.GetBytes(requestData);
requestStream.Write(requestBuffer, 0, requestBuffer.Length);
requestStream.Close();
}
try
{
HttpWebResponse httpResponse = httpRequest.GetResponse() as HttpWebResponse;
var responseText = new StreamReader(httpResponse.GetResponseStream()).ReadToEnd();
Console.WriteLine(responseText);
return responseText;
}
catch (WebException ep)
{
if (ep.Status == WebExceptionStatus.ProtocolError)
{
var responseText = new StreamReader(ep.Response.GetResponseStream()).ReadToEnd();
Console.WriteLine(responseText);
}
throw ep;
}
}
public string GenerateToken()
{
string client_id = _clientId;
string client_secret = _secretValue;
string tenant = _tenantId;
string requestData =
string.Format("client_id={0}&client_secret={1}" +
"&scope=https://graph.microsoft.com/.default&grant_type=client_credentials",
client_id, client_secret);
string tokenUri = string.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", tenant);
string responseText = _postString(tokenUri, requestData);
OAuthResponseParser parser = new OAuthResponseParser();
parser.Load(responseText);
var vv = parser.AccessToken;
return vv;
}
public void Generatemail()
{
interface_class bb = new interface_class();
IGraphClient client = GraphClient.GetClient(bb, _tenantId);
client.Resource = (ResourceType)1;
client.ResourceId = "1234outlook.onmicrosoft.com";
MapiMessage mm = new MapiMessage();
mm.Subject = "EMAILNET-39318 " + Guid.NewGuid().ToString();
mm.Body = "EMAILNET-39318 REST API v1.0 - Create Message";
mm.SetProperty(KnownPropertyList.DisplayTo, "1234outlook.onmicrosoft.com");
mm.SetProperty(KnownPropertyList.SenderName, "1234outlook.onmicrosoft.com");
mm.SetProperty(KnownPropertyList.SentRepresentingEmailAddress, "1234outlook.onmicrosoft.com");
// Create message in inbox folder
MapiMessage createdMessage = client.CreateMessage(Aspose.Email.Clients.Graph.KnownFolders.Inbox, mm);
}
public void FetchMail()
{
try
{
interface_class bb = new interface_class();
using (IGraphClient client = GraphClient.GetClient(bb, _tenantId))
{
client.Resource = (ResourceType)1;
client.ResourceId = "1234outlook.onmicrosoft.com";
FolderInfoCollection folderInfoCol1 = client.ListFolders();
FolderInfo inbox = null;
foreach (FolderInfo folderInfo in folderInfoCol1)
{
if (folderInfo.DisplayName.Equals("Inbox", StringComparison.InvariantCultureIgnoreCase))
{
inbox = folderInfo;
break;
}
}
MessageInfoCollection messageInfoCol = client.ListMessages(inbox.ItemId);
MessageInfo messageInfo = messageInfoCol[0];
MapiMessage message = client.FetchMessage(messageInfo.ItemId);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
--------------
Code file 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aspose.Email.Clients;
using Aspose.Email.Clients.Graph;
namespace Code
{
internal class interface_class : ITokenProvider
{
Graph_API obj = new Graph_API();
DateTime expirationDate = DateTime.Today.AddDays(1);
public void Dispose()
{
throw new NotImplementedException();
}
public OAuthToken GetAccessToken()
{
string token = obj.GenerateToken();
return new OAuthToken(token, expirationDate);
}
public OAuthToken GetAccessToken(bool ignoreExistingToken)
{
throw new NotImplementedException();
}
}
}

How to solve this circular dependency problem?

I have two interfaces for components that each requires functionality from the other one. One that generates Oauth tokens, and another one that gets secrets from a secret provider (Azure Key Vault).
The problem is that the Token Provider needs to obtain a secret value (a password) to make its HTTP call, and the Secret Provider class needs to get a Token in order to call Azure. Chicken and Egg problem.
From the other questions I've read, one suggestion is to create a third class/interface on which the original 2 depend, but I'm not sure how that would work here.
Any help and suggestions would be appreciated. Code for all relevant classes/interfaces is shown below.
public interface ISecretProvider
{
string GetSecret(string secretName);
}
public interface ITokenProvider
{
string GetKeyVaultToken();
}
public class OktaTokenProvider : ITokenProvider
{
ISecretProvider _secretProvider;
public string GetKeyVaultToken()
{
var tokenUrl = ConfigurationManager.AppSettings["KeyVault.Token.Url"];
var clientId = ConfigurationManager.AppSettings["KeyVault.Token.ClientId"];
var clientSecret = _secretProvider.GetSecret("ClientSecret");
var scope = ConfigurationManager.AppSettings["KeyVault.Scope"];
var token = GetToken(tokenUrl, clientId, clientSecret, scope);
return token;
}
private string GetToken(string tokenUrl, string clientId, string clientSecret, string scope)
{
var clientCredentials = $"Basic {Convert.ToBase64String(Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}"))}";
string responseFromServer = string.Empty;
bool success = false;
int retryCount = 0;
while (!success)
{
try
{
var tokenWebRequest = (HttpWebRequest)WebRequest.Create(tokenUrl);
tokenWebRequest.Method = "POST";
tokenWebRequest.Headers.Add($"Authorization:{clientCredentials}");
tokenWebRequest.Headers.Add("Cache-control:no-cache");
tokenWebRequest.ContentType = "application/x-www-form-urlencoded";
using (var streamWriter = new StreamWriter(tokenWebRequest.GetRequestStream()))
{
streamWriter.Write($"grant_type=client_credentials&scope={scope}");
streamWriter.Flush();
streamWriter.Close();
}
using (WebResponse response = tokenWebRequest.GetResponse())
{
using (var dataStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseFromServer = reader.ReadToEnd();
reader.Close();
}
dataStream.Close();
}
response.Close();
response.Dispose();
}
success = true;
}
catch (Exception)
{
if (retryCount > 3)
{
throw;
}
else
{
retryCount++;
}
}
}
JToken token = JObject.Parse(responseFromServer);
var accessToken = $"Bearer {token.SelectToken("access_token").ToString()}";
return accessToken;
}
}
public class KeyVaultSecretProvider : ISecretProvider
{
ITokenProvider _tokenProvider;
public KeyVaultSecretProvider(ITokenProvider tokenProvider)
{
_tokenProvider = tokenProvider;
}
public string GetSecret(string secretName)
{
var KeyVaultUrl = ConfigurationManager.AppSettings[Constants.KEYVAULT_ENDPOINT];
var subscriptionKey = ConfigurationManager.AppSettings[Constants.KEYVAULT_SUBSCRIPTION_KEY];
string responseFromServer = "";
var requestedSecretUrl = $"{KeyVaultUrl}{secretName}";
var secretWebRequest = (HttpWebRequest)WebRequest.Create(requestedSecretUrl);
var accessToken = _tokenProvider.GetKeyVaultToken();
secretWebRequest.Method = "GET";
secretWebRequest.Headers.Add("authorization:" + accessToken);
secretWebRequest.Headers.Add("cache-control:no-cache");
secretWebRequest.Headers.Add("Ocp-Apim-Subscription-Key:" + subscriptionKey);
using (WebResponse response = secretWebRequest.GetResponse())
{
using (var dataStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseFromServer = reader.ReadToEnd();
reader.Close();
}
dataStream.Close();
}
response.Close();
response.Dispose();
}
JToken secret = JObject.Parse(responseFromServer);
var secretValue = secret.SelectToken("Secret").ToString();
return secretValue;
}
}
Have a single class implement both interfaces. The two responsibilities are inter-dependent, so put them together in one class. There is nothing wrong with this.

TwitterSettings.OAuthVersion

i don't understand that : GetRequestToken is not working in TweetSharp on Windows Phone
My code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp2.Resources;
using TweetSharp;
namespace PhoneApp2
{
public partial class MainPage : PhoneApplicationPage
{
private const string consumerKey = "zvBvaKjEQRwGqu9ECaNfop0pr";
private const string consumerSecret = "SgEqsMRcIrEYNrtXhvtYdnx7qBA9EITzswneyjf8wRorDvSAvn";
private TwitterService myclient;
private OAuthRequestToken requestToken;
private bool userAuthenticated = false;
// Constructeur
public MainPage()
{
InitializeComponent();
myclient = new TwitterService(consumerKey, consumerSecret);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//If user is already logged in, just send the tweet, otherwise get the RequestToken
if (userAuthenticated)
//send the Tweet, this is just a placeholder, we will add the actual code later
Dispatcher.BeginInvoke(() => { MessageBox.Show("Placeholder for tweet sending"); });
else
myclient.GetRequestToken(processRequestToken);
}
private void processRequestToken(OAuthRequestToken token, TwitterResponse response)
{
if (token == null)
Dispatcher.BeginInvoke(() => { MessageBox.Show("Error getting request token"); });
else
{
requestToken = token;
Dispatcher.BeginInvoke(() =>
{
Browser.Visibility = System.Windows.Visibility.Visible;
Browser.Navigate(myclient.GetAuthorizationUri(requestToken));
});
}
}
}
}
and visual studio 2013 create an error on myclient.GetRequestToken(processRequestToken); ...
how can incorporate your solution with hammock on my code?
I had this identical error last week (doing this app) The solution was to implement the Hammock Library instead of tweet sharp. Also in the post tweet example change the version from 1 to 1.1
This is the Nokia Developer Documentation I followed to implement logging in
This is the Nokia Developer Documentation I followed to implement posting a tweet
REMEMBER CHANGE THE VERSION TO 1.1 LIKE THIS
From this
var credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = AppSettings.consumerKey,
ConsumerSecret = AppSettings.consumerKeySecret,
Token = this.accessToken,
TokenSecret = this.accessTokenSecret,
Version = "1.0"
};
var restClient = new RestClient
{
Authority = "http://api.twitter.com",
HasElevatedPermissions = true
};
var restRequest = new RestRequest
{
Credentials = credentials,
Path = "/1/statuses/update.json",
Method = WebMethod.Post
};
restRequest.AddParameter("status", txtTweetContent.Text);
restClient.BeginRequest(restRequest, new RestCallback(PostTweetRequestCallback));
To This
var credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = AppSettings.consumerKey,
ConsumerSecret = AppSettings.consumerKeySecret,
Token = this.accessToken,
TokenSecret = this.accessTokenSecret,
Version = "1.0"
};
var restClient = new RestClient
{
Authority = "http://api.twitter.com",
HasElevatedPermissions = true
};
var restRequest = new RestRequest
{
Credentials = credentials,
Path = "/1.1/statuses/update.json",
Method = WebMethod.Post
};
restRequest.AddParameter("status", txtTweetContent.Text);
restClient.BeginRequest(restRequest, new RestCallback(PostTweetRequestCallback));

Private key is not present in x509

Why am I getting this exception. The private key is not present in x509 certificate
This is to generate a username with nonce+ 2 binary security tokens(one for the usercertificate and one for the server).
My user certificate has a private key but the server certificate does not have one.
This is for Asymmetric binding.
using System;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Security;
using System.Text;
namespace MYEmedny
{
public class CustomCredentials : ClientCredentials
{
private X509Certificate2 clientAuthCert;
private X509Certificate2 clientSigningCert;
public CustomCredentials() : base() { }
public CustomCredentials(CustomCredentials other)
: base(other)
{
// other.clientSigningCert = SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, "LMWARD");
clientSigningCert = other.clientSigningCert;
clientAuthCert = other.clientAuthCert;
}
protected override ClientCredentials CloneCore()
{
CustomCredentials scc = new CustomCredentials(this);
return scc;
}
public CustomCredentials(X509Certificate2 ClientAuthCert, X509Certificate2 ClientSigningCert)
: base()
{
clientAuthCert = ClientAuthCert;
clientSigningCert = ClientSigningCert;
}
public X509Certificate2 ClientAuthCert
{
get { return clientAuthCert; }
set { clientAuthCert = value; }
}
public X509Certificate2 ClientSigningCert
{
get { return clientSigningCert; }
set { clientSigningCert = value; }
}
public override SecurityTokenManager CreateSecurityTokenManager()
{
return new CustomTokenManager(this);
}
}
public class CustomTokenManager : ClientCredentialsSecurityTokenManager
{
private CustomCredentials custCreds;
public CustomTokenManager(CustomCredentials CustCreds)
: base(CustCreds)
{
custCreds = CustCreds;
}
public override SecurityTokenProvider CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement)
{
try
{
if (tokenRequirement.TokenType == SecurityTokenTypes.X509Certificate)
{
x509CustomSecurityTokenProvider prov;
object temp = null;
//TransportSecurityBindingElement secBE = null;
AsymmetricSecurityBindingElement secBE = null;
if (tokenRequirement.Properties.TryGetValue("http://schemas.microsoft.com/ws/2006/05/servicemodel/securitytokenrequirement/SecurityBindingElement", out temp))
{
//secBE = (TransportSecurityBindingElement)temp;
secBE = (AsymmetricSecurityBindingElement)temp;
}
if (secBE == null)
prov = new x509CustomSecurityTokenProvider(custCreds.ClientAuthCert);
else
prov = new x509CustomSecurityTokenProvider(custCreds.ClientSigningCert);
return prov;
}
}
catch (Exception ex)
{
throw ex;
}
return base.CreateSecurityTokenProvider(tokenRequirement);
}
public override System.IdentityModel.Selectors.SecurityTokenSerializer CreateSecurityTokenSerializer(System.IdentityModel.Selectors.SecurityTokenVersion version)
{
return new CustomTokenSerializer(System.ServiceModel.Security.SecurityVersion.WSSecurity10);
}
}
class x509CustomSecurityTokenProvider : SecurityTokenProvider
{
private X509Certificate2 clientCert;
public x509CustomSecurityTokenProvider(X509Certificate2 cert)
: base()
{
clientCert = cert;
}
protected override SecurityToken GetTokenCore(TimeSpan timeout)
{
return new X509SecurityToken(clientCert);
}
}
public class CustomTokenSerializer : WSSecurityTokenSerializer
{
public CustomTokenSerializer(SecurityVersion sv) : base(sv) { }
protected override void WriteTokenCore(System.Xml.XmlWriter writer, System.IdentityModel.Tokens.SecurityToken token)
{
if (writer == null)
{
throw new ArgumentNullException("writer");
}
if (token == null)
{
throw new ArgumentNullException("token");
}
if (token.GetType() == new UserNameSecurityToken("x", "y").GetType())
{
UserNameSecurityToken userToken = token as UserNameSecurityToken;
if (userToken == null)
{
throw new ArgumentNullException("userToken: " + token.ToString());
}
string tokennamespace = "wsse";
DateTime created = DateTime.Now;
string createdStr = created.ToString("yyyy-MM-ddThh:mm:ss.fffZ");
string phrase = Guid.NewGuid().ToString();
string nonce = GetSHA1String(phrase);
string password = userToken.Password;
//string password = userToken.Password;
writer.WriteStartElement(tokennamespace, "UsernameToken", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
writer.WriteAttributeString("wsu", "Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", token.Id);
writer.WriteElementString(tokennamespace, "Username", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", userToken.UserName);
writer.WriteStartElement(tokennamespace, "Password", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
writer.WriteAttributeString("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
writer.WriteValue(password);
writer.WriteEndElement();
writer.WriteStartElement(tokennamespace, "Nonce", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
writer.WriteAttributeString("EncodingType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary");
writer.WriteValue(nonce);
writer.WriteEndElement();
writer.WriteElementString(tokennamespace, "Created", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", createdStr);
writer.WriteEndElement();
writer.Flush();
}
else
{
base.WriteTokenCore(writer, token);
}
}
protected string GetSHA1String(string phrase)
{
SHA1CryptoServiceProvider sha1Hasher = new SHA1CryptoServiceProvider();
byte[] hashedDataBytes = sha1Hasher.ComputeHash(Encoding.UTF8.GetBytes(phrase));
return Convert.ToBase64String(hashedDataBytes);
}
}//CustomTokenSerializer
}
This is how I am using it
private CustomBinding GetCustomBinding()
{
AsymmetricSecurityBindingElement secBE = (AsymmetricSecurityBindingElement)SecurityBindingElement.CreateMutualCertificateBindingElement
(
MessageSecurityVersion.WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10
);
secBE.ProtectTokens = false;
X509SecurityTokenParameters x509ProtectionParameters = new X509SecurityTokenParameters();
x509ProtectionParameters.RequireDerivedKeys = false;
x509ProtectionParameters.X509ReferenceStyle = X509KeyIdentifierClauseType.SubjectKeyIdentifier;
x509ProtectionParameters.ReferenceStyle = SecurityTokenReferenceStyle.Internal;
//x509ProtectionParameters.InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient;
secBE.MessageSecurityVersion = System.ServiceModel.MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12;
secBE.InitiatorTokenParameters = x509ProtectionParameters;
secBE.RecipientTokenParameters = x509ProtectionParameters;
secBE.MessageProtectionOrder = System.ServiceModel.Security.MessageProtectionOrder.SignBeforeEncrypt;
secBE.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
secBE.EnableUnsecuredResponse = true;
secBE.SetKeyDerivation(false);
secBE.DefaultAlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.TripleDesRsa15;
secBE.EndpointSupportingTokenParameters.Signed.Add(new UserNameSecurityTokenParameters());
secBE.ProtectTokens = true;
// secBE.in = SecurityTokenInclusionMode.Never, RequireDerivedKeys = false );
secBE.EnableUnsecuredResponse = true;
secBE.IncludeTimestamp = false;
TextMessageEncodingBindingElement textEncBE = new TextMessageEncodingBindingElement(MessageVersion.Soap11WSAddressing10, System.Text.Encoding.UTF8);
HttpsTransportBindingElement httpsBE = new HttpsTransportBindingElement();
httpsBE.RequireClientCertificate = true;
CustomBinding myBinding = new CustomBinding();
myBinding.Elements.Add(secBE);
myBinding.Elements.Add(textEncBE);
myBinding.Elements.Add(httpsBE);
return myBinding;
}
ProxyGeneration.MHSClient proxy = new ProxyGeneration.MHSClient(GetCustomBinding(), new EndpointAddress(new Uri("https://service100.emedny.org:9047/MHService"), EndpointIdentity.CreateDnsIdentity("DPMedsHistory"), new AddressHeaderCollection()));
var vs = proxy.Endpoint.Behaviors.Where((i) => i.GetType().Namespace.Contains("VisualStudio"));
proxy.Endpoint.Behaviors.Remove((System.ServiceModel.Description.IEndpointBehavior)vs.Single());
proxy.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName,"User");
proxy.ClientCredentials.ServiceCertificate.SetDefaultCertificate(StoreLocation.LocalMachine, StoreName.TrustedPeople, X509FindType.FindBySubjectName, "Server");
proxy.Endpoint.Behaviors.Remove(typeof(ClientCredentials));
proxy.Endpoint.Behaviors.Add(new CustomCredentials(GetCertificateFromStore("User"), GetCertificateFromStore("Server")));
proxy.ClientCredentials.UserName.UserName = "User1";
proxy.ClientCredentials.UserName.Password = "PWD";

How to use IHttpCookieContainerManager in WCF 4.5

Just wanted to know how can we use IHttpCookieContainerManager in WCF 4.5. Suggest any sample code please.
In .NET 4.5 you can access the cookie container by using the .GetProperty().CookieContainer method like below if AllowCoookies = true.
Uri serverUri = new Uri("http://localhost/WcfService/Service1.svc");
CookieContainer myCookieContainer = new CookieContainer();
myCookieContainer.Add(serverUri, new Cookie("cookie1", "cookie1Value"));
ChannelFactory<IService1> factory = new ChannelFactory<IService1>(new BasicHttpBinding() { AllowCookies = true }, new EndpointAddress(serverUri));
IService1 client = factory.CreateChannel();
factory.GetProperty<IHttpCookieContainerManager>().CookieContainer = myCookieContainer;
Console.WriteLine(client.GetData(123));
myCookieContainer = factory.GetProperty<IHttpCookieContainerManager>().CookieContainer;
foreach (Cookie receivedCookie in myCookieContainer.GetCookies(serverUri))
{
Console.WriteLine("Cookie name : " + receivedCookie.Name + " Cookie value : " + receivedCookie.Value);
}
((IChannel)client).Close();
factory.Close();
//Server side
public class Service1 : IService1
{
public string GetData(int value)
{
//Read the cookies
HttpRequestMessageProperty reqProperty = (HttpRequestMessageProperty)OperationContext.Current.IncomingMessageProperties[HttpRequestMessageProperty.Name];
string cookies = reqProperty.Headers["Cookie"];
//Write a cookie
HttpResponseMessageProperty resProperty = new HttpResponseMessageProperty();
resProperty.Headers.Add("Set-Cookie", string.Format("Number={0}", value.ToString()));
OperationContext.Current.OutgoingMessageProperties.Add(HttpResponseMessageProperty.Name, resProperty);
return string.Format("You entered: {0}", value);
}
}