示例#1
0
        internal dynamic CreatePayload(FuelSDKConfigurationSection config)
        {
            dynamic payload = new JObject();

            payload.client_id = config.ClientId;

            if (!config.ApplicationType.Equals("public"))
            {
                payload.client_secret = config.ClientSecret;
            }

            if (!string.IsNullOrEmpty(RefreshKey))
            {
                payload.grant_type    = "refresh_token";
                payload.refresh_token = RefreshKey;
            }
            else if (!config.ApplicationType.Equals("server"))
            {
                payload.grant_type   = "authorization_code";
                payload.code         = config.AuthorizationCode;
                payload.redirect_uri = config.RedirectURI;
            }
            else
            {
                payload.grant_type = "client_credentials";
            }

            if (!string.IsNullOrEmpty(config.AccountId))
            {
                payload.account_id = config.AccountId;
            }
            if (!string.IsNullOrEmpty(config.Scope))
            {
                payload.scope = config.Scope;
            }

            return(payload);
        }
示例#2
0
        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();
                    }
                }
            }
        }
 public AuthEndpointUriBuilder(FuelSDKConfigurationSection configSection)
 {
     this.configSection = configSection;
 }
示例#4
0
        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));
                    }
                }
            }
        }