From bee718b5bb4fa7e4233cc1bbf0306b0ae5d8c989 Mon Sep 17 00:00:00 2001 From: Tyler Warner Date: Thu, 25 Sep 2025 07:51:30 -0500 Subject: [PATCH 1/2] Add support for Secure Service Account API. --- Aps.Sdk.sln | 19 +- Directory.Packages.props | 1 + README.md | 1 + .../secureserviceaccount.sln | 28 + ...Authentication.SecureServiceAccount.csproj | 25 + .../source/Http/AccountManagementApi.gen.cs | 596 +++++++++++++++++ .../source/Http/ExchangeTokenApi.gen.cs | 290 ++++++++ .../source/Http/KeyManagementApi.gen.cs | 535 +++++++++++++++ .../source/LocalMarshalling.cs | 109 +++ .../source/Model/GrantType.gen.cs | 50 ++ .../source/Model/Key.gen.cs | 82 +++ .../source/Model/KeyCreated.gen.cs | 56 ++ .../source/Model/KeyStatus.gen.cs | 57 ++ .../source/Model/KeyUpdatePayload.gen.cs | 67 ++ .../source/Model/KeysResponse.gen.cs | 60 ++ .../source/Model/Scopes.gen.cs | 166 +++++ .../source/Model/ServiceAccount.gen.cs | 121 ++++ .../Model/ServiceAccountCreatePayload.gen.cs | 111 +++ .../source/Model/ServiceAccountCreated.gen.cs | 70 ++ .../source/Model/ServiceAccountStatus.gen.cs | 57 ++ .../Model/ServiceAccountUpdatePayload.gen.cs | 67 ++ .../Model/ServiceAccountsResponse.gen.cs | 60 ++ .../source/Model/ThreeLeggedToken.gen.cs | 82 +++ .../source/ServiceApiException.cs | 51 ++ .../source/ServiceCollectionExtensions.gen.cs | 46 ++ .../custom-code/SecureServiceAccountClient.cs | 630 ++++++++++++++++++ ...ntication.SecureServiceAccount.Test.csproj | 20 + .../test/TestSecureServiceAccount.cs | 175 +++++ 28 files changed, 3629 insertions(+), 3 deletions(-) create mode 100644 authentication/secureserviceaccount/secureserviceaccount.sln create mode 100644 authentication/secureserviceaccount/source/Autodesk.Authentication.SecureServiceAccount.csproj create mode 100644 authentication/secureserviceaccount/source/Http/AccountManagementApi.gen.cs create mode 100644 authentication/secureserviceaccount/source/Http/ExchangeTokenApi.gen.cs create mode 100644 authentication/secureserviceaccount/source/Http/KeyManagementApi.gen.cs create mode 100644 authentication/secureserviceaccount/source/LocalMarshalling.cs create mode 100644 authentication/secureserviceaccount/source/Model/GrantType.gen.cs create mode 100644 authentication/secureserviceaccount/source/Model/Key.gen.cs create mode 100644 authentication/secureserviceaccount/source/Model/KeyCreated.gen.cs create mode 100644 authentication/secureserviceaccount/source/Model/KeyStatus.gen.cs create mode 100644 authentication/secureserviceaccount/source/Model/KeyUpdatePayload.gen.cs create mode 100644 authentication/secureserviceaccount/source/Model/KeysResponse.gen.cs create mode 100644 authentication/secureserviceaccount/source/Model/Scopes.gen.cs create mode 100644 authentication/secureserviceaccount/source/Model/ServiceAccount.gen.cs create mode 100644 authentication/secureserviceaccount/source/Model/ServiceAccountCreatePayload.gen.cs create mode 100644 authentication/secureserviceaccount/source/Model/ServiceAccountCreated.gen.cs create mode 100644 authentication/secureserviceaccount/source/Model/ServiceAccountStatus.gen.cs create mode 100644 authentication/secureserviceaccount/source/Model/ServiceAccountUpdatePayload.gen.cs create mode 100644 authentication/secureserviceaccount/source/Model/ServiceAccountsResponse.gen.cs create mode 100644 authentication/secureserviceaccount/source/Model/ThreeLeggedToken.gen.cs create mode 100644 authentication/secureserviceaccount/source/ServiceApiException.cs create mode 100644 authentication/secureserviceaccount/source/ServiceCollectionExtensions.gen.cs create mode 100644 authentication/secureserviceaccount/source/custom-code/SecureServiceAccountClient.cs create mode 100644 authentication/secureserviceaccount/test/Autodesk.Authentication.SecureServiceAccount.Test.csproj create mode 100644 authentication/secureserviceaccount/test/TestSecureServiceAccount.cs diff --git a/Aps.Sdk.sln b/Aps.Sdk.sln index f95318c7..e1568aff 100644 --- a/Aps.Sdk.sln +++ b/Aps.Sdk.sln @@ -35,14 +35,15 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Autodesk.Construction.Accou EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Autodesk.Sdk.Manager", "sdkmanager\Autodesk.Sdk.Manager.csproj", "{38D360E7-663C-4A84-ADAF-D795FBF2426B}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "secureserviceaccount", "secureserviceaccount", "{02EA681E-C7D8-13C7-8484-4AC65E1B71E8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Autodesk.Authentication.SecureServiceAccount", "authentication\secureserviceaccount\source\Autodesk.Authentication.SecureServiceAccount.csproj", "{564373E6-71AF-B523-9AB6-EF4BAC93148F}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {ED05FF2A-8775-4552-B0FF-C9BCD6CB66D4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {ED05FF2A-8775-4552-B0FF-C9BCD6CB66D4}.Debug|Any CPU.Build.0 = Debug|Any CPU @@ -76,6 +77,13 @@ Global {38D360E7-663C-4A84-ADAF-D795FBF2426B}.Debug|Any CPU.Build.0 = Debug|Any CPU {38D360E7-663C-4A84-ADAF-D795FBF2426B}.Release|Any CPU.ActiveCfg = Release|Any CPU {38D360E7-663C-4A84-ADAF-D795FBF2426B}.Release|Any CPU.Build.0 = Release|Any CPU + {564373E6-71AF-B523-9AB6-EF4BAC93148F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {564373E6-71AF-B523-9AB6-EF4BAC93148F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {564373E6-71AF-B523-9AB6-EF4BAC93148F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {564373E6-71AF-B523-9AB6-EF4BAC93148F}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {ED05FF2A-8775-4552-B0FF-C9BCD6CB66D4} = {3E6CDD5D-9AEA-4A9C-9085-00D791DD34E4} @@ -86,5 +94,10 @@ Global {8C6376C9-61E6-4836-831E-8B3E8FDAE65F} = {0CDF551D-4B04-4860-BB8F-F3A77BC899ED} {2E7E4313-B859-4A56-9B52-A4A170C255B9} = {A291A1E6-780A-4EDD-A053-BD03218434FD} {5929BCE7-665A-472C-8498-A368E6675645} = {2E7E4313-B859-4A56-9B52-A4A170C255B9} + {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} = {F4C92067-B21E-4309-A426-C7CEC0BD6213} + {564373E6-71AF-B523-9AB6-EF4BAC93148F} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {4C7BFC9B-2B0C-429F-AA42-D9CC92B0CB40} EndGlobalSection EndGlobal diff --git a/Directory.Packages.props b/Directory.Packages.props index b78ce39d..1558521d 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -17,5 +17,6 @@ + \ No newline at end of file diff --git a/README.md b/README.md index d0adbb65..5012399e 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,7 @@ The Developer Portal has everything APS: - [Data Management](https://www.nuget.org/packages/Autodesk.DataManagement) - [Model Derivative](https://www.nuget.org/packages/Autodesk.ModelDerivative) - [OSS](https://www.nuget.org/packages/Autodesk.Oss) +- [Secure Service Account](https://www.nuget.org/packages/Autodesk.SecureServiceAccount) - [SDK Manager](https://www.nuget.org/packages/Autodesk.SDKManager) - [Webhooks](https://www.nuget.org/packages/Autodesk.Webhooks) diff --git a/authentication/secureserviceaccount/secureserviceaccount.sln b/authentication/secureserviceaccount/secureserviceaccount.sln new file mode 100644 index 00000000..4aefbac2 --- /dev/null +++ b/authentication/secureserviceaccount/secureserviceaccount.sln @@ -0,0 +1,28 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Autodesk.Authentication.SecureServiceAccount", "source\Autodesk.Authentication.SecureServiceAccount.csproj", "{1CFB83E1-D54E-47EF-8E4A-85307A766059}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Autodesk.Authentication.SecureServiceAccount.Test", "test\Autodesk.Authentication.SecureServiceAccount.Test.csproj", "{0BD9E57E-E19A-635F-A2FB-550E9EBEBA1B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1CFB83E1-D54E-47EF-8E4A-85307A766059}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1CFB83E1-D54E-47EF-8E4A-85307A766059}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1CFB83E1-D54E-47EF-8E4A-85307A766059}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1CFB83E1-D54E-47EF-8E4A-85307A766059}.Release|Any CPU.Build.0 = Release|Any CPU + {0BD9E57E-E19A-635F-A2FB-550E9EBEBA1B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0BD9E57E-E19A-635F-A2FB-550E9EBEBA1B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0BD9E57E-E19A-635F-A2FB-550E9EBEBA1B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0BD9E57E-E19A-635F-A2FB-550E9EBEBA1B}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/authentication/secureserviceaccount/source/Autodesk.Authentication.SecureServiceAccount.csproj b/authentication/secureserviceaccount/source/Autodesk.Authentication.SecureServiceAccount.csproj new file mode 100644 index 00000000..0c07ef78 --- /dev/null +++ b/authentication/secureserviceaccount/source/Autodesk.Authentication.SecureServiceAccount.csproj @@ -0,0 +1,25 @@ + + + + true + true + Autodesk Platform Services SDK Team + Client SDK for Secure Service Account API + + • Initial release of Secure Service Account API. + + Autodesk Inc. + Autodesk.SecureServiceAccount + 1.0.0 + LICENSE.txt + README.md + https://github.com/autodesk-platform-services/aps-sdk-net.git + + + + + + + + + diff --git a/authentication/secureserviceaccount/source/Http/AccountManagementApi.gen.cs b/authentication/secureserviceaccount/source/Http/AccountManagementApi.gen.cs new file mode 100644 index 00000000..6e013b19 --- /dev/null +++ b/authentication/secureserviceaccount/source/Http/AccountManagementApi.gen.cs @@ -0,0 +1,596 @@ +/* + * APS SDK + * + * The APS Platform contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. + * + * Authentication.SecureServiceAccount + * + * OAuth2 server-to-server account, key, and token management API. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using Autodesk.Authentication.SecureServiceAccount.Client; +using Autodesk.Authentication.SecureServiceAccount.Model; +using Autodesk.Forge.Core; +using Autodesk.SDKManager; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Runtime.Serialization; + +namespace Autodesk.Authentication.SecureServiceAccount.Http; + +/// +/// Represents a collection of functions to interact with the API endpoints +/// +public interface IAccountManagementApi +{ + /// + /// Creates a service account. + /// Only a server-to-server application can own service accounts. + /// An application can have up to 10 service accounts at any given time. + /// Upon a successful response, the operation returns the service account ID and email address. + /// + /// + /// Describes the creation of the service account. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <<>> + /// + System.Threading.Tasks.Task> CreateServiceAccountAsync(ServiceAccountCreatePayload serviceAccountCreatePayload = default(ServiceAccountCreatePayload), string accessToken = default(string), bool throwOnError = true); + + /// + /// Deletes an existing service account. + /// When a service account is deleted, all associated keys will also be deleted. + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <> + /// + System.Threading.Tasks.Task DeleteServiceAccountAsync(string serviceAccountId = default(string), string accessToken = default(string), bool throwOnError = true); + + /// + /// Retrieves the details for a service account. + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <<>> + /// + System.Threading.Tasks.Task> GetServiceAccountAsync(string serviceAccountId = default(string), string accessToken = default(string), bool throwOnError = true); + + /// + /// Retrieves all service accounts associated with an application. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <<>> + /// + System.Threading.Tasks.Task> GetServiceAccountsAsync(string accessToken = default(string), bool throwOnError = true); + + /// + /// Enables or disables a service account. + /// When a service account is in the disabled state, it loses its capability to manage its service account key. + /// Assertions signed by the key will be treated as invalid. + /// This operation allows enabling a service account that is in a diabled state. + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// Describes the updates to the service account. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <> + /// + System.Threading.Tasks.Task UpdateServiceAccountAsync(string serviceAccountId = default(string), ServiceAccountUpdatePayload serviceAccountUpdatePayload = default(ServiceAccountUpdatePayload), string accessToken = default(string), bool throwOnError = true); +} + +/// +/// Represents a collection of functions to interact with the API endpoints. +/// +public partial class AccountManagementApi : IAccountManagementApi +{ + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class using . + /// + /// + /// An instance of . + /// + public AccountManagementApi(SDKManager.SDKManager sdkManager) + { + Service = sdkManager.ApsClient.Service; + _logger = sdkManager.Logger; + } + + private static void SetQueryParameter(string name, object value, Dictionary dictionary) + { + if (value is Enum) + { + var type = value.GetType(); + var memberInfos = type.GetMember(value.ToString()); + var enumValueMemberInfo = memberInfos.FirstOrDefault(m => m.DeclaringType == type); + var valueAttributes = enumValueMemberInfo.GetCustomAttributes(typeof(EnumMemberAttribute), false); + if (valueAttributes.Length > 0) + { + dictionary.Add(name, ((EnumMemberAttribute)valueAttributes[0]).Value); + } + } + else if (value is int) + { + if ((int)value > 0) + { + dictionary.Add(name, value); + } + } + else + { + if (value != null) + { + dictionary.Add(name, value); + } + } + } + + private static void SetHeader(string baseName, object value, HttpRequestMessage request) + { + if (value is DateTime) + { + if ((DateTime)value != DateTime.MinValue) + { + request.Headers.TryAddWithoutValidation(baseName, LocalMarshalling.ParameterToString(value)); // header parameter + } + } + else + { + if (value != null) + { + if (!string.Equals(baseName, "Content-Range")) + { + request.Headers.TryAddWithoutValidation(baseName, LocalMarshalling.ParameterToString(value)); // header parameter + } + else + { + request.Content.Headers.Add(baseName, LocalMarshalling.ParameterToString(value)); + } + } + } + + } + + /// + /// Gets or sets the object. + /// + /// + /// An instance of the . + /// + public ForgeService Service { get; set; } + + /// + /// Creates a service account. + /// Only a server-to-server application can own service accounts. + /// An application can have up to 10 service accounts at any given time. + /// Upon a successful response, the operation returns the service account ID and email address. + /// + /// + /// Describes the creation of the service account. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <<>> + /// + public async System.Threading.Tasks.Task> CreateServiceAccountAsync(ServiceAccountCreatePayload serviceAccountCreatePayload = default(ServiceAccountCreatePayload), string accessToken = default(string), bool throwOnError = true) + { + _logger.LogInformation($"Entered into {nameof(CreateServiceAccountAsync)}"); + + using var request = new HttpRequestMessage(); + + var queryParam = new Dictionary(); + request.RequestUri = + Marshalling.BuildRequestUri("/authentication/v2/service-accounts", + routeParameters: new Dictionary + { + }, + queryParameters: queryParam + ); + + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + request.Headers.TryAddWithoutValidation("User-Agent", "APS SDK/SECURE SERVICE ACCOUNT/C#/2.0.0"); + + if (!string.IsNullOrEmpty(accessToken)) + { + request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {accessToken}"); + } + + request.Content = Marshalling.Serialize(serviceAccountCreatePayload); + + request.Method = HttpMethod.Post; + + // Make the HTTP request. + var response = await Service.Client.SendAsync(request); + + if (throwOnError) + { + try + { + await response.EnsureSuccessStatusCodeAsync(); + } + catch (HttpRequestException ex) + { + throw new SecureServiceAccountApiException(ex.Message, response, ex); + } + } + else if (!response.IsSuccessStatusCode) + { + _logger.LogError($"Response unsuccess with status code: {response.StatusCode}"); + return new ApiResponse(response, default(ServiceAccountCreated)); + } + _logger.LogInformation($"Exited from {nameof(CreateServiceAccountAsync)} with response statusCode: {response.StatusCode}"); + return new ApiResponse(response, await LocalMarshalling.DeserializeAsync(response.Content)); + } + + /// + /// Deletes an existing service account. + /// When a service account is deleted, all associated keys will also be deleted. + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <> + /// + public async System.Threading.Tasks.Task DeleteServiceAccountAsync(string serviceAccountId = default(string), string accessToken = default(string), bool throwOnError = true) + { + _logger.LogInformation($"Entered into {nameof(DeleteServiceAccountAsync)}"); + + using var request = new HttpRequestMessage(); + + var queryParam = new Dictionary(); + request.RequestUri = + Marshalling.BuildRequestUri("/authentication/v2/service-accounts/{serviceAccountId}", + routeParameters: new Dictionary + { + { "serviceAccountId", serviceAccountId}, + }, + queryParameters: queryParam + ); + + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + request.Headers.TryAddWithoutValidation("User-Agent", "APS SDK/SECURE SERVICE ACCOUNT/C#/2.0.0"); + + if (!string.IsNullOrEmpty(accessToken)) + { + request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {accessToken}"); + } + + request.Method = HttpMethod.Delete; + + // Make the HTTP request. + var response = await Service.Client.SendAsync(request); + + if (throwOnError) + { + try + { + await response.EnsureSuccessStatusCodeAsync(); + } + catch (HttpRequestException ex) + { + throw new SecureServiceAccountApiException(ex.Message, response, ex); + } + } + else if (!response.IsSuccessStatusCode) + { + _logger.LogError($"Response unsuccess with status code: {response.StatusCode}"); + return response; + } + _logger.LogInformation($"Exited from {nameof(DeleteServiceAccountAsync)} with response statusCode: {response.StatusCode}"); + return response; + } + + /// + /// Retrieves the details for a service account. + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <<>> + /// + public async System.Threading.Tasks.Task> GetServiceAccountAsync(string serviceAccountId = default(string), string accessToken = default(string), bool throwOnError = true) + { + _logger.LogInformation($"Entered into {nameof(GetServiceAccountAsync)}"); + + using var request = new HttpRequestMessage(); + + var queryParam = new Dictionary(); + request.RequestUri = + Marshalling.BuildRequestUri("/authentication/v2/service-accounts/{serviceAccountId}", + routeParameters: new Dictionary + { + { "serviceAccountId", serviceAccountId}, + }, + queryParameters: queryParam + ); + + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + request.Headers.TryAddWithoutValidation("User-Agent", "APS SDK/SECURE SERVICE ACCOUNT/C#/2.0.0"); + + if (!string.IsNullOrEmpty(accessToken)) + { + request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {accessToken}"); + } + + request.Method = HttpMethod.Get; + + // Make the HTTP request. + var response = await Service.Client.SendAsync(request); + + if (throwOnError) + { + try + { + await response.EnsureSuccessStatusCodeAsync(); + } + catch (HttpRequestException ex) + { + throw new SecureServiceAccountApiException(ex.Message, response, ex); + } + } + else if (!response.IsSuccessStatusCode) + { + _logger.LogError($"Response unsuccess with status code: {response.StatusCode}"); + return new ApiResponse(response, default(ServiceAccount)); + } + _logger.LogInformation($"Exited from {nameof(GetServiceAccountAsync)} with response statusCode: {response.StatusCode}"); + return new ApiResponse(response, await LocalMarshalling.DeserializeAsync(response.Content)); + } + + /// + /// Retrieves all service accounts associated with an application. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <<>> + /// + public async System.Threading.Tasks.Task> GetServiceAccountsAsync(string accessToken = default(string), bool throwOnError = true) + { + _logger.LogInformation($"Entered into {nameof(GetServiceAccountsAsync)}"); + + using var request = new HttpRequestMessage(); + + var queryParam = new Dictionary(); + request.RequestUri = + Marshalling.BuildRequestUri("/authentication/v2/service-accounts", + routeParameters: new Dictionary + { + }, + queryParameters: queryParam + ); + + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + request.Headers.TryAddWithoutValidation("User-Agent", "APS SDK/SECURE SERVICE ACCOUNT/C#/2.0.0"); + + if (!string.IsNullOrEmpty(accessToken)) + { + request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {accessToken}"); + } + + request.Method = HttpMethod.Get; + + // Make the HTTP request. + var response = await Service.Client.SendAsync(request); + + string json = await response.Content.ReadAsStringAsync(); + + if (throwOnError) + { + try + { + await response.EnsureSuccessStatusCodeAsync(); + } + catch (HttpRequestException ex) + { + throw new SecureServiceAccountApiException(ex.Message, response, ex); + } + } + else if (!response.IsSuccessStatusCode) + { + _logger.LogError($"Response unsuccess with status code: {response.StatusCode}"); + return new ApiResponse(response, default(ServiceAccountsResponse)); + } + _logger.LogInformation($"Exited from {nameof(GetServiceAccountsAsync)} with response statusCode: {response.StatusCode}"); + return new ApiResponse(response, await LocalMarshalling.DeserializeAsync(response.Content)); + } + + /// + /// Enables or disables a service account. + /// When a service account is in the disabled state, it loses its capability to manage its service account key. + /// Assertions signed by the key will be treated as invalid. + /// This operation allows enabling a service account that is in a diabled state. + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// Describes the updates to the service account. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <> + /// + public async System.Threading.Tasks.Task UpdateServiceAccountAsync(string serviceAccountId = default(string), ServiceAccountUpdatePayload serviceAccountUpdatePayload = default(ServiceAccountUpdatePayload), string accessToken = default(string), bool throwOnError = true) + { + _logger.LogInformation($"Entered into {nameof(UpdateServiceAccountAsync)}"); + + using var request = new HttpRequestMessage(); + + var queryParam = new Dictionary(); + request.RequestUri = + Marshalling.BuildRequestUri("/authentication/v2/service-accounts/{serviceAccountId}", + routeParameters: new Dictionary + { + { "serviceAccountId", serviceAccountId}, + }, + queryParameters: queryParam + ); + + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + request.Headers.TryAddWithoutValidation("User-Agent", "APS SDK/SECURE SERVICE ACCOUNT/C#/2.0.0"); + + if (!string.IsNullOrEmpty(accessToken)) + { + request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {accessToken}"); + } + + request.Content = Marshalling.Serialize(serviceAccountUpdatePayload); + + request.Method = HttpMethod.Patch; + + // Make the HTTP request. + var response = await Service.Client.SendAsync(request); + + if (throwOnError) + { + try + { + await response.EnsureSuccessStatusCodeAsync(); + } + catch (HttpRequestException ex) + { + throw new SecureServiceAccountApiException(ex.Message, response, ex); + } + } + else if (!response.IsSuccessStatusCode) + { + _logger.LogError($"Response unsuccess with status code: {response.StatusCode}"); + return response; + } + _logger.LogInformation($"Exited from {nameof(UpdateServiceAccountAsync)} with response statusCode: {response.StatusCode}"); + return response; + } +} diff --git a/authentication/secureserviceaccount/source/Http/ExchangeTokenApi.gen.cs b/authentication/secureserviceaccount/source/Http/ExchangeTokenApi.gen.cs new file mode 100644 index 00000000..4ce9004a --- /dev/null +++ b/authentication/secureserviceaccount/source/Http/ExchangeTokenApi.gen.cs @@ -0,0 +1,290 @@ +/* + * APS SDK + * + * The APS Platform contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. + * + * Authentication.SecureServiceAccount + * + * OAuth2 server-to-server account, key, and token management API. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using Autodesk.Authentication.SecureServiceAccount.Client; +using Autodesk.Authentication.SecureServiceAccount.Model; +using Autodesk.Forge.Core; +using Autodesk.SDKManager; +using Microsoft.Extensions.Logging; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Runtime.Serialization; + +namespace Autodesk.Authentication.SecureServiceAccount.Http; + +/// +/// Represents a collection of functions to interact with the API endpoints +/// +public interface IExchangeTokenApi +{ + /// + /// Returns a three-legged access token for the JWT assertion you provide in the request body. + /// See the Developer’s Guide topic JWT Assertions for information on how to generate a JWT assertion for this operation. + /// This operation is only for confidential clients. + /// It requires Basic Authorization (client_id, client_secret). + /// Authentication information (client_id, client_secret) can be included either in the header or the body, but not both simultaneously. + /// + /// + /// Must be `Basic <BASE64_ENCODED_STRING>` where `<BASE64_ENCODED_STRING>` is the Base64 encoding of the concatenated string `<CLIENT_ID>:<CLIENT_SECRET>`. + /// This parameter is required only if client_id and client_secret are not provided in the request body. + /// (optional) + /// + /// + /// Must be `urn:ietf:params:oauth:grant-type:jwt-bearer`. + /// + /// + /// The value of the JWT assertion to exchange for a three-legged access-token. See JWT Assertions for instructions on how to generate a JWT assertion. + /// + /// + /// An additional option where the client can either use the authorization header or opt to send this information in the body. + /// (optional) + /// + /// + /// An additional option where the client can either use the authorization header or opt to send this information in the body. + /// (optional) + /// + /// + /// A list of requested scopes. + /// See the [Developer's Guide documentation on scopes](/en/docs/oauth/v2/developers_guide/scopes/) for a list of valid values you can provide. + /// The scope in the token endpoint request body should be a subset of or the same as the scope specified in the assertion. + /// If the scope is not present, then the returned access token will have the same scope as the assertion. + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <<>> + /// + System.Threading.Tasks.Task> ExchangeJwtAssertionAsync(string authorization = default(string), GrantType? grantType = null, string assertion = default(string), string clientId = default(string), string clientSecret = default(string), List scopes = null, bool throwOnError = true); +} + +/// +/// Represents a collection of functions to interact with the API endpoints. +/// +public partial class ExchangeTokenApi : IExchangeTokenApi +{ + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class using . + /// + /// + /// An instance of . + /// + public ExchangeTokenApi(SDKManager.SDKManager sdkManager) + { + Service = sdkManager.ApsClient.Service; + _logger = sdkManager.Logger; + } + + private static void SetQueryParameter(string name, object value, Dictionary dictionary) + { + if (value is Enum) + { + var type = value.GetType(); + var memberInfos = type.GetMember(value.ToString()); + var enumValueMemberInfo = memberInfos.FirstOrDefault(m => m.DeclaringType == type); + var valueAttributes = enumValueMemberInfo.GetCustomAttributes(typeof(EnumMemberAttribute), false); + if (valueAttributes.Length > 0) + { + dictionary.Add(name, ((EnumMemberAttribute)valueAttributes[0]).Value); + } + } + else if (value is int) + { + if ((int)value > 0) + { + dictionary.Add(name, value); + } + } + else if (value is IList) + { + if (value is List) + { + dictionary.Add(name, string.Join(" ", (List)value)); + } + else + { + List concatenatedList = []; + foreach (var x in (IList)value) + { + var type = x.GetType(); + var memberInfos = type.GetMember(x.ToString()); + var enumValueMemberInfo = memberInfos.FirstOrDefault(m => m.DeclaringType == type); + var valueAttributes = enumValueMemberInfo.GetCustomAttributes(typeof(EnumMemberAttribute), false); + concatenatedList.Add(((EnumMemberAttribute)valueAttributes[0]).Value); + } + dictionary.Add(name, string.Join(" ", concatenatedList)); + } + } + else + { + if (value != null) + { + dictionary.Add(name, value); + } + } + } + + private static void SetHeader(string baseName, object value, HttpRequestMessage request) + { + if (value is DateTime) + { + if ((DateTime)value != DateTime.MinValue) + { + request.Headers.TryAddWithoutValidation(baseName, LocalMarshalling.ParameterToString(value)); // header parameter + } + } + else + { + if (value != null) + { + if (!string.Equals(baseName, "Content-Range")) + { + request.Headers.TryAddWithoutValidation(baseName, LocalMarshalling.ParameterToString(value)); // header parameter + } + else + { + request.Content.Headers.Add(baseName, LocalMarshalling.ParameterToString(value)); + } + } + } + } + + /// + /// Gets or sets the object. + /// + /// + /// An instance of the . + /// + public ForgeService Service { get; set; } + + /// + /// Returns a three-legged access token for the JWT assertion you provide in the request body. + /// See the Developer’s Guide topic JWT Assertions for information on how to generate a JWT assertion for this operation. + /// This operation is only for confidential clients. + /// It requires Basic Authorization (client_id, client_secret). + /// Authentication information (client_id, client_secret) can be included either in the header or the body, but not both simultaneously. + /// + /// + /// Must be `Basic <BASE64_ENCODED_STRING>` where `<BASE64_ENCODED_STRING>` is the Base64 encoding of the concatenated string `<CLIENT_ID>:<CLIENT_SECRET>`. + /// This parameter is required only if client_id and client_secret are not provided in the request body. + /// (optional) + /// + /// + /// Must be `urn:ietf:params:oauth:grant-type:jwt-bearer`. + /// + /// + /// The value of the JWT assertion to exchange for a three-legged access-token. See JWT Assertions for instructions on how to generate a JWT assertion. + /// + /// + /// An additional option where the client can either use the authorization header or opt to send this information in the body. + /// (optional) + /// + /// + /// An additional option where the client can either use the authorization header or opt to send this information in the body. + /// (optional) + /// + /// + /// A list of requested scopes. + /// See the [Developer's Guide documentation on scopes](/en/docs/oauth/v2/developers_guide/scopes/) for a list of valid values you can provide. + /// The scope in the token endpoint request body should be a subset of or the same as the scope specified in the assertion. + /// If the scope is not present, then the returned access token will have the same scope as the assertion. + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <<>> + /// + public async System.Threading.Tasks.Task> ExchangeJwtAssertionAsync(string authorization = default(string), GrantType? grantType = null, string assertion = default(string), string clientId = default(string), string clientSecret = default(string), List scopes = null, bool throwOnError = true) + { + _logger.LogInformation($"Entered into {nameof(ExchangeJwtAssertionAsync)}"); + + using var request = new HttpRequestMessage(); + + var queryParam = new Dictionary(); + request.RequestUri = + Marshalling.BuildRequestUri("/authentication/v2/token", + routeParameters: new Dictionary + { + }, + queryParameters: queryParam + ); + + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + request.Headers.TryAddWithoutValidation("User-Agent", "APS SDK/SECURE SERVICE ACCOUNT/C#/2.0.0"); + + if (!string.IsNullOrEmpty(authorization)) + { + request.Headers.TryAddWithoutValidation("Authorization", $"Basic {authorization}"); + } + + var formParams = new Dictionary(); + // Convert grantType enum to string + SetQueryParameter("grant_type", grantType, formParams); + if (!string.IsNullOrEmpty(assertion)) { formParams.Add("assertion", assertion); } + // Convert scopes enum to string + SetQueryParameter("scope", scopes, formParams); + if (!string.IsNullOrEmpty(clientId) && string.IsNullOrEmpty(authorization)) { formParams.Add("client_id", clientId); } + if (!string.IsNullOrEmpty(clientSecret) && string.IsNullOrEmpty(authorization)) { formParams.Add("client_secret", clientSecret); } + + request.Content = new FormUrlEncodedContent(new Dictionary(formParams.ToDictionary(k => k.Key, k => k.Value.ToString()))); + + request.Method = HttpMethod.Post; + + // Make the HTTP request. + var response = await Service.Client.SendAsync(request); + + if (throwOnError) + { + try + { + await response.EnsureSuccessStatusCodeAsync(); + } + catch (HttpRequestException ex) + { + throw new SecureServiceAccountApiException(ex.Message, response, ex); + } + } + else if (!response.IsSuccessStatusCode) + { + _logger.LogError($"Response unsuccess with status code: {response.StatusCode}"); + return new ApiResponse(response, default(ThreeLeggedToken)); + } + _logger.LogInformation($"Exited from {nameof(ExchangeJwtAssertionAsync)} with response statusCode: {response.StatusCode}"); + return new ApiResponse(response, await LocalMarshalling.DeserializeAsync(response.Content)); + } +} diff --git a/authentication/secureserviceaccount/source/Http/KeyManagementApi.gen.cs b/authentication/secureserviceaccount/source/Http/KeyManagementApi.gen.cs new file mode 100644 index 00000000..f699288e --- /dev/null +++ b/authentication/secureserviceaccount/source/Http/KeyManagementApi.gen.cs @@ -0,0 +1,535 @@ +/* + * APS SDK + * + * The APS Platform contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. + * + * Authentication.SecureServiceAccount + * + * OAuth2 server-to-server account, key, and token management API. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using Autodesk.Authentication.SecureServiceAccount.Client; +using Autodesk.Authentication.SecureServiceAccount.Model; +using Autodesk.Forge.Core; +using Microsoft.Extensions.Logging; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Runtime.Serialization; + +namespace Autodesk.Authentication.SecureServiceAccount.Http; + +/// +/// Represents a collection of functions to interact with the API endpoints +/// +public interface IKeyManagementApi +{ + /// + /// Creates a service account key. + /// A service account key is a public-private key pair, generated using RSA with a key length of 2048 bits by the Identity Authorization Service(AuthZ). + /// The private key is returned once during its creation.AuthZ only stores the public key. + /// A service account can have up to 3 keys at any given time. + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <<>> + /// + System.Threading.Tasks.Task> CreateKeyAsync(string serviceAccountId = default(string), string accessToken = default(string), bool throwOnError = true); + + /// + /// Deletes an existing key. + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// The ID of the private key. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <> + /// + System.Threading.Tasks.Task DeleteKeyAsync(string serviceAccountId = default(string), string keyId = default(string), string accessToken = default(string), bool throwOnError = true); + + /// + /// Lists all keys associated with the service account. + /// This operation will only return key metadata, not the private or public key. + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <<>> + /// + System.Threading.Tasks.Task> GetKeysAsync(string serviceAccountId = default(string), string accessToken = default(string), bool throwOnError = true); + + /// + /// Deletes an existing key. + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// The ID of the private key. + /// + /// + /// Describes the updates to the key associated with the service account. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <> + /// + System.Threading.Tasks.Task UpdateKeyAsync(string serviceAccountId = default(string), string keyId = default(string), KeyUpdatePayload keyUpdatePayload = default(KeyUpdatePayload), string accessToken = default(string), bool throwOnError = true); +} + +/// +/// Represents a collection of functions to interact with the API endpoints +/// +public partial class KeyManagementApi : IKeyManagementApi +{ + private ILogger _logger; + + /// + /// Initializes a new instance of the class + /// using SDKManager object + /// + /// + /// An instance of SDKManager + /// + public KeyManagementApi(SDKManager.SDKManager sdkManager) + { + Service = sdkManager.ApsClient.Service; + _logger = sdkManager.Logger; + } + + private void SetQueryParameter(string name, object value, Dictionary dictionary) + { + if (value is Enum) + { + var type = value.GetType(); + var memberInfos = type.GetMember(value.ToString()); + var enumValueMemberInfo = memberInfos.FirstOrDefault(m => m.DeclaringType == type); + var valueAttributes = enumValueMemberInfo.GetCustomAttributes(typeof(EnumMemberAttribute), false); + if (valueAttributes.Length > 0) + { + dictionary.Add(name, ((EnumMemberAttribute)valueAttributes[0]).Value); + } + } + else if (value is int) + { + if ((int)value > 0) + { + dictionary.Add(name, value); + } + } + else if (value is IList) + { + if (value is List) + { + dictionary.Add(name, string.Join(" ", (List)value)); + } + else + { + List concatenatedList = []; + foreach (var x in (IList)value) + { + var type = x.GetType(); + var memberInfos = type.GetMember(x.ToString()); + var enumValueMemberInfo = memberInfos.FirstOrDefault(m => m.DeclaringType == type); + var valueAttributes = enumValueMemberInfo.GetCustomAttributes(typeof(EnumMemberAttribute), false); + concatenatedList.Add(((EnumMemberAttribute)valueAttributes[0]).Value); + } + dictionary.Add(name, string.Join(" ", concatenatedList)); + } + } + else + { + if (value != null) + { + dictionary.Add(name, value); + } + } + } + + private void SetHeader(string baseName, object value, HttpRequestMessage req) + { + if (value is DateTime) + { + if ((DateTime)value != DateTime.MinValue) + { + req.Headers.TryAddWithoutValidation(baseName, LocalMarshalling.ParameterToString(value)); // header parameter + } + } + else + { + if (value != null) + { + if (!string.Equals(baseName, "Content-Range")) + { + req.Headers.TryAddWithoutValidation(baseName, LocalMarshalling.ParameterToString(value)); // header parameter + } + else + { + req.Content.Headers.Add(baseName, LocalMarshalling.ParameterToString(value)); + } + } + } + } + + /// + /// Gets or sets the ApsConfiguration object + /// + /// An instance of the ForgeService + public ForgeService Service { get; set; } + + /// + /// Creates a service account key. + /// A service account key is a public-private key pair, generated using RSA with a key length of 2048 bits by the Identity Authorization Service(AuthZ). + /// The private key is returned once during its creation.AuthZ only stores the public key. + /// A service account can have up to 3 keys at any given time. + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <<>> + /// + public async System.Threading.Tasks.Task> CreateKeyAsync(string serviceAccountId = default(string), string accessToken = default(string), bool throwOnError = true) + { + _logger.LogInformation($"Entered into {nameof(CreateKeyAsync)}"); + + using var request = new HttpRequestMessage(); + + var queryParam = new Dictionary(); + request.RequestUri = + Marshalling.BuildRequestUri("/authentication/v2/service-accounts/{serviceAccountId}/keys", + routeParameters: new Dictionary + { + { "serviceAccountId", serviceAccountId}, + }, + queryParameters: queryParam + ); + + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + request.Headers.TryAddWithoutValidation("User-Agent", "APS SDK/SECURE SERVICE ACCOUNT/C#/2.0.0"); + + if (!string.IsNullOrEmpty(accessToken)) + { + request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {accessToken}"); + } + + request.Method = HttpMethod.Post; + + // Make the HTTP request. + var response = await Service.Client.SendAsync(request); + + if (throwOnError) + { + try + { + await response.EnsureSuccessStatusCodeAsync(); + } + catch (HttpRequestException ex) + { + throw new SecureServiceAccountApiException(ex.Message, response, ex); + } + } + else if (!response.IsSuccessStatusCode) + { + _logger.LogError($"Response unsuccess with status code: {response.StatusCode}"); + return new ApiResponse(response, default(KeyCreated)); + } + _logger.LogInformation($"Exited from {nameof(CreateKeyAsync)} with response statusCode: {response.StatusCode}"); + return new ApiResponse(response, await LocalMarshalling.DeserializeAsync(response.Content)); + } + + /// + /// Deletes an existing key. + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// The ID of the private key. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <> + /// + public async System.Threading.Tasks.Task DeleteKeyAsync(string serviceAccountId = default(string), string keyId = default(string), string accessToken = default(string), bool throwOnError = true) + { + _logger.LogInformation($"Entered into {nameof(DeleteKeyAsync)}"); + + using var request = new HttpRequestMessage(); + + var queryParam = new Dictionary(); + request.RequestUri = + Marshalling.BuildRequestUri("/authentication/v2/service-accounts/{serviceAccountId}/keys/{keyId}", + routeParameters: new Dictionary + { + { "serviceAccountId", serviceAccountId}, + { "keyId", keyId }, + }, + queryParameters: queryParam + ); + + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + request.Headers.TryAddWithoutValidation("User-Agent", "APS SDK/SECURE SERVICE ACCOUNT/C#/2.0.0"); + + if (!string.IsNullOrEmpty(accessToken)) + { + request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {accessToken}"); + } + + request.Method = HttpMethod.Delete; + + // Make the HTTP request. + var response = await Service.Client.SendAsync(request); + + if (throwOnError) + { + try + { + await response.EnsureSuccessStatusCodeAsync(); + } + catch (HttpRequestException ex) + { + throw new SecureServiceAccountApiException(ex.Message, response, ex); + } + } + else if (!response.IsSuccessStatusCode) + { + _logger.LogError($"Response unsuccess with status code: {response.StatusCode}"); + return response; + } + _logger.LogInformation($"Exited from {nameof(DeleteKeyAsync)} with response statusCode: {response.StatusCode}"); + return response; + } + + /// + /// Lists all keys associated with the service account. + /// This operation will only return key metadata, not the private or public key. + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <<>> + /// + public async System.Threading.Tasks.Task> GetKeysAsync(string serviceAccountId = default(string), string accessToken = default(string), bool throwOnError = true) + { + _logger.LogInformation($"Entered into {nameof(GetKeysAsync)}"); + + using var request = new HttpRequestMessage(); + + var queryParam = new Dictionary(); + request.RequestUri = + Marshalling.BuildRequestUri("/authentication/v2/service-accounts/{serviceAccountId}/keys", + routeParameters: new Dictionary + { + { "serviceAccountId", serviceAccountId}, + }, + queryParameters: queryParam + ); + + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + request.Headers.TryAddWithoutValidation("User-Agent", "APS SDK/SECURE SERVICE ACCOUNT/C#/2.0.0"); + + if (!string.IsNullOrEmpty(accessToken)) + { + request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {accessToken}"); + } + + request.Method = HttpMethod.Get; + + // Make the HTTP request. + var response = await Service.Client.SendAsync(request); + + if (throwOnError) + { + try + { + await response.EnsureSuccessStatusCodeAsync(); + } + catch (HttpRequestException ex) + { + throw new SecureServiceAccountApiException(ex.Message, response, ex); + } + } + else if (!response.IsSuccessStatusCode) + { + _logger.LogError($"Response unsuccess with status code: {response.StatusCode}"); + return new ApiResponse(response, default(KeysResponse)); + } + _logger.LogInformation($"Exited from {nameof(GetKeysAsync)} with response statusCode: {response.StatusCode}"); + return new ApiResponse(response, await LocalMarshalling.DeserializeAsync(response.Content)); + } + + /// + /// Deletes an existing key. + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// The ID of the private key. + /// + /// + /// Describes the updates to the key associated with the service account. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <> + /// + public async System.Threading.Tasks.Task UpdateKeyAsync(string serviceAccountId = default(string), string keyId = default(string), KeyUpdatePayload keyUpdatePayload = default(KeyUpdatePayload), string accessToken = default(string), bool throwOnError = true) + { + _logger.LogInformation($"Entered into {nameof(UpdateKeyAsync)}"); + + using var request = new HttpRequestMessage(); + + var queryParam = new Dictionary(); + request.RequestUri = + Marshalling.BuildRequestUri("/authentication/v2/service-accounts/{serviceAccountId}/keys/{keyId}", + routeParameters: new Dictionary + { + { "serviceAccountId", serviceAccountId}, + { "keyId", keyId }, + }, + queryParameters: queryParam + ); + + request.Headers.TryAddWithoutValidation("Accept", "application/json"); + request.Headers.TryAddWithoutValidation("User-Agent", "APS SDK/SECURE SERVICE ACCOUNT/C#/2.0.0"); + + if (!string.IsNullOrEmpty(accessToken)) + { + request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {accessToken}"); + } + + request.Content = Marshalling.Serialize(keyUpdatePayload); + + request.Method = HttpMethod.Patch; + + // Make the HTTP request. + var response = await Service.Client.SendAsync(request); + + if (throwOnError) + { + try + { + await response.EnsureSuccessStatusCodeAsync(); + } + catch (HttpRequestException ex) + { + throw new SecureServiceAccountApiException(ex.Message, response, ex); + } + } + else if (!response.IsSuccessStatusCode) + { + _logger.LogError($"Response unsuccess with status code: {response.StatusCode}"); + return response; + } + _logger.LogInformation($"Exited from {nameof(UpdateKeyAsync)} with response statusCode: {response.StatusCode}"); + return response; + } +} diff --git a/authentication/secureserviceaccount/source/LocalMarshalling.cs b/authentication/secureserviceaccount/source/LocalMarshalling.cs new file mode 100644 index 00000000..c5410e80 --- /dev/null +++ b/authentication/secureserviceaccount/source/LocalMarshalling.cs @@ -0,0 +1,109 @@ +/* + * APS SDK + * + * Autodesk Platform Services contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. + * + * Authentication.SecureServiceAccount + * + * OAuth2 server-to-server account, key, and token management API. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using Newtonsoft.Json; +using System.Net.Http; +using System.Threading.Tasks; + +namespace Autodesk.Authentication.SecureServiceAccount.Client; + +/// +/// Helpers for marshalling parameters +/// +public partial class LocalMarshalling +{ + private JsonSerializerSettings _serializerSettings = new() + { + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor + }; + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601) + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// Formatted string. + public static string ParameterToString(object obj) + { + if (obj is DateTime) + { + // https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings#Roundtrip + return ((DateTime)obj).ToString("o"); + } + else + { + return Convert.ToString(obj); + } + } + + public static async Task DeserializeAsync(HttpContent content) + { + ArgumentNullException.ThrowIfNull(content); + + // Don't deserialize Stream - this is fix for download scenarios. + if (typeof(T) == typeof(System.IO.Stream)) + { + return await (dynamic)content.ReadAsStreamAsync(); + } + + string mediaType = content.Headers.ContentType?.MediaType; + if (mediaType != "application/json" && mediaType != "text/plain") + { + throw new ArgumentException($"Content-Type must be application/json. '{mediaType}' was specified."); + } + + var str = await content.ReadAsStringAsync(); + return JsonConvert.DeserializeObject(str); + } + + /// + /// Deserialize the JSON string into a proper object. + /// + /// The HTTP response. + /// Object type. + /// Object representation of the JSON string. + public static object Deserialize(HttpContent content, Type type) + { + return JsonConvert.DeserializeObject(content.ReadAsStringAsync().Result, type); + } + + /// + /// Serialize an input (model) into JSON string + /// + /// Object. + /// HttpContent + public static HttpContent Serialize(object obj, string contentType) + { + return new StringContent(JsonConvert.SerializeObject(obj)); + } + + public static string SetPathVariable(string path, string name, object value) + { + return path.Replace($"", value.ToString()); + } + + public static string AddQuery(string localVarPath, string v, string page) + { + throw new NotImplementedException(); + } +} diff --git a/authentication/secureserviceaccount/source/Model/GrantType.gen.cs b/authentication/secureserviceaccount/source/Model/GrantType.gen.cs new file mode 100644 index 00000000..339d6844 --- /dev/null +++ b/authentication/secureserviceaccount/source/Model/GrantType.gen.cs @@ -0,0 +1,50 @@ +/* + * APS SDK + * + * Autodesk Platform Services contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. + * + * Authentication.SecureServiceAccount + * + * OAuth2 server-to-server account, key, and token management API. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace Autodesk.Authentication.SecureServiceAccount.Model; + +/// +/// Specifies the grant type you are requesting the code for. Possible values are: +/// +/// - `urn:ietf:params:oauth:grant-type:jwt-bearer` - For a jwt-bearer access token. +/// +/// +/// +/// Specifies the grant type you are requesting the code for. Possible values are: +/// +/// - `urn:ietf:params:oauth:grant-type:jwt-bearer` - For a jwt-bearer access token. +/// +/// +[JsonConverter(typeof(StringEnumConverter))] +public enum GrantType +{ + /// + /// Enum for value: urn:ietf:params:oauth:grant-type:jwt-bearer + /// + [EnumMember(Value = "urn:ietf:params:oauth:grant-type:jwt-bearer")] + JwtBearer, +} + diff --git a/authentication/secureserviceaccount/source/Model/Key.gen.cs b/authentication/secureserviceaccount/source/Model/Key.gen.cs new file mode 100644 index 00000000..d8cbe9b4 --- /dev/null +++ b/authentication/secureserviceaccount/source/Model/Key.gen.cs @@ -0,0 +1,82 @@ +/* + * APS SDK + * + * Autodesk Platform Services contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. + * + * Authentication.SecureServiceAccount + * + * OAuth2 server-to-server account, key, and token management API. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System.Runtime.Serialization; + +namespace Autodesk.Authentication.SecureServiceAccount.Model; + +/// +/// Represents a key associated with the service account. +/// +[DataContract] +public partial class Key +{ + /// + /// Initializes a new instance of the class. + /// + public Key() + { } + + /// + /// The ID of the private key. + /// + /// + /// The ID of the private key. + /// + [DataMember(Name = "kid", EmitDefaultValue = false)] + public string Kid { get; set; } + + /// + /// The status of the key. Possible values: + /// + /// - `ENABLED` - + /// - `DISABLED` - + /// + /// + /// + /// The status of the key. Possible values: + /// + /// - `ENABLED` - + /// - `DISABLED` - + /// + /// + [DataMember(Name = "status", EmitDefaultValue = true)] + public KeyStatus Status { get; set; } + + /// + /// The creation time of the key, in UTC format. + /// + /// + /// The creation time of the key, in UTC format. + /// + [DataMember(Name = "createdAt", EmitDefaultValue = false)] + public string CreatedAt { get; set; } + + /// + /// This is the most recent time an access token was generated for this service account key, in UTC format. + /// + /// + /// This is the most recent time an access token was generated for this service account key, in UTC format. + /// + [DataMember(Name = "accessedAt", EmitDefaultValue = false)] + public string AccessedAt { get; set; } +} diff --git a/authentication/secureserviceaccount/source/Model/KeyCreated.gen.cs b/authentication/secureserviceaccount/source/Model/KeyCreated.gen.cs new file mode 100644 index 00000000..b43e6c00 --- /dev/null +++ b/authentication/secureserviceaccount/source/Model/KeyCreated.gen.cs @@ -0,0 +1,56 @@ +/* + * APS SDK + * + * Autodesk Platform Services contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. + * + * Authentication.SecureServiceAccount + * + * OAuth2 server-to-server account, key, and token management API. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System.Runtime.Serialization; + +namespace Autodesk.Authentication.SecureServiceAccount.Model; + +/// +/// Represents a private key associated with the secure service account. +/// +[DataContract] +public partial class KeyCreated +{ + /// + /// Initializes a new instance of the class. + /// + public KeyCreated() + { } + + /// + /// The ID of the private key. + /// + /// + /// The ID of the private key. + /// + [DataMember(Name = "kid", EmitDefaultValue = false)] + public string Kid { get; set; } + + /// + /// The private key value, in PEM format. + /// + /// + /// The private key value, in PEM format. + /// + [DataMember(Name = "privateKey", EmitDefaultValue = false)] + public string PrivateKey { get; set; } +} diff --git a/authentication/secureserviceaccount/source/Model/KeyStatus.gen.cs b/authentication/secureserviceaccount/source/Model/KeyStatus.gen.cs new file mode 100644 index 00000000..86f91336 --- /dev/null +++ b/authentication/secureserviceaccount/source/Model/KeyStatus.gen.cs @@ -0,0 +1,57 @@ +/* + * APS SDK + * + * Autodesk Platform Services contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. + * + * Authentication.SecureServiceAccount + * + * OAuth2 server-to-server account, key, and token management API. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace Autodesk.Authentication.SecureServiceAccount.Model; + +/// +/// Specifies the status of the key associated with the service account. Possible values: +/// +/// - `ENABLED` - +/// - `DISABLED` - +/// +/// +/// +/// Specifies the status of the key associated with the service account. Possible values: +/// +/// - `ENABLED` - +/// - `DISABLED` - +/// +/// +[JsonConverter(typeof(StringEnumConverter))] +public enum KeyStatus +{ + /// + /// Enum for value: ENABLED. + /// + [EnumMember(Value = "ENABLED")] + Enabled, + + /// + /// Enum for value: DISABLED. + /// + [EnumMember(Value = "DISABLED")] + Disabled, +} diff --git a/authentication/secureserviceaccount/source/Model/KeyUpdatePayload.gen.cs b/authentication/secureserviceaccount/source/Model/KeyUpdatePayload.gen.cs new file mode 100644 index 00000000..ea7dcf8c --- /dev/null +++ b/authentication/secureserviceaccount/source/Model/KeyUpdatePayload.gen.cs @@ -0,0 +1,67 @@ +/* + * APS SDK + * + * Autodesk Platform Services contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. + * + * Authentication.SecureServiceAccount + * + * OAuth2 server-to-server account, key, and token management API. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using Newtonsoft.Json; +using System.Runtime.Serialization; + +namespace Autodesk.Authentication.SecureServiceAccount.Model; + +/// +/// Describes the updates to the key associated with the service account. +/// +[DataContract] +public partial class KeyUpdatePayload +{ + /// + /// Initializes a new instance of the class. + /// + public KeyUpdatePayload() + { } + + /// + /// Gets or sets the status of the key associated with the service account. Possible values: + /// + /// - `ENABLED` - + /// - `DISABLED` - + /// + /// + /// + /// Gets or sets the status of the key associated with the service account. Possible values: + /// + /// - `ENABLED` - + /// - `DISABLED` - + /// + /// + [DataMember(Name = "status", EmitDefaultValue = true)] + public KeyStatus Status { get; set; } + + /// + /// Returns the string presentation of the object. + /// + /// + /// String presentation of the object. + /// + public override string ToString() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } +} diff --git a/authentication/secureserviceaccount/source/Model/KeysResponse.gen.cs b/authentication/secureserviceaccount/source/Model/KeysResponse.gen.cs new file mode 100644 index 00000000..958d861c --- /dev/null +++ b/authentication/secureserviceaccount/source/Model/KeysResponse.gen.cs @@ -0,0 +1,60 @@ +/* + * APS SDK + * + * Autodesk Platform Services contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. + * + * Authentication.SecureServiceAccount + * + * OAuth2 server-to-server account, key, and token management API. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using Newtonsoft.Json; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace Autodesk.Authentication.SecureServiceAccount.Model; + +/// +/// Represents the response object for a collection of keys associated with the service account. +/// +[DataContract] +public partial class KeysResponse +{ + /// + /// Initializes a new instance of the class. + /// + public KeysResponse() + { } + + /// + /// A collection of keys associated with the service account. + /// + /// + /// A collection of keys associated with the service account. + /// + [DataMember(Name = "keys", EmitDefaultValue = false)] + public List Keys { get; set; } + + /// + /// Returns the string presentation of the object. + /// + /// + /// String presentation of the object. + /// + public override string ToString() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } +} diff --git a/authentication/secureserviceaccount/source/Model/Scopes.gen.cs b/authentication/secureserviceaccount/source/Model/Scopes.gen.cs new file mode 100644 index 00000000..97551d52 --- /dev/null +++ b/authentication/secureserviceaccount/source/Model/Scopes.gen.cs @@ -0,0 +1,166 @@ +/* + * APS SDK + * + * The Forge Platform contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. + * + * Authentication.SecureServiceAccount + * + * OAuth2 server-to-server account, key, and token management API. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace Autodesk.Authentication.SecureServiceAccount.Model; + +/// +/// Specifies the scope for the token you are requesting. +/// See the [Developer's Guide documentation on scopes](/en/docs/oauth/v2/developers_guide/scopes/) for a complete list of possible values. +/// +/// +/// Specifies the scope for the token you are requesting. +/// See the [Developer's Guide documentation on scopes](/en/docs/oauth/v2/developers_guide/scopes/) for a complete list of possible values. +/// +[JsonConverter(typeof(StringEnumConverter))] +public enum Scopes +{ + + /// + /// Enum for value: user:read + /// + [EnumMember(Value = "user:read")] + UserRead, + + /// + /// Enum for value: user:write + /// + [EnumMember(Value = "user:write")] + UserWrite, + + /// + /// Enum for value: user-profile:read + /// + [EnumMember(Value = "user-profile:read")] + UserProfileRead, + + /// + /// Enum for value: viewables:read + /// + [EnumMember(Value = "viewables:read")] + ViewablesRead, + + /// + /// Enum for value: data:read + /// + [EnumMember(Value = "data:read")] + DataRead, + + /// + /// Enum for value: data:read:<URN_OF_RESOURCE> + /// + [EnumMember(Value = "data:read:")] + DataReadURNOFRESOURCE, + + /// + /// Enum for value: data:write + /// + [EnumMember(Value = "data:write")] + DataWrite, + + /// + /// Enum for value: data:create + /// + [EnumMember(Value = "data:create")] + DataCreate, + + /// + /// Enum for value: data:search + /// + [EnumMember(Value = "data:search")] + DataSearch, + + /// + /// Enum for value: bucket:create + /// + [EnumMember(Value = "bucket:create")] + BucketCreate, + + /// + /// Enum for value: bucket:read + /// + [EnumMember(Value = "bucket:read")] + BucketRead, + + /// + /// Enum for value: bucket:update + /// + [EnumMember(Value = "bucket:update")] + BucketUpdate, + + /// + /// Enum for value: bucket:delete + /// + [EnumMember(Value = "bucket:delete")] + BucketDelete, + + /// + /// Enum for value: code:all + /// + [EnumMember(Value = "code:all")] + CodeAll, + + /// + /// Enum for value: account:read + /// + [EnumMember(Value = "account:read")] + AccountRead, + + /// + /// Enum for value: account:write + /// + [EnumMember(Value = "account:write")] + AccountWrite, + + /// + /// Enum for value: openid + /// + [EnumMember(Value = "openid")] + OpenId, + + /// + /// Enum for value: application:service_account:read + /// + [EnumMember(Value = "application:service_account:read")] + ApplicationServiceAccountRead, + + /// + /// Enum for value: application:service_account:write + /// + [EnumMember(Value = "application:service_account:write")] + ApplicationServiceAccountWrite, + + /// + /// Enum for value: application:service_account_key:read + /// + [EnumMember(Value = "application:service_account_key:read")] + ApplicationServiceAccountKeyRead, + + /// + /// Enum for value: application:service_account_key:write + /// + [EnumMember(Value = "application:service_account_key:write")] + ApplicationServiceAccountKeyWrite, +} diff --git a/authentication/secureserviceaccount/source/Model/ServiceAccount.gen.cs b/authentication/secureserviceaccount/source/Model/ServiceAccount.gen.cs new file mode 100644 index 00000000..c952e2f4 --- /dev/null +++ b/authentication/secureserviceaccount/source/Model/ServiceAccount.gen.cs @@ -0,0 +1,121 @@ +/* + * APS SDK + * + * Autodesk Platform Services contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. + * + * Authentication.SecureServiceAccount + * + * OAuth2 server-to-server account, key, and token management API. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using Newtonsoft.Json; +using System.Runtime.Serialization; + +namespace Autodesk.Authentication.SecureServiceAccount.Model; + +/// +/// Represents a service account. +/// +[DataContract] +public partial class ServiceAccount +{ + /// + /// Initializes a new instance of the class. + /// + public ServiceAccount() + { } + + /// + /// The Autodesk ID of the service account. + /// + /// + /// The Autodesk ID of the service account. + /// + [DataMember(Name = "serviceAccountId", EmitDefaultValue = false)] + public string ServiceAccountId { get; set; } + + /// + /// The email address of the service account. + /// + /// + /// The email address of the service account. + /// + [DataMember(Name = "email", EmitDefaultValue = false)] + public string Email { get; set; } + + /// + /// The client ID used to create the service account. + /// + /// + /// The client ID used to create the service account. + /// + [DataMember(Name = "createdBy", EmitDefaultValue = false)] + public string CreatedBy { get; set; } + + /// + /// The status of the service account. Possible values: + /// + /// - `ENABLED` - + /// - `DISABLED` - + /// + /// + /// + /// The status of the service account. Possible values: + /// + /// - `ENABLED` - + /// - `DISABLED` - + /// + /// + [DataMember(Name = "status", EmitDefaultValue = true)] + public ServiceAccountStatus Status { get; set; } + + /// + /// The creation time of the service account, in UTC format. + /// + /// + /// The creation time of the service account, in UTC format. + /// + [DataMember(Name = "createdAt", EmitDefaultValue = false)] + public string CreatedAt { get; set; } + + /// + /// This is the most recent time an access token was generated for this service account, in UTC format. + /// + /// + /// This is the most recent time an access token was generated for this service account, in UTC format. + /// + [DataMember(Name = "accessedAt", EmitDefaultValue = false)] + public string AccessedAt { get; set; } + + /// + /// The expiration time of the service account, in UTC format. + /// + /// + /// The expiration time of the service account, in UTC format. + /// + [DataMember(Name = "expiresAt", EmitDefaultValue = false)] + public string ExpiresAt { get; set; } + + /// + /// Returns the string presentation of the object. + /// + /// + /// String presentation of the object. + /// + public override string ToString() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } +} diff --git a/authentication/secureserviceaccount/source/Model/ServiceAccountCreatePayload.gen.cs b/authentication/secureserviceaccount/source/Model/ServiceAccountCreatePayload.gen.cs new file mode 100644 index 00000000..f1203813 --- /dev/null +++ b/authentication/secureserviceaccount/source/Model/ServiceAccountCreatePayload.gen.cs @@ -0,0 +1,111 @@ +/* + * APS SDK + * + * Autodesk Platform Services contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. + * + * Authentication.SecureServiceAccount + * + * OAuth2 server-to-server account, key, and token management API. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using Newtonsoft.Json; +using System.Runtime.Serialization; + +namespace Autodesk.Authentication.SecureServiceAccount.Model; + +/// +/// Describes the creation of the service account. +/// +[DataContract] +public partial class ServiceAccountCreatePayload +{ + /// + /// Initializes a new instance of the class. + /// + public ServiceAccountCreatePayload() + { } + + /// + /// The name of the service account. + /// Must be 5-100 characters long, contain only alphanumeric characters and dashes, and include at least one alphanumeric character. + /// + /// + /// The name of the service account. + /// Must be 5-100 characters long, contain only alphanumeric characters and dashes, and include at least one alphanumeric character. + /// + [DataMember(Name = "name", EmitDefaultValue = false)] + public string Name { get; set; } + + /// + /// The last name of the service account. For display purposes only. + /// Must meet the following conditions: + /// Length between 5 and 100 characters + /// Contain only alphanumeric characters and dashes + /// Include at least one alphanumeric character + /// Avoid inappropriate words + /// Exclude invalid characters such as the special characters % and /. + /// Avoid the character pattern of &# even though the characters are allowed individually. + /// For more information, see the [Naming Guidelines](/en/docs/ssa/v1/developers_guide/naming-guidelines/) section in the Developer's Guide. + /// + /// + /// The last name of the service account. For display purposes only. + /// Must meet the following conditions: + /// Length between 5 and 100 characters + /// Contain only alphanumeric characters and dashes + /// Include at least one alphanumeric character + /// Avoid inappropriate words + /// Exclude invalid characters such as the special characters % and /. + /// Avoid the character pattern of &# even though the characters are allowed individually. + /// For more information, see the [Naming Guidelines](/en/docs/ssa/v1/developers_guide/naming-guidelines/) section in the Developer's Guide. + /// + [DataMember(Name = "firstName", EmitDefaultValue = false)] + public string FirstName { get; set; } + + /// + /// The last name of the service account. For display purposes only. + /// Must meet the following conditions: + /// Length between 5 and 100 characters + /// Contain only alphanumeric characters and dashes + /// Include at least one alphanumeric character + /// Avoid inappropriate words + /// Exclude invalid characters such as the special characters % and /. + /// Avoid the character pattern of &# even though the characters are allowed individually. + /// For more information, see the [Naming Guidelines](/en/docs/ssa/v1/developers_guide/naming-guidelines/) section in the Developer's Guide. + /// + /// + /// The last name of the service account. For display purposes only. + /// Must meet the following conditions: + /// Length between 5 and 100 characters + /// Contain only alphanumeric characters and dashes + /// Include at least one alphanumeric character + /// Avoid inappropriate words + /// Exclude invalid characters such as the special characters % and /. + /// Avoid the character pattern of &# even though the characters are allowed individually. + /// For more information, see the [Naming Guidelines](/en/docs/ssa/v1/developers_guide/naming-guidelines/) section in the Developer's Guide. + /// + [DataMember(Name = "lastName", EmitDefaultValue = false)] + public string LastName { get; set; } + + /// + /// Returns the string presentation of the object. + /// + /// + /// String presentation of the object. + /// + public override string ToString() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } +} diff --git a/authentication/secureserviceaccount/source/Model/ServiceAccountCreated.gen.cs b/authentication/secureserviceaccount/source/Model/ServiceAccountCreated.gen.cs new file mode 100644 index 00000000..4dc7b0c9 --- /dev/null +++ b/authentication/secureserviceaccount/source/Model/ServiceAccountCreated.gen.cs @@ -0,0 +1,70 @@ +/* + * APS SDK + * + * Autodesk Platform Services contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. + * + * Authentication.SecureServiceAccount + * + * OAuth2 server-to-server account, key, and token management API. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using Newtonsoft.Json; +using System.Runtime.Serialization; + +namespace Autodesk.Authentication.SecureServiceAccount.Model; + +/// +/// Represents a Secure Service Account. +/// +[DataContract] +public partial class ServiceAccountCreated +{ + /// + /// Initializes a new instance of the class. + /// + public ServiceAccountCreated() + { } + + /// + /// The Autodesk ID of the service account. + /// + /// + /// The Autodesk ID of the service account. + /// + [DataMember(Name = "serviceAccountId", EmitDefaultValue = false)] + public string ServiceAccountId { get; set; } + + /// + /// The email address of the service account. + /// It is of the form {serviceAccountName}@{clientId}.adskserviceaccount.autodesk.com. + /// + /// + /// The email address of the service account. + /// It is of the form {serviceAccountName}@{clientId}.adskserviceaccount.autodesk.com. + /// + [DataMember(Name = "email", EmitDefaultValue = false)] + public string Email { get; set; } + + /// + /// Returns the string presentation of the object. + /// + /// + /// String presentation of the object. + /// + public override string ToString() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } +} diff --git a/authentication/secureserviceaccount/source/Model/ServiceAccountStatus.gen.cs b/authentication/secureserviceaccount/source/Model/ServiceAccountStatus.gen.cs new file mode 100644 index 00000000..00b99140 --- /dev/null +++ b/authentication/secureserviceaccount/source/Model/ServiceAccountStatus.gen.cs @@ -0,0 +1,57 @@ +/* + * APS SDK + * + * Autodesk Platform Services contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. + * + * Authentication.SecureServiceAccount + * + * OAuth2 server-to-server account, key, and token management API. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace Autodesk.Authentication.SecureServiceAccount.Model; + +/// +/// Specifies the status of the key associated with the service account. Possible values: +/// +/// - `ENABLED` - +/// - `DISABLED` - +/// +/// +/// +/// Specifies the status of the key associated with the service account. Possible values: +/// +/// - `ENABLED` - +/// - `DISABLED` - +/// +/// +[JsonConverter(typeof(StringEnumConverter))] +public enum ServiceAccountStatus +{ + /// + /// Enum for value: ENABLED. + /// + [EnumMember(Value = "ENABLED")] + Enabled, + + /// + /// Enum for value: DISABLED. + /// + [EnumMember(Value = "DISABLED")] + Disabled, +} diff --git a/authentication/secureserviceaccount/source/Model/ServiceAccountUpdatePayload.gen.cs b/authentication/secureserviceaccount/source/Model/ServiceAccountUpdatePayload.gen.cs new file mode 100644 index 00000000..e7c2aae5 --- /dev/null +++ b/authentication/secureserviceaccount/source/Model/ServiceAccountUpdatePayload.gen.cs @@ -0,0 +1,67 @@ +/* + * APS SDK + * + * Autodesk Platform Services contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. + * + * Authentication.SecureServiceAccount + * + * OAuth2 server-to-server account, key, and token management API. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using Newtonsoft.Json; +using System.Runtime.Serialization; + +namespace Autodesk.Authentication.SecureServiceAccount.Model; + +/// +/// Describes the updates to the service account. +/// +[DataContract] +public partial class ServiceAccountUpdatePayload +{ + /// + /// Initializes a new instance of the class. + /// + public ServiceAccountUpdatePayload() + { } + + /// + /// Gets or sets the status of the service account. Possible values: + /// + /// - `ENABLED` - + /// - `DISABLED` - + /// + /// + /// + /// Gets or sets the status of the service account. Possible values: + /// + /// - `ENABLED` - + /// - `DISABLED` - + /// + /// + [DataMember(Name = "status", EmitDefaultValue = true)] + public ServiceAccountStatus Status { get; set; } + + /// + /// Returns the string presentation of the object. + /// + /// + /// String presentation of the object. + /// + public override string ToString() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } +} diff --git a/authentication/secureserviceaccount/source/Model/ServiceAccountsResponse.gen.cs b/authentication/secureserviceaccount/source/Model/ServiceAccountsResponse.gen.cs new file mode 100644 index 00000000..438e04d2 --- /dev/null +++ b/authentication/secureserviceaccount/source/Model/ServiceAccountsResponse.gen.cs @@ -0,0 +1,60 @@ +/* + * APS SDK + * + * Autodesk Platform Services contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. + * + * Authentication.SecureServiceAccount + * + * OAuth2 server-to-server account, key, and token management API. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using Newtonsoft.Json; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace Autodesk.Authentication.SecureServiceAccount.Model; + +/// +/// Represents the response object for a collection of service accounts. +/// +[DataContract] +public partial class ServiceAccountsResponse +{ + /// + /// Initializes a new instance of the class. + /// + public ServiceAccountsResponse() + { } + + /// + /// A collection of service accounts. + /// + /// + /// A collection of service accounts. + /// + [DataMember(Name = "serviceAccounts", EmitDefaultValue = false)] + public List ServiceAccounts { get; set; } + + /// + /// Returns the string presentation of the object. + /// + /// + /// String presentation of the object. + /// + public override string ToString() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } +} diff --git a/authentication/secureserviceaccount/source/Model/ThreeLeggedToken.gen.cs b/authentication/secureserviceaccount/source/Model/ThreeLeggedToken.gen.cs new file mode 100644 index 00000000..f86a39a1 --- /dev/null +++ b/authentication/secureserviceaccount/source/Model/ThreeLeggedToken.gen.cs @@ -0,0 +1,82 @@ +/* + * APS SDK + * + * Autodesk Platform Services contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. + * + * Authentication.SecureServiceAccount + * + * OAuth2 server-to-server account, key, and token management API. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System.Runtime.Serialization; + +namespace Autodesk.Authentication.SecureServiceAccount.Model; + +/// +/// Represents a service account token. +/// +[DataContract] +public partial class ThreeLeggedToken +{ + /// + /// Initializes a new instance of the class. + /// + public ThreeLeggedToken() + { } + + private int? _expiresIn; + + private long? _expiresAt; + + /// + /// Access token time to expiration (in seconds). + /// + /// + /// Access token time to expiration (in seconds). + /// + [DataMember(Name = "expires_in", EmitDefaultValue = false)] + public int? ExpiresIn + { + get { return _expiresIn; } + set { _expiresIn = value; } + } + + /// + /// Time the access token will expire at, in Unix seconds. + /// + /// + /// Time the access token will expire at, in Unix seconds. + /// + [DataMember(Name = "expires_at", EmitDefaultValue = false)] + public long? ExpiresAt { get { return _expiresAt; } } + + /// + /// The access token. + /// + /// + /// The access token. + /// + [DataMember(Name = "access_token", EmitDefaultValue = false)] + public string AccessToken { get; set; } + + /// + /// Will always be Bearer. + /// + /// + /// Will always be Bearer. + /// + [DataMember(Name = "token_type", EmitDefaultValue = false)] + public string TokenType { get; set; } +} diff --git a/authentication/secureserviceaccount/source/ServiceApiException.cs b/authentication/secureserviceaccount/source/ServiceApiException.cs new file mode 100644 index 00000000..a57bee5a --- /dev/null +++ b/authentication/secureserviceaccount/source/ServiceApiException.cs @@ -0,0 +1,51 @@ +/* + * APS SDK + * + * Autodesk Platform Services contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. + * + * Authentication.SecureServiceAccount + * + * OAuth2 server-to-server account, key, and token management API. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Net.Http; + +namespace Autodesk.Authentication.SecureServiceAccount; + +/// +/// An object that is returned when an API call fails. +/// +public abstract class ServiceApiException : HttpRequestException +{ + public HttpResponseMessage HttpResponseMessage { get; set; } + + public ServiceApiException(string message) : base(message) { } + + public ServiceApiException(string message, HttpResponseMessage httpResponseMessage, Exception exception) : base(message, exception) + { + HttpResponseMessage = httpResponseMessage; + } +} + +/// +/// An object that is returned when an API call to the service fails. +/// +public class SecureServiceAccountApiException : ServiceApiException +{ + public SecureServiceAccountApiException(string message) : base(message) { } + + public SecureServiceAccountApiException(string message, HttpResponseMessage httpResponseMessage, Exception exception) : base(message, httpResponseMessage, exception) { } +} diff --git a/authentication/secureserviceaccount/source/ServiceCollectionExtensions.gen.cs b/authentication/secureserviceaccount/source/ServiceCollectionExtensions.gen.cs new file mode 100644 index 00000000..c29daf7c --- /dev/null +++ b/authentication/secureserviceaccount/source/ServiceCollectionExtensions.gen.cs @@ -0,0 +1,46 @@ +/* + * APS SDK + * + * Autodesk Platform Services contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. + * + * Authentication.SecureServiceAccount + * + * OAuth2 server-to-server account, key, and token management API. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using Autodesk.Authentication.SecureServiceAccount.Http; +using Autodesk.Forge.Core; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace Autodesk.Authentication.SecureServiceAccount; + +public static class ServiceCollectionExtensions +{ + /// + /// Adds and configures it with the given configuration. + /// + /// + /// + /// + public static IHttpClientBuilder AddAuthentication(this IServiceCollection services, IConfiguration configuration) + { + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + + return services.AddForgeService(configuration); + } +} diff --git a/authentication/secureserviceaccount/source/custom-code/SecureServiceAccountClient.cs b/authentication/secureserviceaccount/source/custom-code/SecureServiceAccountClient.cs new file mode 100644 index 00000000..dbe6155f --- /dev/null +++ b/authentication/secureserviceaccount/source/custom-code/SecureServiceAccountClient.cs @@ -0,0 +1,630 @@ +/* + * APS SDK + * + * Autodesk Platform Services contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. + * + * Authentication.SecureServiceAccount + * + * OAuth2 server-to-server account, key, and token management API. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using Autodesk.Authentication.SecureServiceAccount.Http; +using Autodesk.Authentication.SecureServiceAccount.Model; +using Autodesk.Forge.Core; +using Autodesk.SDKManager; +using Microsoft.IdentityModel.JsonWebTokens; +using Microsoft.IdentityModel.Tokens; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Runtime.Serialization; +using System.Security.Claims; +using System.Security.Cryptography; + +namespace Autodesk.Authentication.SecureServiceAccount; + +/// +/// Represents a collection of functions to interact with the API endpoints +/// +public class SecureServiceAccountClient : BaseClient +{ + /// + /// Gets the service account management API instance. + /// + public IAccountManagementApi AccountManagementApi { get; } + + /// + /// Gets the key management API instance. + /// + public IKeyManagementApi KeyManagementApi { get; } + + /// + /// Gets the exchange token API instance. + /// + public IExchangeTokenApi ExchangeTokenApi { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + /// The SDK manager instance. + /// + /// + /// The authentication provider instance. + /// + public SecureServiceAccountClient(SDKManager.SDKManager sdkManager = default, IAuthenticationProvider authenticationProvider = default) + : base(authenticationProvider) + { + sdkManager ??= SdkManagerBuilder.Create().Build(); + + AccountManagementApi = new AccountManagementApi(sdkManager); + KeyManagementApi = new KeyManagementApi(sdkManager); + ExchangeTokenApi = new ExchangeTokenApi(sdkManager); + } + + #region AccountManagementApi + + /// + /// Creates a service account. + /// Only a server-to-server application can own service accounts. + /// An application can have up to 10 service accounts at any given time. + /// Upon a successful response, the operation returns the service account ID and email address. + /// + /// + /// Required OAuth Scopes: + /// + /// + /// Describes the creation of the service account. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <<>> + /// + public async System.Threading.Tasks.Task CreateServiceAccountAsync(ServiceAccountCreatePayload serviceAccountCreatePayload = default(ServiceAccountCreatePayload), string accessToken = default(string), bool throwOnError = true) + { + if (string.IsNullOrEmpty(accessToken) && AuthenticationProvider == null) + { + throw new Exception("Please provide a valid access token or an authentication provider."); + } + else if (string.IsNullOrEmpty(accessToken)) + { + accessToken = await AuthenticationProvider.GetAccessToken(); + } + + var response = await AccountManagementApi.CreateServiceAccountAsync(serviceAccountCreatePayload: serviceAccountCreatePayload, accessToken: accessToken, throwOnError: throwOnError); + return response.Content; + } + + /// + /// Deletes an existing service account. + /// When a service account is deleted, all associated keys will also be deleted. + /// + /// + /// Required OAuth Scopes: + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <> + /// + public async System.Threading.Tasks.Task DeleteServiceAccountAsync(string serviceAccountId = default(string), string accessToken = default(string), bool throwOnError = true) + { + if (string.IsNullOrEmpty(accessToken) && AuthenticationProvider == null) + { + throw new Exception("Please provide a valid access token or an authentication provider."); + } + else if (string.IsNullOrEmpty(accessToken)) + { + accessToken = await AuthenticationProvider.GetAccessToken(); + } + + var response = await AccountManagementApi.DeleteServiceAccountAsync(serviceAccountId: serviceAccountId, accessToken: accessToken, throwOnError: throwOnError); + return response; + } + + /// + /// Retrieves the details for a service account. + /// + /// + /// Required OAuth Scopes: + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <<>> + /// + public async System.Threading.Tasks.Task GetServiceAccountAsync(string serviceAccountId = default(string), string accessToken = default(string), bool throwOnError = true) + { + if (string.IsNullOrEmpty(accessToken) && AuthenticationProvider == null) + { + throw new Exception("Please provide a valid access token or an authentication provider."); + } + else if (string.IsNullOrEmpty(accessToken)) + { + accessToken = await AuthenticationProvider.GetAccessToken(); + } + + var response = await AccountManagementApi.GetServiceAccountAsync(serviceAccountId: serviceAccountId, accessToken: accessToken, throwOnError: throwOnError); + return response.Content; + } + + /// + /// Retrieves all service accounts associated with an application. + /// + /// + /// Required OAuth Scopes: + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <<>> + /// + public async System.Threading.Tasks.Task GetServiceAccountsAsync(string accessToken = default(string), bool throwOnError = true) + { + if (string.IsNullOrEmpty(accessToken) && AuthenticationProvider == null) + { + throw new Exception("Please provide a valid access token or an authentication provider."); + } + else if (string.IsNullOrEmpty(accessToken)) + { + accessToken = await AuthenticationProvider.GetAccessToken(); + } + + var response = await AccountManagementApi.GetServiceAccountsAsync(accessToken: accessToken, throwOnError: throwOnError); + return response.Content; + } + + /// + /// Enables or disables a service account. + /// When a service account is in the disabled state, it loses its capability to manage its service account key. + /// Assertions signed by the key will be treated as invalid. + /// This operation allows enabling a service account that is in a diabled state. + /// + /// + /// Required OAuth Scopes: + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// Describes the updates to the service account. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// Thrown when fails to make API call. + /// + /// + /// <> + /// + public async System.Threading.Tasks.Task UpdateServiceAccountAsync(string serviceAccountId = default(string), ServiceAccountUpdatePayload serviceAccountUpdatePayload = default(ServiceAccountUpdatePayload), string accessToken = default(string), bool throwOnError = true) + { + if (string.IsNullOrEmpty(accessToken) && AuthenticationProvider == null) + { + throw new Exception("Please provide a valid access token or an authentication provider."); + } + else if (string.IsNullOrEmpty(accessToken)) + { + accessToken = await AuthenticationProvider.GetAccessToken(); + } + + var response = await AccountManagementApi.UpdateServiceAccountAsync(serviceAccountId: serviceAccountId, serviceAccountUpdatePayload: serviceAccountUpdatePayload, accessToken: accessToken, throwOnError: throwOnError); + return response; + } + + #endregion AccountManagementApi + + #region KeyManagementApi + + /// + /// Creates a service account key. + /// A service account key is a public-private key pair, generated using RSA with a key length of 2048 bits by the Identity Authorization Service(AuthZ). + /// The private key is returned once during its creation.AuthZ only stores the public key. + /// A service account can have up to 3 keys at any given time. + /// + /// + /// Required OAuth Scopes: + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// <> + /// + public async System.Threading.Tasks.Task CreateKeyAsync(string serviceAccountId = default(string), string accessToken = default(string), bool throwOnError = true) + { + if (string.IsNullOrEmpty(accessToken) && AuthenticationProvider == null) + { + throw new Exception("Please provide a valid access token or an authentication provider."); + } + else if (string.IsNullOrEmpty(accessToken)) + { + accessToken = await AuthenticationProvider.GetAccessToken(); + } + + var response = await KeyManagementApi.CreateKeyAsync(serviceAccountId: serviceAccountId, accessToken: accessToken, throwOnError: throwOnError); + return response.Content; + } + + /// + /// Deletes an existing key. + /// + /// + /// Required OAuth Scopes: + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// The ID of the private key. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// <> + /// + public async System.Threading.Tasks.Task DeleteKeyAsync(string serviceAccountId = default(string), string keyId = default(string), string accessToken = default(string), bool throwOnError = true) + { + if (string.IsNullOrEmpty(accessToken) && AuthenticationProvider == null) + { + throw new Exception("Please provide a valid access token or an authentication provider."); + } + else if (string.IsNullOrEmpty(accessToken)) + { + accessToken = await AuthenticationProvider.GetAccessToken(); + } + + var response = await KeyManagementApi.DeleteKeyAsync(serviceAccountId: serviceAccountId, keyId: keyId, accessToken: accessToken, throwOnError: throwOnError); + return response; + } + + /// + /// Lists all keys associated with the service account. + /// This operation will only return key metadata, not the private or public key. + /// + /// + /// Required OAuth Scopes: + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// <> + /// + public async System.Threading.Tasks.Task GetKeysAsync(string serviceAccountId = default(string), string accessToken = default(string), bool throwOnError = true) + { + if (string.IsNullOrEmpty(accessToken) && AuthenticationProvider == null) + { + throw new Exception("Please provide a valid access token or an authentication provider."); + } + else if (string.IsNullOrEmpty(accessToken)) + { + accessToken = await AuthenticationProvider.GetAccessToken(); + } + + var response = await KeyManagementApi.GetKeysAsync(serviceAccountId: serviceAccountId, accessToken: accessToken, throwOnError: throwOnError); + return response.Content; + } + + /// + /// Enables or disables a service account key. + /// + /// + /// Required OAuth Scopes: + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// The ID of the private key. + /// + /// + /// Describes the updates to the key. + /// + /// + /// An access token obtained by a call to GetTwoLeggedTokenAsync(). + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// <> + /// + public async System.Threading.Tasks.Task UpdateKeyAsync(string serviceAccountId = default(string), string keyId = default(string), KeyUpdatePayload keyUpdatePayload = default(KeyUpdatePayload), string accessToken = default(string), bool throwOnError = true) + { + if (string.IsNullOrEmpty(accessToken) && AuthenticationProvider == null) + { + throw new Exception("Please provide a valid access token or an authentication provider."); + } + else if (string.IsNullOrEmpty(accessToken)) + { + accessToken = await AuthenticationProvider.GetAccessToken(); + } + + var response = await KeyManagementApi.UpdateKeyAsync(serviceAccountId: serviceAccountId, keyId: keyId, keyUpdatePayload: keyUpdatePayload, accessToken: accessToken, throwOnError: throwOnError); + return response; + } + + #endregion KeyManagementApi + + #region ExchangeTokenApi + + /// + /// Returns a three-legged access token for the JWT assertion you provide in the request body. + /// See the Developer’s Guide topic JWT Assertions for information on how to generate a JWT assertion for this operation. + /// This operation is only for confidential clients. + /// It requires Basic Authorization (client_id, client_secret). + /// Authentication information (client_id, client_secret) can be included either in the header or the body, but not both simultaneously. + /// + /// + /// Required OAuth Scopes: None + /// + /// + /// Must be `Basic <BASE64_ENCODED_STRING>` where `<BASE64_ENCODED_STRING>` is the Base64 encoding of the concatenated string `<CLIENT_ID>:<CLIENT_SECRET>`. + /// This parameter is required only if client_id and client_secret are not provided in the request body. + /// (optional) + /// + /// + /// Must be `urn:ietf:params:oauth:grant-type:jwt-bearer`. + /// + /// + /// The value of the JWT assertion to exchange for a three-legged access-token. See JWT Assertions for instructions on how to generate a JWT assertion. + /// + /// + /// An additional option where the client can either use the authorization header or opt to send this information in the body. + /// (optional) + /// + /// + /// An additional option where the client can either use the authorization header or opt to send this information in the body. + /// (optional) + /// + /// + /// A URL-encoded space-delimited list of scopes. + /// The scope in the token endpoint request body should be a subset of or the same as the scope specified in the assertion. + /// If the scope is not present, then the returned access token will have the same scope as the assertion. + /// (optional) + /// + /// + /// Indicates whether to throw an exception on error. + /// (optional) + /// + /// + /// <> + /// + public async System.Threading.Tasks.Task ExchangeJwtAssertionAsync(string authorization = default(string), GrantType? grantType = null, string assertion = default(string), string clientId = default(string), string clientSecret = default(string), List scopes = null, bool throwOnError = true) + { + var response = await ExchangeTokenApi.ExchangeJwtAssertionAsync(authorization: authorization, grantType: grantType, assertion: assertion, clientId: clientId, clientSecret: clientSecret, scopes: scopes, throwOnError: throwOnError); + return response.Content; + } + + /// + /// Generates a JWT assertion which is a security token used to make verifiable claims about a subject. + /// It is cryptographically signed to ensure authenticity and integrity. + /// + /// + /// The Client ID of the calling application, as registered with APS. + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// The RSA private key in PEM format (unencrypted PKCS#1 or PKCS#8). + /// + /// + /// The ID of the private key. + /// + /// + /// A list of requested scopes. + /// See the [Developer's Guide documentation on scopes](/en/docs/oauth/v2/developers_guide/scopes/) for a list of valid values you can provide. + /// + /// + /// The token lifetime in seconds. Must be between 0 and 300 seconds (5 minutes). + /// + /// + /// Thrown when required parameters are missing or empty. + /// + /// + /// Thrown when is outside the allowed range of 0 to 300 seconds (5 minutes). + /// + /// + /// + /// + public string GenerateJwtAssertion( + string clientId, + string serviceAccountId, + string privateKey, + string keyId, + List scopes, + long lifetimeSeconds = 300) + { + if (string.IsNullOrWhiteSpace(clientId)) + throw new ArgumentException($"{nameof(clientId)} is required.", nameof(clientId)); + if (string.IsNullOrWhiteSpace(serviceAccountId)) + throw new ArgumentException($"{nameof(serviceAccountId)} is required.", nameof(serviceAccountId)); + if (string.IsNullOrWhiteSpace(privateKey)) + throw new ArgumentException($"{nameof(privateKey)} is required.", nameof(privateKey)); + if (string.IsNullOrWhiteSpace(keyId)) + throw new ArgumentException($"{nameof(keyId)} is required.", nameof(keyId)); + if (lifetimeSeconds < 0 || lifetimeSeconds > 300) + throw new ArgumentOutOfRangeException(nameof(lifetimeSeconds), $"{nameof(lifetimeSeconds)} must be 0 to 300 seconds (5 minutes)."); + + using var rsa = RSA.Create(); + rsa.ImportFromPem(privateKey.ToCharArray()); + + RsaSecurityKey rsaKey = new(rsa) + { + KeyId = keyId, + }; + + List claims = + [ + new(JwtRegisteredClaimNames.Sub, serviceAccountId), + new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")), + ]; + + foreach (var scope in scopes) + { + var memberInfo = typeof(Scopes).GetMember(scope.ToString()).FirstOrDefault(); + var attribute = Attribute.GetCustomAttributes(memberInfo, typeof(EnumMemberAttribute)).FirstOrDefault(); + claims.Add(new("scope", ((EnumMemberAttribute)attribute)?.Value)); + } + + var currentTime = DateTime.UtcNow; + var expirationTime = currentTime.AddSeconds(lifetimeSeconds); + + SecurityTokenDescriptor securityTokenDescriptor = new() + { + Issuer = clientId, + Audience = "https://developer.api.autodesk.com/authentication/v2/token", + Subject = new ClaimsIdentity(claims), + IssuedAt = currentTime, + NotBefore = currentTime, + Expires = expirationTime, + SigningCredentials = new SigningCredentials(rsaKey, SecurityAlgorithms.RsaSha256) + }; + + return new JsonWebTokenHandler().CreateToken(securityTokenDescriptor); + } + + /// + /// Generates a JWT assertion which is a security token used to make verifiable claims about a subject. + /// It is cryptographically signed to ensure authenticity and integrity. + /// + /// + /// The Client ID of the calling application, as registered with APS. + /// + /// + /// The Autodesk ID of the service account. + /// + /// + /// The stream of the RSA private key in PEM format (unencrypted PKCS#1 or PKCS#8). + /// + /// + /// The ID of the private key. + /// + /// + /// A list of requested scopes. + /// See the [Developer's Guide documentation on scopes](/en/docs/oauth/v2/developers_guide/scopes/) for a list of valid values you can provide. + /// + /// + /// The token lifetime in seconds. Must be between 0 and 300 seconds (5 minutes). + /// + /// + /// Thrown when required parameters are missing or empty. + /// + /// + /// Thrown when is outside the allowed range of 0 to 300 seconds (5 minutes). + /// + /// + /// + /// + public string GenerateJwtAssertion( + string clientId, + string serviceAccountId, + Stream privateKey, + string keyId, + List scopes, + int lifetimeSeconds = 300) + { + if (privateKey is null || !privateKey.CanRead) + throw new ArgumentException($"{nameof(privateKey)} must be a readable stream.", nameof(privateKey)); + + if (privateKey.CanSeek && privateKey.Position != 0) + privateKey.Seek(0, SeekOrigin.Begin); + + using StreamReader streamReader = new(privateKey, leaveOpen: true); + string privateKeyPem = streamReader.ReadToEnd(); + + return GenerateJwtAssertion(clientId, serviceAccountId, privateKeyPem, keyId, scopes, lifetimeSeconds); + } + + #endregion ExchangeTokenApi + +} \ No newline at end of file diff --git a/authentication/secureserviceaccount/test/Autodesk.Authentication.SecureServiceAccount.Test.csproj b/authentication/secureserviceaccount/test/Autodesk.Authentication.SecureServiceAccount.Test.csproj new file mode 100644 index 00000000..dee4972d --- /dev/null +++ b/authentication/secureserviceaccount/test/Autodesk.Authentication.SecureServiceAccount.Test.csproj @@ -0,0 +1,20 @@ + + + enable + enable + Autodesk.Authentication.Test + false + + + + + + + + + + + + + + diff --git a/authentication/secureserviceaccount/test/TestSecureServiceAccount.cs b/authentication/secureserviceaccount/test/TestSecureServiceAccount.cs new file mode 100644 index 00000000..a6c1b359 --- /dev/null +++ b/authentication/secureserviceaccount/test/TestSecureServiceAccount.cs @@ -0,0 +1,175 @@ +using Autodesk.Authentication.SecureServiceAccount.Model; +using Autodesk.SDKManager; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Net; +using System.Text; + +namespace Autodesk.Authentication.SecureServiceAccount.Test; + +[TestClass] +public class TestSecureServiceAccount +{ + private static SecureServiceAccountClient _secureServiceAccountClient = null!; + + private readonly string? _clientId = Environment.GetEnvironmentVariable("clientId"); + private readonly string? _clientSecret = Environment.GetEnvironmentVariable("clientSecret"); + private readonly string? _twoLeggedToken = Environment.GetEnvironmentVariable("twoLeggedToken"); + + private readonly string? _serviceAccountName = Environment.GetEnvironmentVariable("serviceAccountName"); + private readonly string? _serviceAccountFirstName = Environment.GetEnvironmentVariable("serviceAccountFirstName"); + private readonly string? _serviceAccountLastName = Environment.GetEnvironmentVariable("serviceAccountLastName"); + private readonly string? _serviceAccountId = Environment.GetEnvironmentVariable("serviceAccountId"); + + private readonly string? _pathToPrivateKeyFile = Environment.GetEnvironmentVariable("pathToPrivateKeyFile"); + private readonly string? _keyId = Environment.GetEnvironmentVariable("keyId"); + + [ClassInitialize] + public static void ClassInitialize(TestContext testContext) + { + SDKManager.SDKManager sdkManager = SdkManagerBuilder + .Create() + .Add(new ApsConfiguration()) + .Add(ResiliencyConfiguration.CreateDefault()) + .Build(); + + _secureServiceAccountClient = new SecureServiceAccountClient(sdkManager); + } + + #region AccountManagementApi + + [TestMethod] + public async Task TestCreateServiceAccountAsync() + { + ServiceAccountCreatePayload serviceAccountCreatePayload = new() + { + Name = _serviceAccountName, + FirstName = _serviceAccountFirstName, + LastName = _serviceAccountLastName, + }; + + ServiceAccountCreated serviceAccount = await _secureServiceAccountClient.CreateServiceAccountAsync( + serviceAccountCreatePayload: serviceAccountCreatePayload, + accessToken: _twoLeggedToken); + Assert.IsNotNull(serviceAccount); + } + + [TestMethod] + public async Task TestDeleteServiceAccountAsync() + { + HttpResponseMessage httpResponseMessage = await _secureServiceAccountClient.DeleteServiceAccountAsync( + serviceAccountId: _serviceAccountId, + accessToken: _twoLeggedToken); + Assert.IsTrue(httpResponseMessage.StatusCode == HttpStatusCode.NoContent); + } + + [TestMethod] + public async Task TestGetServiceAccountAsync() + { + ServiceAccount serviceAccount = await _secureServiceAccountClient.GetServiceAccountAsync( + serviceAccountId: _serviceAccountId, + accessToken: _twoLeggedToken); + Assert.IsNotNull(serviceAccount); + } + + [TestMethod] + public async Task TestGetServiceAccountsAsync() + { + ServiceAccountsResponse serviceAccounts = await _secureServiceAccountClient.GetServiceAccountsAsync( + accessToken: _twoLeggedToken); + Assert.IsInstanceOfType(serviceAccounts); + } + + [TestMethod] + public async Task TestUpdateServiceAccountAsync() + { + ServiceAccountUpdatePayload serviceAccountUpdatePayload = new() + { + Status = ServiceAccountStatus.Enabled, + }; + + HttpResponseMessage httpResponseMessage = await _secureServiceAccountClient.UpdateServiceAccountAsync( + serviceAccountId: _serviceAccountId, + serviceAccountUpdatePayload: serviceAccountUpdatePayload, + accessToken: _twoLeggedToken); + Assert.IsTrue(httpResponseMessage.StatusCode == HttpStatusCode.OK); + } + + #endregion AccountManagementApi + + #region KeyManagementApi + + [TestMethod] + public async Task TestCreateKeyAsync() + { + KeyCreated key = await _secureServiceAccountClient.CreateKeyAsync( + serviceAccountId: _serviceAccountId, + accessToken: _twoLeggedToken); + Assert.IsNotNull(key); + } + + [TestMethod] + public async Task TestDeleteKeyAsync() + { + HttpResponseMessage httpResponseMessage = await _secureServiceAccountClient.DeleteKeyAsync( + serviceAccountId: _serviceAccountId, + keyId: _keyId, + accessToken: _twoLeggedToken); + Assert.IsTrue(httpResponseMessage.StatusCode == HttpStatusCode.NoContent); + } + + [TestMethod] + public async Task TestGetKeysAsync() + { + KeysResponse keys = await _secureServiceAccountClient.GetKeysAsync( + serviceAccountId: _serviceAccountId, + accessToken: _twoLeggedToken); + Assert.IsInstanceOfType(keys); + } + + [TestMethod] + public async Task TestUpdateKeyAsync() + { + KeyUpdatePayload keyUpdatePayload = new() + { + Status = KeyStatus.Enabled, + }; + + HttpResponseMessage httpResponseMessage = await _secureServiceAccountClient.UpdateKeyAsync( + serviceAccountId: _serviceAccountId, + keyId: _keyId, + keyUpdatePayload: keyUpdatePayload, + accessToken: _twoLeggedToken); + Assert.IsTrue(httpResponseMessage.StatusCode == HttpStatusCode.NoContent); + } + + #endregion KeyManagementApi + + #region ExchangeTokenApi + + [TestMethod] + public async Task TestExchangeJwtAssertion() + { + string authorization = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{_clientId}:{_clientSecret}")); + List scopes = [Scopes.DataCreate, Scopes.DataRead, Scopes.DataWrite]; + + using var fileStream = File.OpenRead(_pathToPrivateKeyFile); + string assertion = _secureServiceAccountClient.GenerateJwtAssertion( + clientId: _clientId, + serviceAccountId: _serviceAccountId, + privateKey: fileStream, + keyId: _keyId, + scopes: scopes); + + ThreeLeggedToken threeLeggedToken = await _secureServiceAccountClient.ExchangeJwtAssertionAsync( + authorization: authorization, + grantType: GrantType.JwtBearer, + assertion: assertion, + clientId: _clientId, + clientSecret: _clientSecret, + scopes: scopes); + Assert.IsNotNull(threeLeggedToken); + } + + #endregion ExchangeTokenApi + +} \ No newline at end of file From 1b2e2abe6e8a36f1e67999f83804d49837f847c7 Mon Sep 17 00:00:00 2001 From: Tyler Warner Date: Thu, 30 Oct 2025 05:20:08 -0500 Subject: [PATCH 2/2] Correct 'RootNamespace' in test project file --- .../Autodesk.Authentication.SecureServiceAccount.Test.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/authentication/secureserviceaccount/test/Autodesk.Authentication.SecureServiceAccount.Test.csproj b/authentication/secureserviceaccount/test/Autodesk.Authentication.SecureServiceAccount.Test.csproj index dee4972d..cf0ae003 100644 --- a/authentication/secureserviceaccount/test/Autodesk.Authentication.SecureServiceAccount.Test.csproj +++ b/authentication/secureserviceaccount/test/Autodesk.Authentication.SecureServiceAccount.Test.csproj @@ -2,7 +2,7 @@ enable enable - Autodesk.Authentication.Test + Autodesk.Authentication.SecureServiceAccount.Test false