public object BeforeSendRequest(ref Message request, IClientChannel channel) { HttpRequestMessageProperty property = new HttpRequestMessageProperty(); property.Headers.Add("username", HttpContext.Current.User.Identity.Name); request.Properties.Add("username", property); return null; }
protected async void Button1_Click(object sender, EventArgs e) { var authServer = new AuthorizationServerDescription() { TokenEndpoint = new Uri("http://localhost:53022/OAuth/token "), ProtocolVersion = ProtocolVersion.V20 }; WebServerClient Client= new WebServerClient(authServer, "idefav", "1"); var code =await Client.GetClientAccessTokenAsync(new string[] { "http://localhost:55045/IService1/DoWork" }); string token = code.AccessToken; Service1Reference.Service1Client service1Client=new Service1Client(); var httpRequest = (HttpWebRequest)WebRequest.Create(service1Client.Endpoint.Address.Uri); ClientBase.AuthorizeRequest(httpRequest,token); var httpDetails = new HttpRequestMessageProperty(); httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers[HttpRequestHeader.Authorization]; using (var scope = new OperationContextScope(service1Client.InnerChannel)) { if (OperationContext.Current.OutgoingMessageProperties.ContainsKey(HttpRequestMessageProperty.Name)) { OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpDetails; } else { OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpDetails); } Button1.Text= service1Client.DoWork(); } }
static void Main(string[] args) { var aosUriString = ClientConfiguration.Default.UriString; var oauthHeader = OAuthHelper.GetAuthenticationHeader(); var serviceUriString = SoapUtility.SoapHelper.GetSoapServiceUriString(UserSessionServiceName, aosUriString); var endpointAddress = new System.ServiceModel.EndpointAddress(serviceUriString); var binding = SoapUtility.SoapHelper.GetBinding(); var client = new UserSessionServiceClient(binding, endpointAddress); var channel = client.InnerChannel; UserSessionInfo sessionInfo = null; using (OperationContextScope operationContextScope = new OperationContextScope(channel)) { HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty(); requestMessage.Headers[OAuthHelper.OAuthHeader] = oauthHeader; OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage; sessionInfo = ((UserSessionService)channel).GetUserSessionInfo(new GetUserSessionInfo()).result; } Console.WriteLine(); Console.WriteLine("User ID: {0}", sessionInfo.UserId); Console.WriteLine("Is Admin: {0}", sessionInfo.IsSysAdmin); Console.ReadLine(); }
protected TResult[] ExecuteAPI <TResult, TObject>(Func <APIObject, TObject> select, Func <ETClient, TObject[], ExecuteAPIResponse <TResult> > func, params APIObject[] objs) { if (objs == null) { throw new ArgumentNullException("objs"); } var client = objs.Select(x => x.AuthStub).FirstOrDefault(); if (client == null) { throw new InvalidOperationException("client"); } client.RefreshToken(); using (var scope = new OperationContextScope(client.SoapClient.InnerChannel)) { // Add oAuth token to SOAP header. XNamespace ns = "http://exacttarget.com"; var oauthElement = new XElement(ns + "oAuthToken", client.InternalAuthToken); var xmlHeader = MessageHeader.CreateHeader("oAuth", "http://exacttarget.com", oauthElement); OperationContext.Current.OutgoingMessageHeaders.Add(xmlHeader); var httpRequest = new System.ServiceModel.Channels.HttpRequestMessageProperty(); OperationContext.Current.OutgoingMessageProperties.Add(System.ServiceModel.Channels.HttpRequestMessageProperty.Name, httpRequest); httpRequest.Headers.Add(HttpRequestHeader.UserAgent, ETClient.SDKVersion); var response = func(client, objs.Select(select).ToArray()); RequestID = response.RequestID; Status = (response.OverallStatus == "OK" || response.OverallStatus == "MoreDataAvailable"); Code = (Status ? 200 : 0); MoreResults = (response.OverallStatus == "MoreDataAvailable"); Message = (response.OverallStatusMessage ?? string.Empty); return(response.Results); } }
public object BeforeSendRequest(ref Message request, IClientChannel channel) { var tokenInjector = ServiceLocator.Current.GetInstance<ISecurityTokenInjector>(); if (tokenInjector != null) { object httpRequestMessageObject; if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject)) { var httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty; if (httpRequestMessage != null) tokenInjector.InjectToken(httpRequestMessage.Headers); } else { var httpRequestMessage = new HttpRequestMessageProperty(); tokenInjector.InjectToken(httpRequestMessage.Headers); request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage); } } return null; }
public static void Main() { // Typically this request would be constructed by a web browser or non-WCF application instead of using WCF Console.WriteLine("Starting client with ByteStreamHttpBinding"); using (ChannelFactory<IHttpHandler> cf = new ChannelFactory<IHttpHandler>("byteStreamHttpBinding")) { IHttpHandler channel = cf.CreateChannel(); Console.WriteLine("Client channel created"); Message byteStream = Message.CreateMessage(MessageVersion.None, "*", new ByteStreamBodyWriter(TestFileName)); HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty(); httpRequestProperty.Headers.Add("Content-Type", "application/octet-stream"); byteStream.Properties.Add(HttpRequestMessageProperty.Name, httpRequestProperty); Console.WriteLine("Client calling service"); Message reply = channel.ProcessRequest(byteStream); //Get bytes from the reply XmlDictionaryReader reader = reply.GetReaderAtBodyContents(); reader.MoveToElement(); String name = reader.Name; Console.WriteLine("First element in the byteStream message is : <" + name + ">"); byte[] array = reader.ReadElementContentAsBase64(); String replyMessage = System.Text.Encoding.UTF8.GetString(array); Console.WriteLine("Client received a reply from service of length :" + replyMessage.Length); } Console.WriteLine("Done"); Console.WriteLine("Press <ENTER> to exit client"); Console.ReadLine(); }
internal void Apply (HttpRequestMessageProperty hp) { foreach (var key in Headers.AllKeys) hp.Headers [key] = Headers [key]; if (Accept != null) hp.Headers ["Accept"] = Accept; if (ContentLength > 0) hp.Headers ["Content-Length"] = ContentLength.ToString (NumberFormatInfo.InvariantInfo); if (ContentType != null) hp.Headers ["Content-Type"] = ContentType; if (IfMatch != null) hp.Headers ["If-Match"] = IfMatch; if (IfModifiedSince != null) hp.Headers ["If-Modified-Since"] = IfModifiedSince; if (IfNoneMatch != null) hp.Headers ["If-None-Match"] = IfNoneMatch; if (IfUnmodifiedSince != null) hp.Headers ["If-Unmodified-Since"] = IfUnmodifiedSince; if (Method != null) hp.Method = Method; if (SuppressEntityBody) hp.SuppressEntityBody = true; if (UserAgent != null) hp.Headers ["User-Agent"] = UserAgent; }
public static void Method_Property_Sets() { const string newMethod = "PUT"; HttpRequestMessageProperty requestMsgProperty = new HttpRequestMessageProperty(); requestMsgProperty.Method = newMethod; Assert.Equal<string>(newMethod, requestMsgProperty.Method); }
public static void QueryString_Property_Sets() { const string newQueryString = "name=Mary"; HttpRequestMessageProperty requestMsgProperty = new HttpRequestMessageProperty(); requestMsgProperty.QueryString = newQueryString; Assert.Equal<string>(newQueryString, requestMsgProperty.QueryString); }
internal IncomingWebRequestContext (OperationContext context) { if (context.IncomingMessageProperties != null) hp = (HttpRequestMessageProperty) context.IncomingMessageProperties [HttpRequestMessageProperty.Name]; else hp = new HttpRequestMessageProperty (); }
public object BeforeSendRequest(ref Message request, IClientChannel channel) { object httpRequestMessageObject; if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject)) { HttpRequestMessageProperty httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty; if (httpRequestMessage != null) { httpRequestMessage.Headers[SERVICE_KEY_HTTP_HEADER] = (ServiceKey ?? string.Empty); } else { httpRequestMessage = new HttpRequestMessageProperty(); httpRequestMessage.Headers.Add(SERVICE_KEY_HTTP_HEADER, (ServiceKey ?? string.Empty)); request.Properties[HttpRequestMessageProperty.Name] = httpRequestMessage; } } else { HttpRequestMessageProperty httpRequestMessage = new HttpRequestMessageProperty(); httpRequestMessage.Headers.Add(SERVICE_KEY_HTTP_HEADER, (ServiceKey ?? string.Empty)); request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage); } return null; }
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message Request, System.ServiceModel.IClientChannel Channel) { HttpRequestMessageProperty httpRequestMessage; object httpRequestMessageObject; if (Request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject)) { httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty; if (String.IsNullOrEmpty(httpRequestMessage.Headers["WPMediaToken"])) { if (WMB.WPMediaApplicationState.Instance.Properties.ContainsKey("WPMediaToken")) httpRequestMessage.Headers["WPMediaToken"] = WMB.WPMediaApplicationState.Instance.Properties["WPMediaToken"].ToString(); } } else { if (WMB.WPMediaApplicationState.Instance.Properties.ContainsKey("WPMediaToken")) { httpRequestMessage = new HttpRequestMessageProperty(); httpRequestMessage.Headers.Add("WPMediaToken", WMB.WPMediaApplicationState.Instance.Properties["WPMediaToken"].ToString()); Request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage); } } return null; }
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel) { HttpRequestMessageProperty httpRequestMessage; object httpRequestMessageObject; if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject)) { httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty; if (string.IsNullOrEmpty(httpRequestMessage.Headers[HttpRequestHeader.Authorization])) { var authResult = Expenses.WPF.AADSignIn.AADAuthResult; if (authResult != null) { httpRequestMessage.Headers[HttpRequestHeader.Authorization] = Expenses.WPF.AADSignIn.AADAuthResult.CreateAuthorizationHeader(); } } } else { var authResult = Expenses.WPF.AADSignIn.AADAuthResult; if (authResult != null) { httpRequestMessage = new HttpRequestMessageProperty(); httpRequestMessage.Headers.Add(HttpRequestHeader.Authorization, Expenses.WPF.AADSignIn.AADAuthResult.CreateAuthorizationHeader()); request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage); } } return null; }
/// <summary> /// Enables inspection or modification of a message before a request message is sent to a service. /// </summary> /// <returns> /// The object that is returned as the <paramref name="correlationState "/>argument of the <see cref="M:System.ServiceModel.Dispatcher.IClientMessageInspector.AfterReceiveReply(System.ServiceModel.Channels.Message@,System.Object)"/> method. This is null if no correlation state is used.The best practice is to make this a <see cref="T:System.Guid"/> to ensure that no two <paramref name="correlationState"/> objects are the same. /// </returns> /// <param name="request">The message to be sent to the service.</param><param name="channel">The WCF client object channel.</param> public object BeforeSendRequest(ref Message request, IClientChannel channel) { HttpRequestMessageProperty httpRequest; if (request.Properties.ContainsKey(HttpRequestMessageProperty.Name)) { httpRequest = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty; } else { httpRequest = new HttpRequestMessageProperty(); request.Properties.Add(HttpRequestMessageProperty.Name, httpRequest); } if (httpRequest != null) { httpRequest.Headers.Add("Authorization", string.Format("{0}", AdalTokenManager.GetToken(serviceName).CreateAuthorizationHeader())); var supportCode = ""; RuntimeFactory.Current.GetStateStorageContainer().TryGetItem("supportCode", out supportCode); var meta = new RequestHeader { Environment = Utilities.GetEnvironment(), ConfigSet = Utilities.GetConfigSetName(), ServiceName = RuntimeFactory.Current.ServiceName, MessageId = Guid.NewGuid().ToString(), ServerIdentity = Environment.MachineName, RuntimeInstance = RuntimeFactory.Current.InstanceId.ToString(), SupportCode = supportCode }; httpRequest.Headers.Add("X-Stardust-Meta", Convert.ToBase64String(JsonConvert.SerializeObject(meta).GetByteArray())); } return RuntimeFactory.Current; }
private static Message CreateNormalRequestMessage() { var requestProperty = new HttpRequestMessageProperty(); Message requestMessage = Message.CreateMessage(MessageVersion.None, null); requestMessage.Properties.Add(HttpRequestMessageProperty.Name, requestProperty); return requestMessage; }
static void Main(string[] args) { var binding = new WSHttpBinding(SecurityMode.Transport); binding.Name = "binding"; binding.MaxReceivedMessageSize = 500000; binding.AllowCookies = true; var client = new SyncReplyClient(binding, new EndpointAddress("https://platform.gaelenlighten.com/api/soap12")); using (new OperationContextScope(client.InnerChannel)) { var requestMessage = new HttpRequestMessageProperty(); requestMessage.Headers["Tenant"] = "tenant.gaelenlighten.com"; // Add your tenant var token = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes("username:password")); // Add your username and password here requestMessage.Headers["Authorization"] = token; OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage; var response = client.GetReports(new GetReports { //// Specify filters ReportStatus = ReportStatus.New, Take = 100, Skip = 0 }); var reportList = response.Reports; foreach (var report in reportList) { ////Example of iterating through the report list } response.PrintDump(); Console.ReadLine(); } }
public static void DigestAuthentication_Echo_RoundTrips_String_No_Domain() { ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; string testString = "Hello"; BasicHttpBinding binding; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Digest; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Http_DigestAuth_NoDomain_Address)); string DigestUsernameHeaderName = "DigestUsername"; string DigestPasswordHeaderName = "DigestPassword"; string DigestRealmHeaderName = "DigestRealm"; string username = Guid.NewGuid().ToString("n").Substring(0, 8); string password = Guid.NewGuid().ToString("n").Substring(0, 16); string realm = Guid.NewGuid().ToString("n").Substring(0, 5); factory.Credentials.HttpDigest.ClientCredential = new NetworkCredential(username, password, realm); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = null; using (var scope = new OperationContextScope((IContextChannel)serviceProxy)) { HttpRequestMessageProperty requestMessageProperty; if (!OperationContext.Current.OutgoingMessageProperties.ContainsKey(HttpRequestMessageProperty.Name)) { requestMessageProperty = new HttpRequestMessageProperty(); OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessageProperty; } else { requestMessageProperty = (HttpRequestMessageProperty)OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name]; } requestMessageProperty.Headers[DigestUsernameHeaderName] = username; requestMessageProperty.Headers[DigestPasswordHeaderName] = password; requestMessageProperty.Headers[DigestRealmHeaderName] = realm; result = serviceProxy.Echo(testString); } // *** VALIDATE *** \\ Assert.True(result == testString, string.Format("Error: expected response from service: '{0}' Actual was: '{1}'", testString, result)); // *** CLEANUP *** \\ factory.Close(); ((ICommunicationObject)serviceProxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
static string GetOperationName(Uri address, IDispatchOperationSelector operationSelector) { Message message = Message.CreateMessage(MessageVersion.None, ""); message.Headers.To = address; HttpRequestMessageProperty messageProperty = new HttpRequestMessageProperty(); messageProperty.Method = "GET"; message.Properties.Add(HttpRequestMessageProperty.Name, messageProperty); return operationSelector.SelectOperation(ref message); }
private static Message CreateRequestMessage(string authorizationheaderToAdd) { const string BasicAuthenticationHeaderName = "Authorization"; Message requestMessage = Message.CreateMessage(MessageVersion.None, null); var requestProperty = new HttpRequestMessageProperty(); requestProperty.Headers.Add(BasicAuthenticationHeaderName, authorizationheaderToAdd); requestMessage.Properties.Add(HttpRequestMessageProperty.Name, requestProperty); return requestMessage; }
public static void Default_Ctor_Initializes_Properties() { HttpRequestMessageProperty requestMsgProperty = new HttpRequestMessageProperty(); Assert.NotNull(requestMsgProperty.Headers); Assert.Equal<string>("POST", requestMsgProperty.Method); Assert.Equal<string>(string.Empty, requestMsgProperty.QueryString); Assert.False(requestMsgProperty.SuppressEntityBody); }
public object BeforeSendRequest(ref Message request, IClientChannel channel) { MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue); request = buffer.CreateMessage(); Message msg = buffer.CreateMessage(); ASCIIEncoding encoder = new ASCIIEncoding(); var sb = new StringBuilder(); var xmlWriter = XmlWriter.Create(sb, new XmlWriterSettings { OmitXmlDeclaration = true }); var writer = XmlDictionaryWriter.CreateDictionaryWriter(xmlWriter); msg.WriteStartEnvelope(writer); msg.WriteStartBody(writer); msg.WriteBodyContents(writer); xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); writer.Flush(); string body = sb.ToString().Replace(" />", "/>"); byte[] xmlByte = encoder.GetBytes(body); SHA1CryptoServiceProvider sha1Crypto = new SHA1CryptoServiceProvider(); string hash = BitConverter.ToString(sha1Crypto.ComputeHash(xmlByte)).Replace("-", ""); string hashedContent = hash.ToLower(); //assign values to hashing and header variables string time = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"); string hashData = "POST\ntext/xml; charset=utf-8\n" + hashedContent + "\n" + time + "\n/transaction/v12"; //hmac sha1 hash with key + hash_data HMAC hmacSha1 = new HMACSHA1(Encoding.UTF8.GetBytes(_hmac)); //key byte[] hmacData = hmacSha1.ComputeHash(Encoding.UTF8.GetBytes(hashData)); //data //base64 encode on hmac_data string base64Hash = Convert.ToBase64String(hmacData); HttpRequestMessageProperty httpRequestMessage; object httpRequestMessageObject; if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject)) { httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty; httpRequestMessage.Headers["X-GGe4-Content-SHA1"] = hashedContent; httpRequestMessage.Headers["X-GGe4-Date"] = time; httpRequestMessage.Headers["Authorization"] = "GGE4_API " + _keyId + ":" + base64Hash; } else { httpRequestMessage = new HttpRequestMessageProperty(); httpRequestMessage.Headers["X-GGe4-Content-SHA1"] = hashedContent; httpRequestMessage.Headers["X-GGe4-Date"] = time; httpRequestMessage.Headers["Authorization"] = "GGE4_API " + _keyId + ":" + base64Hash; request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage); } return null; }
/// <summary> /// Gets a response from the IdP based on a message. /// </summary> /// <param name="endpoint">The IdP endpoint.</param> /// <param name="message">The message.</param> /// <param name="auth">Basic authentication settings.</param> /// <returns>The Stream.</returns> public Stream GetResponse(string endpoint, string message, HttpAuth auth, string relayState) { if (auth != null && auth.ClientCertificate != null && auth.Credentials != null) { throw new Saml20Exception(string.Format("Artifact resolution cannot specify both client certificate and basic credentials for endpoint {0}", endpoint)); } var binding = CreateSslBinding(); if (auth != null && auth.ClientCertificate != null) { // Client certificate auth binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate; } var request = Message.CreateMessage(binding.MessageVersion, HttpArtifactBindingConstants.SoapAction, new SimpleBodyWriter(message)); request.Headers.To = new Uri(endpoint); var property = new HttpRequestMessageProperty { Method = "POST" }; property.Headers.Add(HttpRequestHeader.ContentType, "text/xml; charset=utf-8"); if (auth != null && auth.Credentials != null) { // Basic http auth over ssl var basicAuthzHeader = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(auth.Credentials.Username + ":" + auth.Credentials.Password)); property.Headers.Add(HttpRequestHeader.Authorization, basicAuthzHeader); } request.Properties.Add(HttpRequestMessageProperty.Name, property); if (relayState != null) { request.Properties.Add("relayState", relayState); } var epa = new EndpointAddress(endpoint); var factory = new ChannelFactory<IRequestChannel>(binding, epa); if (auth != null && auth.ClientCertificate != null) { // Client certificate factory.Credentials.ClientCertificate.Certificate = auth.ClientCertificate; } var reqChannel = factory.CreateChannel(); reqChannel.Open(); var response = reqChannel.Request(request); Console.WriteLine(response); reqChannel.Close(); var doc = new XmlDocument { PreserveWhitespace = true }; doc.Load(response.GetReaderAtBodyContents()); var outerXml = doc.DocumentElement.OuterXml; var memStream = new MemoryStream(Encoding.UTF8.GetBytes(outerXml)); return memStream; }
private static Message CreateAuthorizedRequestMessage() { const string BasicAuthenticationHeaderName = "Authorization"; Message requestMessage = Message.CreateMessage(MessageVersion.None, null); var requestProperty = new HttpRequestMessageProperty(); const string BasicAuthenticationHeaderValue = "Basic SGVsbG8gQmFzZTY0"; requestProperty.Headers.Add(BasicAuthenticationHeaderName, BasicAuthenticationHeaderValue); requestMessage.Properties.Add(HttpRequestMessageProperty.Name, requestProperty); return requestMessage; }
public static Message CreateMessage() { const string AuthenticationHeaderName = "Authorization"; Message requestMessage = Message.CreateMessage(MessageVersion.None, null); var requestProperty = new HttpRequestMessageProperty(); requestProperty.Headers.Add(AuthenticationHeaderName, AuthenticationString); requestProperty.Method = "GET"; requestMessage.Properties.Add(HttpRequestMessageProperty.Name, requestProperty); return requestMessage; }
IMessageProperty IMessageProperty.CreateCopy () { var copy = new HttpRequestMessageProperty (); // FIXME: Clone headers? copy.headers = headers; copy.method = method; copy.query_string = query_string; copy.suppress_entity = suppress_entity; return copy; }
private static async Task<IPrincipal> VerifyOAuth2Async(HttpRequestMessageProperty httpDetails, Uri requestUri, params string[] requiredScopes) { // for this sample where the auth server and resource server are the same site, // we use the same public/private key. using (var signing = Global.CreateAuthorizationServerSigningServiceProvider()) { using (var encrypting = Global.CreateResourceServerEncryptionServiceProvider()) { var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer(signing, encrypting)); return await resourceServer.GetPrincipalAsync(httpDetails, requestUri, requiredScopes: requiredScopes); } } }
private static BasicToken ExtractToken(HttpRequestMessageProperty request) { var authHeader = request.Headers[HttpRequestHeader.Authorization]; if (authHeader != null && authHeader.StartsWith("Basic")) { return CreateBasicToken(authHeader); } return null; }
public static void BasicAuthentication_RoundTrips_Echo() { StringBuilder errorBuilder = new StringBuilder(); try { BasicHttpBinding basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; ChannelFactory<IWcfCustomUserNameService> factory = new ChannelFactory<IWcfCustomUserNameService>(basicHttpBinding, new EndpointAddress(Endpoints.Https_BasicAuth_Address)); string username = Guid.NewGuid().ToString("n").Substring(0, 8); string password = Guid.NewGuid().ToString("n").Substring(0, 16); factory.Credentials.UserName.UserName = username; factory.Credentials.UserName.Password = password; IWcfCustomUserNameService serviceProxy = factory.CreateChannel(); string testString = "I am a test"; string result; using (var scope = new OperationContextScope((IContextChannel)serviceProxy)) { HttpRequestMessageProperty requestMessageProperty; if (!OperationContext.Current.OutgoingMessageProperties.ContainsKey(HttpRequestMessageProperty.Name)) { requestMessageProperty = new HttpRequestMessageProperty(); OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessageProperty; } else { requestMessageProperty = (HttpRequestMessageProperty)OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name]; } requestMessageProperty.Headers[BasicUsernameHeaderName] = username; requestMessageProperty.Headers[BasicPasswordHeaderName] = password; result = serviceProxy.Echo(testString); } bool success = string.Equals(result, testString); if (!success) { errorBuilder.AppendLine(string.Format("Basic echo test.\nTest variation:...\n{0}\nUsing address: '{1}'", "BasicAuthentication_RoundTrips_Echo", Endpoints.Https_BasicAuth_Address)); errorBuilder.AppendLine(String.Format(" Error: expected response from service: '{0}' Actual was: '{1}'", testString, result)); } } catch (Exception ex) { errorBuilder.AppendLine(string.Format("Basic echo test.\nTest variation:...\n{0}\nUsing address: '{1}'", "BasicAuthentication_RoundTrips_Echo", Endpoints.Https_BasicAuth_Address)); errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString())); } Assert.True(errorBuilder.Length == 0, String.Format("Test Case: BasicAuthentication FAILED with the following errors: {0}", errorBuilder)); }
/// <summary> /// Scope is being passed /// </summary> /// <param name="scope"></param> public static void AddCustomHeaderUserInformation(OperationContextScope scope, Dictionary<string, string> headers) { //Add the basic userId HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty(); foreach (var headerKey in headers.Keys) { requestProperty.Headers.Add(headerKey, headers[headerKey]); } OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestProperty; }
/// <summary> /// Initializes a new instance of the <see cref="HttpRequestInfo"/> class. /// </summary> /// <param name="request">The request.</param> /// <param name="requestUri">The request URI.</param> internal HttpRequestInfo(HttpRequestMessageProperty request, Uri requestUri) { Requires.NotNull(request, "request"); Requires.NotNull(requestUri, "requestUri"); this.httpMethod = request.Method; this.headers = request.Headers; this.requestUri = requestUri; this.form = new NameValueCollection(); this.serverVariables = new NameValueCollection(); Reporting.RecordRequestStatistics(this); }
public DeleteReturn(APIObject theObject) { string OverallStatus = string.Empty, RequestID = string.Empty; Result[] requestResults = new Result[0]; theObject.AuthStub.refreshToken(); using (var scope = new OperationContextScope(theObject.AuthStub.soapclient.InnerChannel)) { //Add oAuth token to SOAP header. XNamespace ns = "http://exacttarget.com"; var oauthElement = new XElement(ns + "oAuthToken", theObject.AuthStub.internalAuthToken); var xmlHeader = MessageHeader.CreateHeader("oAuth", "http://exacttarget.com", oauthElement); OperationContext.Current.OutgoingMessageHeaders.Add(xmlHeader); var httpRequest = new System.ServiceModel.Channels.HttpRequestMessageProperty(); OperationContext.Current.OutgoingMessageProperties.Add(System.ServiceModel.Channels.HttpRequestMessageProperty.Name, httpRequest); httpRequest.Headers.Add(HttpRequestHeader.UserAgent, theObject.AuthStub.SDKVersion); theObject = this.TranslateObject(theObject); requestResults = theObject.AuthStub.soapclient.Delete(new DeleteOptions(), new APIObject[] { theObject }, out RequestID, out OverallStatus); this.Status = true; this.Code = 200; this.MoreResults = false; this.Message = ""; if (OverallStatus != "OK") { this.Status = false; } if (requestResults.GetType() == typeof(DeleteResult[]) && requestResults.Length > 0) { List<ResultDetail> results = new List<ResultDetail>(); foreach (DeleteResult cr in requestResults) { ResultDetail detail = new ResultDetail(); if (cr.StatusCode != null) detail.StatusCode = cr.StatusCode; if (cr.StatusMessage != null) detail.StatusMessage = cr.StatusMessage; if (cr.Object != null) detail.Object = this.TranslateObject(cr.Object); detail.OrdinalID = cr.OrdinalID; detail.ErrorCode = cr.ErrorCode; results.Add(detail); } this.Results = results.ToArray(); } } }
void OnReceiveHttpCookies(Message message) { object property; if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property)) { HttpRequestMessageProperty httpRequest = property as HttpRequestMessageProperty; if (httpRequest != null) { string cookieHeader = httpRequest.Headers[HttpRequestHeader.Cookie]; ContextMessageProperty messageContext; if (!string.IsNullOrEmpty(cookieHeader) && HttpCookieToolbox.TryCreateFromHttpCookieHeader(cookieHeader, out messageContext)) { messageContext.AddOrReplaceInMessage(message); } } } }
private void OnReceiveHttpCookies(Message message) { object obj2; if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out obj2)) { HttpRequestMessageProperty property = obj2 as HttpRequestMessageProperty; if (property != null) { ContextMessageProperty property2; string str = property.Headers[HttpRequestHeader.Cookie]; if (!string.IsNullOrEmpty(str) && ContextProtocol.HttpCookieToolbox.TryCreateFromHttpCookieHeader(str, out property2)) { property2.AddOrReplaceInMessage(message); } } } }
internal static HttpRequestMessage GetHttpRequestMessageFromMessage(Message message) { HttpRequestMessage httpRequestMessage = null; HttpRequestMessageProperty property = message.Properties.GetValue <HttpRequestMessageProperty>(HttpRequestMessageProperty.Name); if (property != null) { httpRequestMessage = property.HttpRequestMessage; if (httpRequestMessage != null) { httpRequestMessage.CopyPropertiesFromMessage(message); message.EnsureReadMessageState(); } } return(httpRequestMessage); }
void OnSendHttpCookies(Message message, ContextMessageProperty context) { string cookieHeader = null; if (this.contextManagementEnabled || context == null) { Fx.Assert(context == null, "Context should be null"); lock (this.cookieContainer) { cookieHeader = this.cookieContainer.GetCookieHeader(this.Uri); } } else { if (context != null) //User provided context is not null. { string contextCookieHeader = this.GetCookieHeaderFromContext(context); lock (this.cookieContainer) { this.cookieContainer.SetCookies(this.Uri, contextCookieHeader); cookieHeader = this.cookieContainer.GetCookieHeader(this.Uri); this.cookieContainer.SetCookies(this.Uri, HttpCookieToolbox.RemoveContextHttpCookieHeader); } } } if (!string.IsNullOrEmpty(cookieHeader)) { object tmpProperty; HttpRequestMessageProperty property = null; if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out tmpProperty)) { property = tmpProperty as HttpRequestMessageProperty; } if (property == null) { property = new HttpRequestMessageProperty(); message.Properties.Add(HttpRequestMessageProperty.Name, property); } property.Headers.Add(HttpRequestHeader.Cookie, cookieHeader); } }
public HttpRequestMessageProperty CreateTraditionalRequestMessageProperty() { HttpRequestMessageProperty copiedProperty = new HttpRequestMessageProperty(); foreach (var headerKey in this.Headers.AllKeys) { copiedProperty.Headers[headerKey] = this.Headers[headerKey]; } if (this.Method != TraditionalHttpRequestMessageProperty.DefaultMethod) { copiedProperty.Method = this.Method; } copiedProperty.QueryString = this.QueryString; copiedProperty.SuppressEntityBody = this.SuppressEntityBody; return(copiedProperty); }
public static async Task <string> PobierzDane(string nip) { // WSHttpBinding myBinding = new WSHttpBinding(); // myBinding.Security.Mode = SecurityMode.Transport; // myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None; // myBinding.TextEncoding = Encoding.Unicode; // WSMessageEncoding.Mtom; // BasicHttpBinding b = new BasicHttpBinding(); // b.Security.Mode = BasicHttpSecurityMode.Transport; // b.Security.Transport.ClientCredentialType = HttpClientCredentialType.None; // b.TextEncoding = Encoding.Unicode; string result; var encoding = new MtomMessageEncoderBindingElement(new TextMessageEncodingBindingElement()); var transport = new HttpsTransportBindingElement(); var customBinding = new CustomBinding(encoding, transport); // bir.Endpoint.Binding = customBinding; EndpointAddress ea = new EndpointAddress("https://wyszukiwarkaregontest.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc"); UslugaBIRzewnPublClient cc = new UslugaBIRzewnPublClient(customBinding, ea); await cc.OpenAsync(); ZalogujResponse r = await cc.ZalogujAsync("abcde12345abcde12345"); using (OperationContextScope scope = new OperationContextScope(cc.InnerChannel)) { System.ServiceModel.Channels.HttpRequestMessageProperty requestMessage = new System.ServiceModel.Channels.HttpRequestMessageProperty(); requestMessage.Headers.Add("sid", r.ZalogujResult); OperationContext.Current.OutgoingMessageProperties[System.ServiceModel.Channels.HttpRequestMessageProperty.Name] = requestMessage; // DANE SZUKAJ 1 ParametryWyszukiwania objParametryGR1 = new ParametryWyszukiwania(); objParametryGR1.Nip = nip; DaneSzukajPodmiotyResponse dane = await cc.DaneSzukajPodmiotyAsync(objParametryGR1); // File.WriteAllText(Directory.GetCurrentDirectory() + "\\wynik.xml", dane.DaneSzukajPodmiotyResult); result = dane.DaneSzukajPodmiotyResult; WylogujResponse w = await cc.WylogujAsync(r.ZalogujResult); cc.Close(); return(result); } }
protected override void AddProperties(Message message) { HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty(this.listenerHttpContext); requestProperty.Method = this.listenerHttpContext.listenerContext.Request.HttpMethod; // Uri.Query always includes the '?' if (this.listenerHttpContext.listenerContext.Request.Url.Query.Length > 1) { requestProperty.QueryString = this.listenerHttpContext.listenerContext.Request.Url.Query.Substring(1); } message.Properties.Add(HttpRequestMessageProperty.Name, requestProperty); message.Properties.Via = this.listenerHttpContext.listenerContext.Request.Url; RemoteEndpointMessageProperty remoteEndpointProperty = new RemoteEndpointMessageProperty(this.listenerHttpContext.listenerContext.Request.RemoteEndPoint); message.Properties.Add(RemoteEndpointMessageProperty.Name, remoteEndpointProperty); }
private void ApplyManualAddressing(ref EndpointAddress to, ref Uri via, Message message) { if (ManualAddressing) { Uri toHeader = message.Headers.To; if (toHeader == null) { throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.ManualAddressingRequiresAddressedMessages), message); } to = new EndpointAddress(toHeader); if (MessageVersion.Addressing == AddressingVersion.None) { via = toHeader; } } // now apply query string property object property; if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property)) { HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)property; if (!string.IsNullOrEmpty(requestProperty.QueryString)) { UriBuilder uriBuilder = new UriBuilder(via); if (requestProperty.QueryString.StartsWith("?", StringComparison.Ordinal)) { uriBuilder.Query = requestProperty.QueryString.Substring(1); } else { uriBuilder.Query = requestProperty.QueryString; } via = uriBuilder.Uri; } } }
private void OnSendHttpCookies(Message message, ContextMessageProperty context) { string cookieHeader = null; if (this.contextManagementEnabled || (context == null)) { lock (this.cookieContainer) { cookieHeader = this.cookieContainer.GetCookieHeader(this.Uri); goto Label_00A2; } } if (context != null) { string cookieHeaderFromContext = this.GetCookieHeaderFromContext(context); lock (this.cookieContainer) { this.cookieContainer.SetCookies(this.Uri, cookieHeaderFromContext); cookieHeader = this.cookieContainer.GetCookieHeader(this.Uri); this.cookieContainer.SetCookies(this.Uri, "WscContext;Max-Age=0"); } } Label_00A2: if (!string.IsNullOrEmpty(cookieHeader)) { object obj2; HttpRequestMessageProperty property = null; if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out obj2)) { property = obj2 as HttpRequestMessageProperty; } if (property == null) { property = new HttpRequestMessageProperty(); message.Properties.Add(HttpRequestMessageProperty.Name, property); } property.Headers.Add(HttpRequestHeader.Cookie, cookieHeader); } }
private void PrepareContentHeaders() { bool wasContentTypeSet = false; string action = _message.Headers.Action; if (action != null) { action = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", UrlUtility.UrlPathEncode(action)); } object property; if (_message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property)) { HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)property; WebHeaderCollection requestHeaders = requestProperty.Headers; var headerKeys = requestHeaders.AllKeys; for (int i = 0; i < headerKeys.Length; i++) { string name = headerKeys[i]; string value = requestHeaders[name]; if (string.Compare(name, "SOAPAction", StringComparison.OrdinalIgnoreCase) == 0) { if (action == null) { action = value; } else { if (!String.IsNullOrEmpty(value) && string.Compare(value, action, StringComparison.Ordinal) != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ProtocolException(SR.Format(SR.HttpSoapActionMismatch, action, value))); } } } else if (string.Compare(name, "content-type", StringComparison.OrdinalIgnoreCase) == 0) { if (SetContentType(value)) { wasContentTypeSet = true; } } } } if (action != null) { if (_message.Version.Envelope == EnvelopeVersion.Soap12) { if (_message.Version.Addressing == AddressingVersion.None) { bool shouldSetContentType = true; if (wasContentTypeSet) { var actionParams = (from p in Headers.ContentType.Parameters where p.Name == "action" select p).ToArray(); Contract.Assert(actionParams.Length <= 1, "action MUST only appear as a content type parameter at most 1 time"); if (actionParams.Length > 0) { try { string value = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", actionParams[0].Value); if (string.Compare(value, action, StringComparison.Ordinal) != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ProtocolException(SR.Format(SR.HttpSoapActionMismatchContentType, action, value))); } shouldSetContentType = false; } catch (FormatException formatException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ProtocolException(SR.Format(SR.HttpContentTypeFormatException, formatException.Message, Headers.ContentType.ToString()), formatException)); } } } if (shouldSetContentType) { Headers.ContentType.Parameters.Add(new NameValueHeaderValue("action", action)); } } } } }
void BeginProcessRequest(HttpChannelRequestAsyncResult result) { Message message = result.Message; TimeSpan timeout = result.Timeout; // FIXME: is distination really like this? Uri destination = message.Headers.To; if (destination == null) { if (source.Transport.ManualAddressing) { throw new InvalidOperationException("When manual addressing is enabled on the transport, every request messages must be set its destination address."); } else { destination = Via ?? RemoteAddress.Uri; } } var web_request = HttpWebRequest.Create(destination); web_requests.Add(web_request); result.WebRequest = web_request; web_request.Method = "POST"; web_request.ContentType = Encoder.ContentType; #if NET_2_1 HttpWebRequest hwr = (web_request as HttpWebRequest); #if MOONLIGHT if (hwr.SupportsCookieContainer) { #endif var cmgr = source.GetProperty <IHttpCookieContainerManager> (); if (cmgr != null) { hwr.CookieContainer = cmgr.CookieContainer; } #if MOONLIGHT } #endif #endif #if !MOONLIGHT // until we support NetworkCredential like SL4 will do. // client authentication (while SL3 has NetworkCredential class, it is not implemented yet. So, it is non-SL only.) var httpbe = (HttpTransportBindingElement)source.Transport; string authType = null; switch (httpbe.AuthenticationScheme) { // AuthenticationSchemes.Anonymous is the default, ignored. case AuthenticationSchemes.Basic: authType = "Basic"; break; case AuthenticationSchemes.Digest: authType = "Digest"; break; case AuthenticationSchemes.Ntlm: authType = "Ntlm"; break; case AuthenticationSchemes.Negotiate: authType = "Negotiate"; break; } if (authType != null) { var cred = source.ClientCredentials; string user = cred != null ? cred.UserName.UserName : null; string pwd = cred != null ? cred.UserName.Password : null; if (String.IsNullOrEmpty(user)) { throw new InvalidOperationException(String.Format("Use ClientCredentials to specify a user name for required HTTP {0} authentication.", authType)); } var nc = new NetworkCredential(user, pwd); web_request.Credentials = nc; // FIXME: it is said required in SL4, but it blocks full WCF. //web_request.UseDefaultCredentials = false; } #endif #if !NET_2_1 // FIXME: implement this to not depend on Timeout property web_request.Timeout = (int)timeout.TotalMilliseconds; #endif // There is no SOAP Action/To header when AddressingVersion is None. if (message.Version.Envelope.Equals(EnvelopeVersion.Soap11) || message.Version.Addressing.Equals(AddressingVersion.None)) { if (message.Headers.Action != null) { web_request.Headers ["SOAPAction"] = String.Concat("\"", message.Headers.Action, "\""); message.Headers.RemoveAll("Action", message.Version.Addressing.Namespace); } } // apply HttpRequestMessageProperty if exists. bool suppressEntityBody = false; string pname = HttpRequestMessageProperty.Name; if (message.Properties.ContainsKey(pname)) { HttpRequestMessageProperty hp = (HttpRequestMessageProperty)message.Properties [pname]; #if !NET_2_1 // FIXME: how can this be done? foreach (var key in hp.Headers.AllKeys) { if (!WebHeaderCollection.IsRestricted(key)) { web_request.Headers [key] = hp.Headers [key]; } } #endif web_request.Method = hp.Method; // FIXME: do we have to handle hp.QueryString ? if (hp.SuppressEntityBody) { suppressEntityBody = true; } } #if !NET_2_1 if (source.ClientCredentials.ClientCertificate.Certificate != null) { ((HttpWebRequest)web_request).ClientCertificates.Add(source.ClientCredentials.ClientCertificate.Certificate); } #endif if (!suppressEntityBody && String.Compare(web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) { MemoryStream buffer = new MemoryStream(); Encoder.WriteMessage(message, buffer); if (buffer.Length > int.MaxValue) { throw new InvalidOperationException("The argument message is too large."); } #if !NET_2_1 web_request.ContentLength = (int)buffer.Length; #endif web_request.BeginGetRequestStream(delegate(IAsyncResult r) { try { result.CompletedSynchronously &= r.CompletedSynchronously; using (Stream s = web_request.EndGetRequestStream(r)) s.Write(buffer.GetBuffer(), 0, (int)buffer.Length); web_request.BeginGetResponse(GotResponse, result); } catch (WebException ex) { switch (ex.Status) { #if !NET_2_1 case WebExceptionStatus.NameResolutionFailure: #endif case WebExceptionStatus.ConnectFailure: result.Complete(new EndpointNotFoundException(new EndpointNotFoundException().Message, ex)); break; default: result.Complete(ex); break; } } catch (Exception ex) { result.Complete(ex); } }, null); } else { web_request.BeginGetResponse(GotResponse, result); } }
public ETClient(NameValueCollection parameters = null, RefreshState refreshState = null) { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); var config = builder.Build(); // Get configuration file and set variables configSection = (FuelSDKConfigurationSection)config.GetSection("FuelSDK").Get <FuelSDKConfigurationSection>(); if (parameters != null) { if (parameters.AllKeys.Contains("appSignature")) { configSection.AppSignature = parameters["appSignature"]; } if (parameters.AllKeys.Contains("clientId")) { configSection.ClientId = parameters["clientId"]; } if (parameters.AllKeys.Contains("clientSecret")) { configSection.ClientSecret = parameters["clientSecret"]; } if (parameters.AllKeys.Contains("soapEndPoint")) { configSection.SoapEndPoint = parameters["soapEndPoint"]; //https://webservice.s4.exacttarget.com/Service.asmx } if (parameters.AllKeys.Contains("authEndPoint")) { configSection.AuthenticationEndPoint = parameters["authEndPoint"]; //https://auth-qa.exacttargetapis.com/v1/requestToken?legacy=1 } } if (string.IsNullOrEmpty(configSection.ClientId) || string.IsNullOrEmpty(configSection.ClientSecret)) { throw new Exception("clientId or clientSecret is null: Must be provided in config file or passed when instantiating ETClient"); } // If JWT URL Parameter Used var organizationFind = false; if (refreshState != null) { RefreshKey = refreshState.RefreshKey; EnterpriseId = refreshState.EnterpriseId; OrganizationId = refreshState.OrganizationId; Stack = refreshState.Stack; RefreshToken(); } else if (parameters != null && parameters.AllKeys.Contains("jwt") && !string.IsNullOrEmpty(parameters["jwt"])) { if (string.IsNullOrEmpty(configSection.AppSignature)) { throw new Exception("Unable to utilize JWT for SSO without appSignature: Must be provided in config file or passed when instantiating ETClient"); } var encodedJWT = parameters["jwt"].ToString().Trim(); var decodedJWT = DecodeJWT(encodedJWT, configSection.AppSignature); var parsedJWT = JObject.Parse(decodedJWT); AuthToken = parsedJWT["request"]["user"]["oauthToken"].Value <string>().Trim(); AuthTokenExpiration = DateTime.Now.AddSeconds(int.Parse(parsedJWT["request"]["user"]["expiresIn"].Value <string>().Trim())); InternalAuthToken = parsedJWT["request"]["user"]["internalOauthToken"].Value <string>().Trim(); RefreshKey = parsedJWT["request"]["user"]["refreshToken"].Value <string>().Trim(); Jwt = parsedJWT; var orgPart = parsedJWT["request"]["organization"]; if (orgPart != null) { EnterpriseId = orgPart["enterpriseId"].Value <string>().Trim(); OrganizationId = orgPart["id"].Value <string>().Trim(); Stack = orgPart["stackKey"].Value <string>().Trim(); } } else { RefreshToken(); organizationFind = true; } // Find the appropriate endpoint for the acccount var grSingleEndpoint = new ETEndpoint { AuthStub = this, Type = "soap" }.Get(); if (grSingleEndpoint.Status && grSingleEndpoint.Results.Length == 1) { configSection.SoapEndPoint = ((ETEndpoint)grSingleEndpoint.Results[0]).URL; } else { throw new Exception("Unable to determine stack using /platform/v1/endpoints: " + grSingleEndpoint.Message); } // Create the SOAP binding for call with Oauth. SoapClient = new SoapClient(GetSoapBinding(), new EndpointAddress(new Uri(configSection.SoapEndPoint))); SoapClient.ClientCredentials.UserName.UserName = "******"; SoapClient.ClientCredentials.UserName.Password = "******"; // Find Organization Information if (organizationFind) { using (var scope = new OperationContextScope(SoapClient.InnerChannel)) { // Add oAuth token to SOAP header. XNamespace ns = "http://exacttarget.com"; var oauthElement = new XElement(ns + "oAuthToken", InternalAuthToken); var xmlHeader = MessageHeader.CreateHeader("oAuth", "http://exacttarget.com", oauthElement); OperationContext.Current.OutgoingMessageHeaders.Add(xmlHeader); var httpRequest = new System.ServiceModel.Channels.HttpRequestMessageProperty(); OperationContext.Current.OutgoingMessageProperties.Add(System.ServiceModel.Channels.HttpRequestMessageProperty.Name, httpRequest); httpRequest.Headers.Add(HttpRequestHeader.UserAgent, ETClient.SDKVersion); var req = new RetrieveRequest { ObjectType = "BusinessUnit", Properties = new[] { "ID", "Client.EnterpriseID" } }; var req1 = new RetrieveRequest1(req); var r = SoapClient.RetrieveAsync(req1).Result; if (r.OverallStatus == "OK" && r.Results.Length > 0) { EnterpriseId = r.Results[0].Client.EnterpriseID.ToString(); OrganizationId = r.Results[0].ID.ToString(); Stack = GetStackFromSoapEndPoint(new Uri(configSection.SoapEndPoint)); } } } }
private static Message ConfigureRequestMessage(Message message) { if (message == null) { return(null); } HttpRequestMessageProperty requestProperty = message.GetHttpRequestMessageProperty(); if (requestProperty == null) { throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, SR.RequestMissingHttpRequestMessageProperty, HttpRequestMessageProperty.Name, typeof(HttpRequestMessageProperty).FullName)); } Uri uri = message.Headers.To; if (uri == null) { throw new InvalidOperationException(SR.RequestMissingToHeader); } HttpRequestMessage httpRequestMessage = message.ToHttpRequestMessage(); if (httpRequestMessage == null) { httpRequestMessage = new HttpRequestMessage(); httpRequestMessage.Content = new StringContent(String.Empty); httpRequestMessage.Content.Headers.ContentLength = 0; message.Close(); message = httpRequestMessage.ToMessage(); } else { message.Headers.Clear(); message.Properties.Clear(); httpRequestMessage.Headers.Clear(); httpRequestMessage.GetProperties().Clear(); } message.Headers.To = uri; httpRequestMessage.RequestUri = uri; httpRequestMessage.Method = new HttpMethod(requestProperty.Method); foreach (var headerName in requestProperty.Headers.AllKeys) { if (headerName.StartsWith("content-", StringComparison.OrdinalIgnoreCase) || headerName.Equals("Allow", StringComparison.OrdinalIgnoreCase) || headerName.Equals("Expires") || headerName.Equals("Expires", StringComparison.OrdinalIgnoreCase)) { httpRequestMessage.Content.Headers.Remove(headerName); httpRequestMessage.Content.Headers.Add(headerName, requestProperty.Headers[headerName]); continue; } httpRequestMessage.Headers.Remove(headerName); httpRequestMessage.Headers.Add(headerName, requestProperty.Headers[headerName]); } return(message); }
public ETClient(NameValueCollection parameters = null, RefreshState refreshState = null) { // Get configuration file and set variables configSection = (FuelSDKConfigurationSection)ConfigurationManager.GetSection("fuelSDK"); configSection = (configSection != null ? (FuelSDKConfigurationSection)configSection.Clone() : new FuelSDKConfigurationSection()); configSection = configSection .WithDefaultAuthEndpoint(DefaultEndpoints.Auth) .WithDefaultRestEndpoint(DefaultEndpoints.Rest); if (parameters != null) { if (parameters.AllKeys.Contains("appSignature")) { configSection.AppSignature = parameters["appSignature"]; } if (parameters.AllKeys.Contains("clientId")) { configSection.ClientId = parameters["clientId"]; } if (parameters.AllKeys.Contains("clientSecret")) { configSection.ClientSecret = parameters["clientSecret"]; } if (parameters.AllKeys.Contains("soapEndPoint")) { configSection.SoapEndPoint = parameters["soapEndPoint"]; } if (parameters.AllKeys.Contains("authEndPoint")) { configSection.AuthenticationEndPoint = parameters["authEndPoint"]; } if (parameters.AllKeys.Contains("restEndPoint")) { configSection.RestEndPoint = parameters["restEndPoint"]; } } if (string.IsNullOrEmpty(configSection.ClientId) || string.IsNullOrEmpty(configSection.ClientSecret)) { throw new Exception("clientId or clientSecret is null: Must be provided in config file or passed when instantiating ETClient"); } // If JWT URL Parameter Used var organizationFind = false; if (refreshState != null) { RefreshKey = refreshState.RefreshKey; EnterpriseId = refreshState.EnterpriseId; OrganizationId = refreshState.OrganizationId; Stack = refreshState.Stack; RefreshToken(); } else if (parameters != null && parameters.AllKeys.Contains("jwt") && !string.IsNullOrEmpty(parameters["jwt"])) { if (string.IsNullOrEmpty(configSection.AppSignature)) { throw new Exception("Unable to utilize JWT for SSO without appSignature: Must be provided in config file or passed when instantiating ETClient"); } var encodedJWT = parameters["jwt"].ToString().Trim(); var decodedJWT = DecodeJWT(encodedJWT, configSection.AppSignature); var parsedJWT = JObject.Parse(decodedJWT); AuthToken = parsedJWT["request"]["user"]["oauthToken"].Value <string>().Trim(); AuthTokenExpiration = DateTime.Now.AddSeconds(int.Parse(parsedJWT["request"]["user"]["expiresIn"].Value <string>().Trim())); InternalAuthToken = parsedJWT["request"]["user"]["internalOauthToken"].Value <string>().Trim(); RefreshKey = parsedJWT["request"]["user"]["refreshToken"].Value <string>().Trim(); Jwt = parsedJWT; var orgPart = parsedJWT["request"]["organization"]; if (orgPart != null) { EnterpriseId = orgPart["enterpriseId"].Value <string>().Trim(); OrganizationId = orgPart["id"].Value <string>().Trim(); Stack = orgPart["stackKey"].Value <string>().Trim(); } } else { RefreshToken(); organizationFind = true; } FetchSoapEndpoint(); // Create the SOAP binding for call with Oauth. SoapClient = new SoapClient(GetSoapBinding(), new EndpointAddress(new Uri(configSection.SoapEndPoint))); SoapClient.ClientCredentials.UserName.UserName = "******"; SoapClient.ClientCredentials.UserName.Password = "******"; // Find Organization Information if (organizationFind) { using (var scope = new OperationContextScope(SoapClient.InnerChannel)) { // Add oAuth token to SOAP header. XNamespace ns = "http://exacttarget.com"; var oauthElement = new XElement(ns + "oAuthToken", InternalAuthToken); var xmlHeader = MessageHeader.CreateHeader("oAuth", "http://exacttarget.com", oauthElement); OperationContext.Current.OutgoingMessageHeaders.Add(xmlHeader); var httpRequest = new System.ServiceModel.Channels.HttpRequestMessageProperty(); OperationContext.Current.OutgoingMessageProperties.Add(System.ServiceModel.Channels.HttpRequestMessageProperty.Name, httpRequest); httpRequest.Headers.Add(HttpRequestHeader.UserAgent, ETClient.SDKVersion); string requestID; APIObject[] results; var r = SoapClient.Retrieve(new RetrieveRequest { ObjectType = "BusinessUnit", Properties = new[] { "ID", "Client.EnterpriseID" } }, out requestID, out results); if (r == "OK" && results.Length > 0) { EnterpriseId = results[0].Client.EnterpriseID.ToString(); OrganizationId = results[0].ID.ToString(); } } } }
void BeginProcessRequest(HttpChannelRequestAsyncResult result) { Message message = result.Message; TimeSpan timeout = result.Timeout; // FIXME: is distination really like this? Uri destination = message.Headers.To; if (destination == null) { if (source.Source.ManualAddressing) { throw new InvalidOperationException("When manual addressing is enabled on the transport, every request messages must be set its destination address."); } else { destination = Via ?? RemoteAddress.Uri; } } web_request = HttpWebRequest.Create(destination); web_request.Method = "POST"; web_request.ContentType = Encoder.ContentType; #if !NET_2_1 // FIXME: implement this to not depend on Timeout property web_request.Timeout = (int)timeout.TotalMilliseconds; #endif // There is no SOAP Action/To header when AddressingVersion is None. if (message.Version.Envelope.Equals(EnvelopeVersion.Soap11) || message.Version.Addressing.Equals(AddressingVersion.None)) { if (message.Headers.Action != null) { web_request.Headers ["SOAPAction"] = String.Concat("\"", message.Headers.Action, "\""); message.Headers.RemoveAll("Action", message.Version.Addressing.Namespace); } } // apply HttpRequestMessageProperty if exists. bool suppressEntityBody = false; #if !NET_2_1 string pname = HttpRequestMessageProperty.Name; if (message.Properties.ContainsKey(pname)) { HttpRequestMessageProperty hp = (HttpRequestMessageProperty)message.Properties [pname]; web_request.Headers.Add(hp.Headers); web_request.Method = hp.Method; // FIXME: do we have to handle hp.QueryString ? if (hp.SuppressEntityBody) { suppressEntityBody = true; } } #endif if (!suppressEntityBody && String.Compare(web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) { MemoryStream buffer = new MemoryStream(); Encoder.WriteMessage(message, buffer); if (buffer.Length > int.MaxValue) { throw new InvalidOperationException("The argument message is too large."); } #if !NET_2_1 web_request.ContentLength = (int)buffer.Length; #endif web_request.BeginGetRequestStream(delegate(IAsyncResult r) { try { result.CompletedSynchronously &= r.CompletedSynchronously; using (Stream s = web_request.EndGetRequestStream(r)) s.Write(buffer.GetBuffer(), 0, (int)buffer.Length); web_request.BeginGetResponse(GotResponse, result); } catch (Exception ex) { result.Complete(ex); } }, null); } else { web_request.BeginGetResponse(GotResponse, result); } }
private bool PrepareMessageHeaders(Message message) { string action = message.Headers.Action; if (action != null) { action = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", UrlUtility.UrlPathEncode(action)); } if (message.Version.Addressing == AddressingVersion.None) { message.Headers.Action = null; message.Headers.To = null; } bool suppressEntityBody = message is NullMessage; object property; if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property)) { HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)property; _httpRequestMessage.Method = new HttpMethod(requestProperty.Method); // Query string was applied in HttpChannelFactory.ApplyManualAddressing WebHeaderCollection requestHeaders = requestProperty.Headers; suppressEntityBody = suppressEntityBody || requestProperty.SuppressEntityBody; var headerKeys = requestHeaders.AllKeys; for (int i = 0; i < headerKeys.Length; i++) { string name = headerKeys[i]; string value = requestHeaders[name]; if (string.Compare(name, "accept", StringComparison.OrdinalIgnoreCase) == 0) { _httpRequestMessage.Headers.Accept.TryParseAdd(value); } else if (string.Compare(name, "connection", StringComparison.OrdinalIgnoreCase) == 0) { if (value.IndexOf("keep-alive", StringComparison.OrdinalIgnoreCase) != -1) { _httpRequestMessage.Headers.ConnectionClose = false; } else { _httpRequestMessage.Headers.Connection.TryParseAdd(value); } } else if (string.Compare(name, "SOAPAction", StringComparison.OrdinalIgnoreCase) == 0) { if (action == null) { action = value; } else { if (!String.IsNullOrEmpty(value) && string.Compare(value, action, StringComparison.Ordinal) != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ProtocolException(SR.Format(SR.HttpSoapActionMismatch, action, value))); } } } else if (string.Compare(name, "content-length", StringComparison.OrdinalIgnoreCase) == 0) { // this will be taken care of by System.Net when we write to the content } else if (string.Compare(name, "content-type", StringComparison.OrdinalIgnoreCase) == 0) { // Handled by MessageContent } else if (string.Compare(name, "expect", StringComparison.OrdinalIgnoreCase) == 0) { if (value.ToUpperInvariant().IndexOf("100-CONTINUE", StringComparison.OrdinalIgnoreCase) != -1) { _httpRequestMessage.Headers.ExpectContinue = true; } else { _httpRequestMessage.Headers.Expect.TryParseAdd(value); } } else if (string.Compare(name, "host", StringComparison.OrdinalIgnoreCase) == 0) { // this should be controlled through Via } else if (string.Compare(name, "referer", StringComparison.OrdinalIgnoreCase) == 0) { // referrer is proper spelling, but referer is the what is in the protocol. _httpRequestMessage.Headers.Referrer = new Uri(value); } else if (string.Compare(name, "transfer-encoding", StringComparison.OrdinalIgnoreCase) == 0) { if (value.ToUpperInvariant().IndexOf("CHUNKED", StringComparison.OrdinalIgnoreCase) != -1) { _httpRequestMessage.Headers.TransferEncodingChunked = true; } else { _httpRequestMessage.Headers.TransferEncoding.TryParseAdd(value); } } else if (string.Compare(name, "user-agent", StringComparison.OrdinalIgnoreCase) == 0) { _httpRequestMessage.Headers.UserAgent.Add(ProductInfoHeaderValue.Parse(value)); } else if (string.Compare(name, "if-modified-since", StringComparison.OrdinalIgnoreCase) == 0) { DateTimeOffset modifiedSinceDate; if (DateTimeOffset.TryParse(value, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeLocal, out modifiedSinceDate)) { _httpRequestMessage.Headers.IfModifiedSince = modifiedSinceDate; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ProtocolException(SR.Format(SR.HttpIfModifiedSinceParseError, value))); } } else if (string.Compare(name, "date", StringComparison.OrdinalIgnoreCase) == 0) { // this will be taken care of by System.Net when we make the request } else if (string.Compare(name, "proxy-connection", StringComparison.OrdinalIgnoreCase) == 0) { throw ExceptionHelper.PlatformNotSupported("proxy-connection"); } else if (string.Compare(name, "range", StringComparison.OrdinalIgnoreCase) == 0) { // specifying a range doesn't make sense in the context of WCF } else { try { _httpRequestMessage.Headers.Add(name, value); } catch (Exception addHeaderException) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format( SR.CopyHttpHeaderFailed, name, value, HttpChannelUtilities.HttpRequestHeadersTypeName), addHeaderException)); } } } } if (action != null) { if (message.Version.Envelope == EnvelopeVersion.Soap11) { _httpRequestMessage.Headers.TryAddWithoutValidation("SOAPAction", action); } else if (message.Version.Envelope == EnvelopeVersion.Soap12) { // Handled by MessageContent } else if (message.Version.Envelope != EnvelopeVersion.None) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ProtocolException(SR.Format(SR.EnvelopeVersionUnknown, message.Version.Envelope.ToString()))); } } // since we don't get the output stream in send when retVal == true, // we need to disable chunking for some verbs (DELETE/PUT) if (suppressEntityBody) { _httpRequestMessage.Headers.TransferEncodingChunked = false; } return(suppressEntityBody); }