diff --git a/src/Twilio/Base/BearerToken/TokenResourceSet.cs b/src/Twilio/Base/BearerToken/TokenResourceSet.cs deleted file mode 100644 index dfaec4c39..000000000 --- a/src/Twilio/Base/BearerToken/TokenResourceSet.cs +++ /dev/null @@ -1,124 +0,0 @@ -using System; -using System.Reflection; -using System.Collections.Generic; -using Twilio.Clients; -using Twilio.Clients.BearerToken; -using Twilio.Annotations; - -namespace Twilio.Base.BearerToken -{ - /// - /// A collection of resources of type T - /// - /// - /// Resource Type - [Beta] - public class TokenResourceSet : IEnumerable where T : Resource - { - /// - /// Automatically iterate through pages of results - /// - public bool AutoPaging { get; set; } - - private readonly TwilioOrgsTokenRestClient _client; - private readonly ReadOptions _options; - private readonly long _pageLimit; - - private long _pages; - private long _processed; - private Page _page; - private IEnumerator _iterator; - - /// - /// Create a new resource set - /// - /// - /// Page of resources - /// Read options - /// Client to make requests - public TokenResourceSet(Page page, ReadOptions options, TwilioOrgsTokenRestClient client) - { - _page = page; - _options = options; - _client = client; - - _iterator = page.Records.GetEnumerator(); - _processed = 0; - _pages = 1; - _pageLimit = long.MaxValue; - - AutoPaging = true; - - if (_options.Limit != null) - { - _pageLimit = (long) (Math.Ceiling((double) _options.Limit.Value / page.PageSize)); - } - } - - /// - /// Get iterator for resources - /// - /// - /// IEnumerator of resources - public IEnumerator GetEnumerator() - { - while (_page != null) - { - _iterator.Reset(); - while (_iterator.MoveNext()) - { - // Exit if we've reached item limit - if (_options.Limit != null && _processed > _options.Limit.Value) - { - yield break; - } - - _processed++; - yield return _iterator.Current; - } - - if (AutoPaging && _page.HasNextPage()) - { - FetchNextPage(); - } - else - { - break; - } - } - } - - /// - /// Get iterator for resources - /// - /// - /// IEnumerator of resources - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - - private void FetchNextPage() - { - if (!_page.HasNextPage() || _pages >= _pageLimit) - { - _page = null; - _iterator = null; - return; - } - - _pages++; - _page = (Page)GetNextPage().Invoke(null, new object[]{ _page, _client }); - _iterator = _page.Records.GetEnumerator(); - } - - private static MethodInfo GetNextPage() - { -#if !NET35 - return typeof(T).GetRuntimeMethod("NextPage", new[]{ typeof(Page), typeof(TwilioOrgsTokenRestClient) }); -#else - return typeof(T).GetMethod("NextPage", new[]{ typeof(Page), typeof(TwilioOrgsTokenRestClient) }); -#endif - } - } -} diff --git a/src/Twilio/Clients/BearerToken/TwilioOrgsTokenRestClient.cs b/src/Twilio/Clients/BearerToken/TwilioOrgsTokenRestClient.cs deleted file mode 100644 index 6ac86fcf4..000000000 --- a/src/Twilio/Clients/BearerToken/TwilioOrgsTokenRestClient.cs +++ /dev/null @@ -1,392 +0,0 @@ -using System; -using System.Net; -using System.Linq; -using Newtonsoft.Json; -using Twilio.Exceptions; -using Twilio.Http.BearerToken; -using Twilio.Jwt; -using Twilio.Clients; -using Twilio.Annotations; - -#if !NET35 -using System.IdentityModel.Tokens.Jwt; -using System.Threading.Tasks; -#endif - -using Twilio.Http; -using Twilio.Http.BearerToken; -#if NET35 -using Twilio.Http.Net35; -using System.Collections.Generic; -using System.Text; -using System.Web.Script.Serialization; -#endif - - -namespace Twilio.Clients.BearerToken -{ - /// - /// Implementation of a TwilioRestClient. - /// - [Deprecated] - public class TwilioOrgsTokenRestClient - { - /// - /// Client to make HTTP requests - /// - public TokenHttpClient HttpClient { get; } - - /// - /// Twilio region to make requests to - /// - public string Region { get; } - - /// - /// Twilio edge to make requests to - /// - public string Edge { get; set; } - - /// - /// Additions to the user agent string - /// - public string[] UserAgentExtensions { get; set; } - - /// - /// Log level for logging - /// - public string LogLevel { get; set; } = Environment.GetEnvironmentVariable("TWILIO_LOG_LEVEL"); - - /// - /// Token Manage for managing and refreshing tokens - /// - private TokenManager _tokenManager { get; set; } - - /// - /// Access token used for rest calls with bearer token authentication method - /// - private string _accessToken; - - private readonly object lockObject = new object(); - - /// - /// Constructor for a TwilioRestClient - /// - /// - /// to manage access token for requests - /// account sid to make requests for - /// region to make requests for - /// http client used to make the requests - /// edge to make requests for - public TwilioOrgsTokenRestClient( - TokenManager tokenManager, - string region = null, - TokenHttpClient httpClient = null, - string edge = null - ) - { - _tokenManager = tokenManager; - - HttpClient = httpClient ?? DefaultClient(); - - Region = region; - Edge = edge; - } - - /// - /// Check if an access token is expired or not. Use the System.IdentityModel.Tokens.Jwt; for versions other - /// than net35 and use redirect to custom function if net35 - /// - /// - /// access token for which expiry have to be checked - /// true if expired, false otherwise - public bool tokenExpired(String accessToken){ - #if NET35 - return IsTokenExpired(accessToken); - #else - return isTokenExpired(accessToken); - #endif - } - - /// - /// Make a request to the Twilio API - /// - /// - /// request to make - /// response of the request - public Response Request(TokenRequest request) - { - if ((_accessToken == null )|| tokenExpired(_accessToken)) { - lock (lockObject){ - if ((_accessToken == null) || tokenExpired(_accessToken)) { - _accessToken = _tokenManager.fetchAccessToken(); - } - } - } - request.SetAuth(_accessToken); - - if (LogLevel == "debug") - LogRequest(request); - - if (Region != null) - request.Region = Region; - - if (Edge != null) - request.Edge = Edge; - - if (UserAgentExtensions != null) - request.UserAgentExtensions = UserAgentExtensions; - - Response response; - try - { - response = HttpClient.MakeRequest(request); - if (LogLevel == "debug") - { - Console.WriteLine("response.status: " + response.StatusCode); - Console.WriteLine("response.headers: " + response.Headers); - } - } - catch (Exception clientException) - { - throw new ApiConnectionException( - "Connection Error: " + request.Method + request.ConstructUrl(), - clientException - ); - } - return ProcessResponse(response); - } - -#if NET35 - public static bool IsTokenExpired(string token) - { - try - { - // Split the token into its components - var parts = token.Split('.'); - if (parts.Length != 3) - throw new ArgumentException("Malformed token received"); - - // Decode the payload (the second part of the JWT) - string payload = Base64UrlEncoder.Decode(parts[1]); - - // Parse the payload JSON - var serializer = new JavaScriptSerializer(); - var payloadData = serializer.Deserialize>(payload); - - // Check the 'exp' claim - if (payloadData.TryGetValue("exp", out object expObj)) - { - if (long.TryParse(expObj.ToString(), out long exp)) - { - DateTime expirationDate = UnixTimeStampToDateTime(exp); - return DateTime.UtcNow > expirationDate; - } - } - - // If 'exp' claim is missing or not a valid timestamp, consider the token expired - throw new ApiConnectionException("token expired 1"); - return true; - } - catch (Exception ex) - { - // Handle exceptions (e.g., malformed token or invalid JSON) - Console.WriteLine($"Error checking token expiration: {ex.Message}"); - throw new ApiConnectionException("token expired 2"); - return true; // Consider as expired if there's an error - } - } - - private static DateTime UnixTimeStampToDateTime(long unixTimeStamp) - { - // Unix timestamp is seconds past epoch - var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - return epoch.AddSeconds(unixTimeStamp); - } -#endif - -#if !NET35 - public bool isTokenExpired(string token){ - var handler = new JwtSecurityTokenHandler(); - try{ - var jwtToken = handler.ReadJwtToken(token); - var exp = jwtToken.Payload.Exp; - if (exp.HasValue) - { - var expirationDate = DateTimeOffset.FromUnixTimeSeconds(exp.Value).UtcDateTime; - return DateTime.UtcNow > expirationDate; - } - else - { - return true; // Assuming token is expired if exp claim is missing - } - } - catch (Exception ex) - { - Console.WriteLine($"Error reading token: {ex.Message}"); - - return true; // Treat as expired if there is an error - } - } -#endif - -#if !NET35 - /// - /// Make a request to the Twilio API - /// - /// - /// request to make - /// Task that resolves to the response of the request - public async Task RequestAsync(TokenRequest request) - { - request.SetAuth(_accessToken); - - if (Region != null) - request.Region = Region; - - if (Edge != null) - request.Edge = Edge; - - if (UserAgentExtensions != null) - request.UserAgentExtensions = UserAgentExtensions; - - Response response; - try - { - response = await HttpClient.MakeRequestAsync(request); - } - catch (Exception clientException) - { - throw new ApiConnectionException( - "Connection Error: " + request.Method + request.ConstructUrl(), - clientException - ); - } - return ProcessResponse(response); - } - - private static TokenHttpClient DefaultClient() - { - return new SystemNetTokenHttpClient(); - } -#else - private static TokenHttpClient DefaultClient() - { - return new WebBearerTokenRequestClient(); - } -#endif - - private static Response ProcessResponse(Response response) - { - if (response == null) - { - throw new ApiConnectionException("Connection Error: No response received."); - } - - - if (response.StatusCode >= HttpStatusCode.OK && response.StatusCode < HttpStatusCode.BadRequest) - { - return response; - } - - // Deserialize and throw exception - RestException restException = null; - try - { - restException = RestException.FromJson(response.Content); - } - catch (JsonReaderException) { /* Allow null check below to handle */ } - - if (restException == null) - { - throw new ApiException("Api Error: " + response.StatusCode + " - " + (response.Content ?? "[no content]")); - } - - throw new ApiException( - restException.Code, - (int)response.StatusCode, - restException.Message ?? "Unable to make request, " + response.StatusCode, - restException.MoreInfo, - restException.Details - ); - } - - /// - /// Test if your environment is impacted by a TLS or certificate change - /// by sending an HTTP request to the test endpoint tls-test.twilio.com:443 - /// It's a bit easier to call this method from TwilioClient.ValidateSslCertificate(). - /// - public static void ValidateSslCertificate() - { - ValidateSslCertificate(DefaultClient()); - } - - /// - /// Test that this application can use updated SSL certificates on - /// tls-test.twilio.com:443. Generally, you'll want to use the version of this - /// function that takes no parameters unless you have a reason not to. - /// - /// - /// HTTP Client to use for testing the request - public static void ValidateSslCertificate(TokenHttpClient client) - { - TokenRequest request = new TokenRequest("GET", "tls-test", ":443/", null); - - try - { - Response response = client.MakeRequest(request); - - if (!response.StatusCode.Equals(HttpStatusCode.OK)) - { - throw new CertificateValidationException( - "Unexpected response from certificate endpoint", - null, - response - ); - } - } - catch (CertificateValidationException e) - { - throw e; - } - catch (Exception e) - { - throw new CertificateValidationException( - "Connection to tls-test.twilio.com:443 failed", - e, - null - ); - } - } - - /// - /// Format request information when LogLevel is set to debug - /// - /// - /// HTTP request - private static void LogRequest(TokenRequest request) - { - Console.WriteLine("-- BEGIN Twilio API Request --"); - Console.WriteLine("request.method: " + request.Method); - Console.WriteLine("request.URI: " + request.Uri); - - if (request.QueryParams != null) - { - request.QueryParams.ForEach(parameter => Console.WriteLine(parameter.Key + ":" + parameter.Value)); - } - - if (request.HeaderParams != null) - { - for (int i = 0; i < request.HeaderParams.Count; i++) - { - var lowercaseHeader = request.HeaderParams[i].Key.ToLower(); - if (lowercaseHeader.Contains("authorization") == false) - { - Console.WriteLine(request.HeaderParams[i].Key + ":" + request.HeaderParams[i].Value); - } - } - } - - Console.WriteLine("-- END Twilio API Request --"); - } - } -} diff --git a/src/Twilio/Twilio.csproj b/src/Twilio/Twilio.csproj index 44b3a0a8d..66c08fde8 100644 --- a/src/Twilio/Twilio.csproj +++ b/src/Twilio/Twilio.csproj @@ -38,14 +38,14 @@ - - + + - - + + diff --git a/src/Twilio/TwilioOrgsTokenAuth.cs b/src/Twilio/TwilioOrgsTokenAuth.cs deleted file mode 100644 index 0593af2e4..000000000 --- a/src/Twilio/TwilioOrgsTokenAuth.cs +++ /dev/null @@ -1,232 +0,0 @@ -using Twilio.Clients; -using Twilio.Clients.NoAuth; -using Twilio.Clients.BearerToken; -using Twilio.Exceptions; -using Twilio.Http.BearerToken; -using Twilio.Annotations; - - -namespace Twilio -{ - /// - /// Default Twilio Client for bearer token authentication - /// - [Beta] - public class TwilioOrgsTokenAuthClient - { - private static string _accessToken; - private static string _region; - private static string _edge; - private static TwilioOrgsTokenRestClient _restClient; - private static TwilioNoAuthRestClient _noAuthRestClient; - private static string _logLevel; - private static TokenManager _tokenManager; - private static string _clientId; - private static string _clientSecret; - - private TwilioOrgsTokenAuthClient() { } - - /// - /// Initialize base client with username and password - /// - public static void Init(string clientId, string clientSecret) - { - SetClientId(clientId); - SetClientSecret(clientSecret); - SetTokenManager(new OrgsTokenManager(clientId, clientSecret)); - } - - - /// - /// Initialize base client - /// - public static void Init(string clientId, string clientSecret, - string code = null, - string redirectUri = null, - string audience = null, - string refreshToken = null, - string scope = null) - { - SetClientId(clientId); - SetClientSecret(clientSecret); - SetTokenManager(new OrgsTokenManager(clientId, clientSecret, code, redirectUri, audience, refreshToken, scope)); - } - - /// - /// Set the token manager - /// - /// token manager - public static void SetTokenManager(TokenManager tokenManager) - { - if (tokenManager == null) - { - throw new AuthenticationException("Token Manager can not be null"); - } - - if (tokenManager != _tokenManager) - { - Invalidate(); - } - - _tokenManager = tokenManager; - } - - /// - /// Set the client id - /// - /// client id of the organisation - public static void SetClientId(string clientId) - { - if (clientId == null) - { - throw new AuthenticationException("Client Id can not be null"); - } - - if (clientId != _clientId) - { - Invalidate(); - } - - _clientId = clientId; - } - - /// - /// Set the client secret - /// - /// client secret of the organisation - public static void SetClientSecret(string clientSecret) - { - if (clientSecret == null) - { - throw new AuthenticationException("Client Secret can not be null"); - } - - if (clientSecret != _clientSecret) - { - Invalidate(); - } - - _clientSecret = clientSecret; - } - - /// - /// Set the client region - /// - /// Client region - public static void SetRegion(string region) - { - if (region != _region) - { - Invalidate(); - InvalidateNoAuthClient(); - } - _region = region; - } - - /// - /// Set the client edge - /// - /// Client edge - public static void SetEdge(string edge) - { - if (edge != _edge) - { - Invalidate(); - InvalidateNoAuthClient(); - } - _edge = edge; - } - - /// - /// Set the logging level - /// - /// log level - public static void SetLogLevel(string loglevel) - { - if (loglevel != _logLevel) - { - Invalidate(); - InvalidateNoAuthClient(); - } - _logLevel = loglevel; - } - - /// - /// Get the rest client - /// - /// The rest client - public static TwilioOrgsTokenRestClient GetRestClient() - { - if (_restClient != null) - { - return _restClient; - } - - if (_tokenManager == null) - { - throw new AuthenticationException( - "TwilioBearerTokenRestClient was used before token manager was set, please call TwilioClient.init()" - ); - } - - _restClient = new TwilioOrgsTokenRestClient(_tokenManager, region: _region, edge: _edge) - { - LogLevel = _logLevel - }; - return _restClient; - } - - - /// - /// Get the noauth rest client - /// - /// The not auth rest client - public static TwilioNoAuthRestClient GetNoAuthRestClient() - { - if (_noAuthRestClient != null) - { - return _noAuthRestClient; - } - - _noAuthRestClient = new TwilioNoAuthRestClient(region: _region, edge: _edge) - { - LogLevel = _logLevel - }; - return _noAuthRestClient; - } - - /// - /// Set the rest client - /// - /// Rest Client to use - public static void SetRestClient(TwilioOrgsTokenRestClient restClient) - { - _restClient = restClient; - } - - /// - /// Clear out the Rest Client - /// - public static void Invalidate() - { - _restClient = null; - } - - /// - /// Clear out the Rest Client - /// - public static void InvalidateNoAuthClient() - { - _noAuthRestClient = null; - } - - /// - /// Test if your environment is impacted by a TLS or certificate change - /// by sending an HTTP request to the test endpoint tls-test.twilio.com:443 - /// - public static void ValidateSslCertificate() - { - TwilioRestClient.ValidateSslCertificate(); - } - } -} diff --git a/test/Twilio.Test/ClusterTest.cs b/test/Twilio.Test/ClusterTest.cs index 3c149f715..25fd5dd54 100644 --- a/test/Twilio.Test/ClusterTest.cs +++ b/test/Twilio.Test/ClusterTest.cs @@ -43,7 +43,7 @@ public void SetUp() oAuthClientSecret = Environment.GetEnvironmentVariable("TWILIO_CLIENT_SECRET"); oAuthMessageId = Environment.GetEnvironmentVariable("TWILIO_MESSAGE_SID"); TwilioClient.Init(username:apiKey,password:secret,accountSid:accountSid); - TwilioOrgsTokenAuthClient.Init(clientId, clientSecret); + //TwilioOrgsTokenAuthClient.Init(clientId, clientSecret); }