diff --git a/authentication/source/Http/TokenApi.gen.cs b/authentication/source/Http/TokenApi.gen.cs index bcb7fa1..b52aeaf 100644 --- a/authentication/source/Http/TokenApi.gen.cs +++ b/authentication/source/Http/TokenApi.gen.cs @@ -31,6 +31,7 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Autodesk.SDKManager; +using System.Collections; namespace Autodesk.Authentication.Http { @@ -74,7 +75,7 @@ public interface ITokenApi /// ///The string can only contain alphanumeric characters, commas, periods, underscores, and hyphens. (optional) /// - /// + /// ///A URL-encoded space-delimited 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 string you specify for this parameter must not exceed 2000 characters and it cannot contain more than 50 scopes. (optional) @@ -106,8 +107,9 @@ public interface ITokenApi /// ///- `S256`- Hashes the code verifier using the SHA-256 algorithm and then applies Base64 URL encoding. (optional) /// + /// string - string Authorize(string clientId, string responseType, string redirectUri, string state = default(string), string nonce = default(string), string scope = null, string responseMode = default(string), string prompt = default(string), string authoptions = default(string), string codeChallenge = default(string), string codeChallengeMethod = default(string) /*string accessToken = null, bool throwOnError = true*/); + string Authorize(string clientId, ResponseType responseType, string redirectUri, string nonce = default(string), string state = default(string), List scopes = null, string responseMode = default(string), string prompt = default(string), string authoptions = default(string), string codeChallenge = default(string), string codeChallengeMethod = default(string)/*, string accessToken = null , bool throwOnError = true */ ); /// /// Acquire Token /// @@ -143,15 +145,15 @@ public interface ITokenApi /// ///The refresh token used to acquire a new access token and a refresh token. Required if `grant_type` is `refresh_token`. (optional) /// - /// - /// (optional) + /// + /// A URL-encoded space-delimited 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. (optional) /// /// - /// (optional) - /// - /// Task ofHttpResponseMessage + ///The Client ID of the application making the request. **Note** This is required only for Traditional Web Apps and Server-to-Server Apps. It is not required for Desktop, Mobile, and Single-Page Apps. (optional) + /// + /// Task of HttpResponseMessage - System.Threading.Tasks.Task FetchTokenAsync(string authorization = default(string), string grantType = default, string code = default(string), string redirectUri = default(string), string codeVerifier = default(string), string refreshToken = default(string), string scope = null, string clientId = default(string),/* string accessToken = null,*/ bool throwOnError = true); + System.Threading.Tasks.Task FetchTokenAsync(string authorization = default(string), GrantType? grantType = null, string code = default(string), string redirectUri = default(string), string codeVerifier = default(string), string refreshToken = default(string), List scopes = null, string clientId = default(string),/* string accessToken = null , */ bool throwOnError = true); /// /// Get JWKS /// @@ -163,10 +165,9 @@ public interface ITokenApi ///See the Developer's Guide topic on [Asymmetric Signing](/en/docs/oauth/v2/developers_guide/asymmetric-encryption/) for more information. /// /// Thrown when fails to make API call - /// Task of ApiResponse<Jwks> - System.Threading.Tasks.Task> GetKeysAsync(/*string accessToken = null*/ bool throwOnError = true); + System.Threading.Tasks.Task> GetKeysAsync(/* string accessToken = null , */ bool throwOnError = true); /// /// Get OIDC Specification /// @@ -174,10 +175,9 @@ public interface ITokenApi ///Returns an OpenID Connect Discovery Specification compliant JSON document. It contains a list of the OpenID/OAuth endpoints, supported scopes, claims, public keys used to sign the tokens, and other details. /// /// Thrown when fails to make API call - /// Task of ApiResponse<OidcSpec> - System.Threading.Tasks.Task> GetOidcSpecAsync(/*string accessToken = null,*/ bool throwOnError = true); + System.Threading.Tasks.Task> GetOidcSpecAsync(/* string accessToken = null , */ bool throwOnError = true); /// /// Introspect Token /// @@ -198,7 +198,7 @@ public interface ITokenApi ///The token to be introspected. (optional) /// /// - /// (optional) + ///The Client ID of the application making the request. **Note** This is required only for Traditional Web Apps and Server-to-Server Apps. It is not required for Desktop, Mobile, and Single-Page Apps. (optional) /// /// Task of ApiResponse<IntrospectToken> @@ -243,11 +243,11 @@ public interface ITokenApi ///**Note** This header is required only for Traditional Web Apps and Server-to-Server Apps. It is not required for Desktop, Mobile, and Single-Page Apps. (optional) /// /// - /// (optional) + ///The Client ID of the application making the request. **Note** This is required only for Traditional Web Apps and Server-to-Server Apps. It is not required for Desktop, Mobile, and Single-Page Apps. (optional) /// /// Task of HttpResponseMessage - System.Threading.Tasks.Task RevokeAsync(string token, string authorization = default(string), string tokenTypeHint = default(string), string clientId = default(string), bool throwOnError = true); + System.Threading.Tasks.Task RevokeAsync(string token, TokenTypeHint tokenTypeHint, string authorization = default(string), string clientId = default(string)/* , string accessToken = null */, bool throwOnError = true); } /// @@ -288,6 +288,26 @@ private void SetQueryParameter(string name, object value, Dictionary) + { + dictionary.Add(name, String.Join(" ", (List)value)); + } + else + { + List concatenatedList = new List(); + 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) @@ -332,7 +352,7 @@ private void SetHeader(string baseName, object value, HttpRequestMessage req) /// Authorize User /// /// - ///Displays a sign-in page where users of your application can authorize the application to access resources on their behalf. + ///Returns a browser URL to redirect an end user in order to acquire the user’s consent to authorize the application to access resources on their behalf. /// ///Invoking this operation is the first step in authenticating users and retrieving an authorization code grant. The authorization code that is generated remains valid for 5 minutes, while the ID token stays valid for 60 minutes. Any access tokens you obtain are valid for 60 minutes, and refresh tokens remain valid for 15 days. /// @@ -396,7 +416,7 @@ private void SetHeader(string baseName, object value, HttpRequestMessage req) ///- `S256`- Hashes the code verifier using the SHA-256 algorithm and then applies Base64 URL encoding. (optional) /// /// string - public string Authorize(string clientId, string responseType, string redirectUri, string state = default(string), string nonce = default(string), string scope = null, string responseMode = default(string), string prompt = default(string), string authoptions = default(string), string codeChallenge = default(string), string codeChallengeMethod = default(string) /*string accessToken = null, bool throwOnError = true*/) + public string Authorize(string clientId, ResponseType responseType, string redirectUri, string nonce = default(string), string state = default(string), List scopes = null, string responseMode = default(string), string prompt = default(string), string authoptions = default(string), string codeChallenge = default(string), string codeChallengeMethod = default(string)/* , string accessToken = null , bool throwOnError = true */) { logger.LogInformation("Entered into AuthorizeAsync "); // ss manually added. This method does not call any rest endpoints. @@ -404,11 +424,11 @@ private void SetHeader(string baseName, object value, HttpRequestMessage req) { var queryParam = new Dictionary(); if (!string.IsNullOrEmpty(clientId)) { SetQueryParameter("client_id", clientId, queryParam); } - if (!string.IsNullOrEmpty(responseType)) { SetQueryParameter("response_type", responseType, queryParam); } + SetQueryParameter("response_type", responseType, queryParam); if (!string.IsNullOrEmpty(redirectUri)) { SetQueryParameter("redirect_uri", redirectUri, queryParam); } if (!string.IsNullOrEmpty(nonce)) { SetQueryParameter("nonce", nonce, queryParam); } if (!string.IsNullOrEmpty(state)) { SetQueryParameter("state", state, queryParam); } - if (!string.IsNullOrEmpty(scope)) { SetQueryParameter("scope", scope, queryParam); } + SetQueryParameter("scope", scopes, queryParam); if (!string.IsNullOrEmpty(responseMode)) { SetQueryParameter("response_mode", responseMode, queryParam); } if (!string.IsNullOrEmpty(prompt)) { SetQueryParameter("prompt", prompt, queryParam); } if (!string.IsNullOrEmpty(authoptions)) { SetQueryParameter("authoptions", authoptions, queryParam); } @@ -462,15 +482,15 @@ private void SetHeader(string baseName, object value, HttpRequestMessage req) /// ///The refresh token used to acquire a new access token and a refresh token. Required if `grant_type` is `refresh_token`. (optional) /// - /// - /// (optional) + /// + /// A URL-encoded space-delimited 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.(optional) /// /// - /// (optional) + ///The Client ID of the application making the request. **Note** This is required only for Traditional Web Apps and Server-to-Server Apps. It is not required for Desktop, Mobile, and Single-Page Apps. (optional) /// - /// Task of HttpResponseMessage + /// Task of HttpResponseMessage;> - public async System.Threading.Tasks.Task FetchTokenAsync(string authorization = default(string), string grantType = default, string code = default(string), string redirectUri = default(string), string codeVerifier = default(string), string refreshToken = default(string), string scope = null, string clientId = default(string),/* string accessToken = null,*/ bool throwOnError = true) + public async System.Threading.Tasks.Task FetchTokenAsync(string authorization = default(string), GrantType? grantType = null, string code = default(string), string redirectUri = default(string), string codeVerifier = default(string), string refreshToken = default(string), List scopes = null, string clientId = default(string), /* string accessToken = null, */ bool throwOnError = true) { logger.LogInformation("Entered into FetchTokenAsync "); using (var request = new HttpRequestMessage()) @@ -487,31 +507,24 @@ private void SetHeader(string baseName, object value, HttpRequestMessage req) request.Headers.TryAddWithoutValidation("Accept", "application/json"); request.Headers.TryAddWithoutValidation("User-Agent", "APS SDK/AUTHENTICATION/C#/1.0.0-beta1"); - // *** ss manually added*** + if (!string.IsNullOrEmpty(authorization)) { request.Headers.TryAddWithoutValidation("Authorization", $"Basic {authorization}"); } - // if(!string.IsNullOrEmpty(accessToken)) - // { - // request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {accessToken}"); - // } - var formParams = new Dictionary(); - if (!string.IsNullOrEmpty(grantType)) { formParams.Add("grant_type", grantType); } + var formParams = new Dictionary(); + // convert grantType enum to string + SetQueryParameter("grant_type", grantType, formParams); if (!string.IsNullOrEmpty(code)) { formParams.Add("code", code); } if (!string.IsNullOrEmpty(redirectUri)) { formParams.Add("redirect_uri", redirectUri); } if (!string.IsNullOrEmpty(codeVerifier)) { formParams.Add("code_verifier", codeVerifier); } if (!string.IsNullOrEmpty(refreshToken)) { formParams.Add("refresh_token", refreshToken); } - if (!string.IsNullOrEmpty(scope)) { formParams.Add("scope", scope); } + // convert scopes enum to string + SetQueryParameter("scope", scopes, formParams); if (!string.IsNullOrEmpty(clientId)) { formParams.Add("client_id", clientId); } - request.Content = new FormUrlEncodedContent(formParams); - - // SetHeader("Authorization", authorization, request); - - // *** --- ss ***** - // tell the underlying pipeline what scope we'd like to use + request.Content = new FormUrlEncodedContent(new Dictionary(formParams.ToDictionary(k => k.Key, k => k.Value.ToString()))); request.Method = new HttpMethod("POST"); @@ -536,7 +549,6 @@ private void SetHeader(string baseName, object value, HttpRequestMessage req) } logger.LogInformation($"Exited from FetchtokenAsync with response statusCode: {response.StatusCode}"); return response; - //return new ApiResponse(response, await LocalMarshalling.DeserializeAsync(response.Content)); } // using } @@ -551,7 +563,6 @@ private void SetHeader(string baseName, object value, HttpRequestMessage req) ///See the Developer's Guide topic on [Asymmetric Signing](/en/docs/oauth/v2/developers_guide/asymmetric-encryption/) for more information. /// /// Thrown when fails to make API call - /// Task of ApiResponse<Jwks>> public async System.Threading.Tasks.Task> GetKeysAsync(/*string accessToken = null,*/ bool throwOnError = true) @@ -570,13 +581,7 @@ public async System.Threading.Tasks.Task> GetKeysAsync(/*strin request.Headers.TryAddWithoutValidation("Accept", "application/json"); request.Headers.TryAddWithoutValidation("User-Agent", "APS SDK/AUTHENTICATION/C#/1.0.0-beta1"); - // if (!string.IsNullOrEmpty(accessToken)) - // { - // request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {accessToken}"); - // } - - // tell the underlying pipeline what scope we'd like to use - + request.Method = new HttpMethod("GET"); // make the HTTP request @@ -610,7 +615,6 @@ public async System.Threading.Tasks.Task> GetKeysAsync(/*strin ///Returns an OpenID Connect Discovery Specification compliant JSON document. It contains a list of the OpenID/OAuth endpoints, supported scopes, claims, public keys used to sign the tokens, and other details. /// /// Thrown when fails to make API call - /// Task of ApiResponse<OidcSpec>> public async System.Threading.Tasks.Task> GetOidcSpecAsync(/*string accessToken = null,*/ bool throwOnError = true) @@ -629,14 +633,7 @@ public async System.Threading.Tasks.Task> GetOidcSpecAsync request.Headers.TryAddWithoutValidation("Accept", "application/json"); request.Headers.TryAddWithoutValidation("User-Agent", "APS SDK/AUTHENTICATION/C#/1.0.0-beta1"); - // if (!string.IsNullOrEmpty(accessToken)) - // { - // request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {accessToken}"); - // } - - - - + // tell the underlying pipeline what scope we'd like to use request.Method = new HttpMethod("GET"); @@ -685,7 +682,7 @@ public async System.Threading.Tasks.Task> GetOidcSpecAsync ///The token to be introspected. (optional) /// /// - /// (optional) + ///The Client ID of the application making the request. **Note** This is required only for Traditional Web Apps and Server-to-Server Apps. It is not required for Desktop, Mobile, and Single-Page Apps. (optional) /// /// Task of ApiResponse<IntrospectToken>> @@ -706,25 +703,11 @@ public async System.Threading.Tasks.Task> GetOidcSpecAsync request.Headers.TryAddWithoutValidation("Accept", "application/json"); request.Headers.TryAddWithoutValidation("User-Agent", "APS SDK/AUTHENTICATION/C#/1.0.0-beta1"); - - // *** ss - Manually added *** - if (!string.IsNullOrEmpty(authorization)) { request.Headers.TryAddWithoutValidation("Authorization", $"Basic {authorization}"); } - // if (!string.IsNullOrEmpty(accessToken)) - // { - // request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {accessToken}"); - // } - - - // request.Content = new StringContent(token); - // request.Content = new StringContent(clientId); - - // SetHeader("Authorization", authorization, request); - var formParams = new Dictionary(); if (!string.IsNullOrEmpty(token)) { formParams.Add("token", token); } @@ -732,10 +715,6 @@ public async System.Threading.Tasks.Task> GetOidcSpecAsync request.Content = new FormUrlEncodedContent(formParams); - // -- ss - end of Manual code - - // tell the underlying pipeline what scope we'd like to use - request.Method = new HttpMethod("POST"); // make the HTTP request @@ -824,11 +803,12 @@ public async System.Threading.Tasks.Task> GetOidcSpecAsync ///**Note** This header is required only for Traditional Web Apps and Server-to-Server Apps. It is not required for Desktop, Mobile, and Single-Page Apps. (optional) /// /// - /// (optional) + ///The Client ID of the application making the request. **Note** This is required only for Traditional Web Apps and Server-to-Server Apps. It is not required for Desktop, Mobile, and Single-Page Apps. (optional) /// /// Task of HttpResponseMessage - public async System.Threading.Tasks.Task RevokeAsync(string token, string authorization = default(string), string tokenTypeHint = default(string), string clientId = default(string), bool throwOnError = true) + + public async System.Threading.Tasks.Task RevokeAsync(string token, TokenTypeHint tokenTypeHint, string authorization = default(string), string clientId = default(string), /* string accessToken = null, */ bool throwOnError = true) { logger.LogInformation("Entered into RevokeAsync "); using (var request = new HttpRequestMessage()) @@ -845,35 +825,17 @@ public async System.Threading.Tasks.Task> GetOidcSpecAsync request.Headers.TryAddWithoutValidation("Accept", "application/json"); request.Headers.TryAddWithoutValidation("User-Agent", "APS SDK/AUTHENTICATION/C#/1.0.0-beta1"); - // ss manually added - if (!string.IsNullOrEmpty(authorization)) { request.Headers.TryAddWithoutValidation("Authorization", $"Basic {authorization}"); } - // if (!string.IsNullOrEmpty(accessToken)) - // { - // request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {accessToken}"); - // } - - - // request.Content = new StringContent(token); - // request.Content = new StringContent(tokenTypeHint); - // request.Content = new StringContent(clientId); - - - var formParams = new Dictionary(); - + var formParams = new Dictionary(); if (!string.IsNullOrEmpty(token)) { formParams.Add("token", token); } - if (!string.IsNullOrEmpty(tokenTypeHint)) { formParams.Add("token_type_hint", tokenTypeHint); } + // convert tokenTypeHint enum to string + SetQueryParameter("token_type_hint", tokenTypeHint, formParams); if (!string.IsNullOrEmpty(clientId)) { formParams.Add("client_id", clientId); } - request.Content = new FormUrlEncodedContent(formParams); - - - - // ss - end of code block - // tell the underlying pipeline what scope we'd like to use + request.Content = new FormUrlEncodedContent(new Dictionary(formParams.ToDictionary(k => k.Key, k => k.Value.ToString()))); request.Method = new HttpMethod("POST"); diff --git a/authentication/source/Http/UsersApi.gen.cs b/authentication/source/Http/UsersApi.gen.cs index 3d59734..85f2aab 100644 --- a/authentication/source/Http/UsersApi.gen.cs +++ b/authentication/source/Http/UsersApi.gen.cs @@ -48,8 +48,8 @@ public interface IUsersApi /// Thrown when fails to make API call /// YOUR_3_LEGGED_ACCESS_TOKEN (optional) /// Task of ApiResponse<UserInfo> - - System.Threading.Tasks.Task> GetUserinfoAsync (string authorization, bool throwOnError = true); + + System.Threading.Tasks.Task> GetUserInfoAsync(string authorization, bool throwOnError = true); } /// @@ -59,6 +59,9 @@ public partial class UsersApi : IUsersApi { ILogger logger; + // Manually added because UsersApi has a different base address. + public Uri BaseAddress { get; set; } + /// /// Initializes a new instance of the class /// using SDKManager object @@ -68,31 +71,32 @@ public partial class UsersApi : IUsersApi public UsersApi(SDKManager.SDKManager sdkManager) { this.Service = sdkManager.ApsClient.Service; + this.BaseAddress = new Uri("https://api.userprofile.autodesk.com/"); this.logger = sdkManager.Logger; } private void SetQueryParameter(string name, object value, Dictionary dictionary) { - if(value is Enum) + 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) + if (valueAttributes.Length > 0) { dictionary.Add(name, ((EnumMemberAttribute)valueAttributes[0]).Value); } } - else if(value is int) + else if (value is int) { - if((int)value > 0) + if ((int)value > 0) { dictionary.Add(name, value); } } else { - if(value != null) + if (value != null) { dictionary.Add(name, value); } @@ -100,27 +104,27 @@ private void SetQueryParameter(string name, object value, Dictionary /// An instance of the ForgeService - public ForgeService Service {get; set;} + public ForgeService Service { get; set; } /// /// Get User Info @@ -139,36 +143,24 @@ private void SetHeader(string baseName, object value, HttpRequestMessage req) /// Thrown when fails to make API call /// YOUR_3_LEGGED_ACCESS_TOKEN (optional) /// Task of ApiResponse<UserInfo> - - public async System.Threading.Tasks.Task> GetUserinfoAsync (string authorization, bool throwOnError = true) + + public async System.Threading.Tasks.Task> GetUserInfoAsync(string authorization, bool throwOnError = true) { - logger.LogInformation("Entered into GetUserinfoAsync "); + logger.LogInformation("Entered into GetUserInfoAsync "); using (var request = new HttpRequestMessage()) { var queryParam = new Dictionary(); // *** ss added manually - request.RequestUri = new Uri("https://api.userprofile.autodesk.com/userinfo"); - // Marshalling.BuildRequestUri("/userinfo", - // routeParameters: new Dictionary { - // }, - // queryParameters: queryParam - // ); + request.RequestUri = new Uri(BaseAddress, "/userinfo"); request.Headers.TryAddWithoutValidation("Accept", "application/json"); - request.Headers.TryAddWithoutValidation("User-Agent", "APS SDK/AUTHENTICATION/C#/1.0.0-beta1"); - if(!string.IsNullOrEmpty(authorization)) + request.Headers.TryAddWithoutValidation("User-Agent", "APS SDK/AUTHENTICATION/C#/1.0.0"); + if (!string.IsNullOrEmpty(authorization)) { request.Headers.TryAddWithoutValidation("Authorization", $"Bearer {authorization}"); } - - // SetHeader("Authorization", authorization, request); - - // *** ss code end*** - - // tell the underlying pipeline what scope we'd like to use - request.Method = new HttpMethod("GET"); // make the HTTP request @@ -178,9 +170,11 @@ public async System.Threading.Tasks.Task> GetUserinfoAsync { try { - await response.EnsureSuccessStatusCodeAsync(); - } catch (HttpRequestException ex) { - throw new AuthenticationApiException(ex.Message, response, ex); + await response.EnsureSuccessStatusCodeAsync(); + } + catch (HttpRequestException ex) + { + throw new AuthenticationApiException(ex.Message, response, ex); } } else if (!response.IsSuccessStatusCode) @@ -188,7 +182,7 @@ public async System.Threading.Tasks.Task> GetUserinfoAsync logger.LogError($"response unsuccess with status code: {response.StatusCode}"); return new ApiResponse(response, default(UserInfo)); } - logger.LogInformation($"Exited from GetUserinfoAsync with response statusCode: {response.StatusCode}"); + logger.LogInformation($"Exited from GetUserInfoAsync with response statusCode: {response.StatusCode}"); return new ApiResponse(response, await LocalMarshalling.DeserializeAsync(response.Content)); } // using diff --git a/authentication/source/Model/GrantType.cs b/authentication/source/Model/GrantType.gen.cs similarity index 100% rename from authentication/source/Model/GrantType.cs rename to authentication/source/Model/GrantType.gen.cs diff --git a/authentication/source/Model/IntrospectToken.gen.cs b/authentication/source/Model/IntrospectToken.gen.cs index bfa0b6c..ebd7b20 100644 --- a/authentication/source/Model/IntrospectToken.gen.cs +++ b/authentication/source/Model/IntrospectToken.gen.cs @@ -33,10 +33,10 @@ namespace Autodesk.Authentication.Model { /// - /// IntrospectToken + /// Represents the payload returned for an introspect token request. /// [DataContract] - public partial class IntrospectToken + public partial class IntrospectToken { /// /// Initializes a new instance of the class. @@ -44,18 +44,18 @@ public partial class IntrospectToken public IntrospectToken() { } - + /// ///`true`: The token is active. -/// -///`false`: The token is expired, invalid, or revoked. + /// + ///`false`: The token is expired, invalid, or revoked. /// /// ///`true`: The token is active. -/// -///`false`: The token is expired, invalid, or revoked. + /// + ///`false`: The token is expired, invalid, or revoked. /// - [DataMember(Name="active", EmitDefaultValue=false)] + [DataMember(Name = "active", EmitDefaultValue = false)] public bool? Active { get; set; } /// @@ -64,7 +64,7 @@ public IntrospectToken() /// ///A URL-encoded, space separated list of scopes associated with the token. /// - [DataMember(Name="scope", EmitDefaultValue=false)] + [DataMember(Name = "scope", EmitDefaultValue = false)] public string Scope { get; set; } /// @@ -73,7 +73,7 @@ public IntrospectToken() /// ///The Client ID of the application associated with the token. /// - [DataMember(Name="client_id", EmitDefaultValue=false)] + [DataMember(Name = "client_id", EmitDefaultValue = false)] public string ClientId { get; set; } /// @@ -82,7 +82,7 @@ public IntrospectToken() /// ///The expiration time of the token, represented as a Unix timestamp. /// - [DataMember(Name="exp", EmitDefaultValue=false)] + [DataMember(Name = "exp", EmitDefaultValue = false)] public int? Exp { get; set; } /// @@ -91,8 +91,8 @@ public IntrospectToken() /// ///The ID of the user who authorized the token. /// - [DataMember(Name="userid", EmitDefaultValue=false)] - public string Userid { get; set; } + [DataMember(Name = "userid", EmitDefaultValue = false)] + public string UserId { get; set; } /// /// Returns the string presentation of the object diff --git a/authentication/source/Model/Jwks.gen.cs b/authentication/source/Model/Jwks.gen.cs index bea7b89..fe32e6e 100644 --- a/authentication/source/Model/Jwks.gen.cs +++ b/authentication/source/Model/Jwks.gen.cs @@ -33,7 +33,7 @@ namespace Autodesk.Authentication.Model { /// - /// Jwks + /// Represents a successful response to a Get JWKS operation. /// [DataContract] public partial class Jwks @@ -46,8 +46,11 @@ public Jwks() } /// - ///Gets or Sets Keys + ///An array of objects where each object represents a JSON Web Key Set (JWKS). /// + /// + ///An array of objects where each object represents a JSON Web Key Set (JWKS). + /// [DataMember(Name="keys", EmitDefaultValue=false)] public List Keys { get; set; } diff --git a/authentication/source/Model/JwksKey.cs b/authentication/source/Model/JwksKey.gen.cs similarity index 85% rename from authentication/source/Model/JwksKey.cs rename to authentication/source/Model/JwksKey.gen.cs index 2f8622f..8a606b4 100644 --- a/authentication/source/Model/JwksKey.cs +++ b/authentication/source/Model/JwksKey.gen.cs @@ -33,10 +33,10 @@ namespace Autodesk.Authentication.Model { /// - /// JwksKey + /// Represents a JSON Web Key Set (JWKS). /// [DataContract] - public partial class JwksKey + public partial class JwksKey { /// /// Initializes a new instance of the class. @@ -44,14 +44,14 @@ public partial class JwksKey public JwksKey() { } - + /// ///The ID of the key. Acts as a unique identifier for a specific key within the JWKS. /// /// ///The ID of the key. Acts as a unique identifier for a specific key within the JWKS. /// - [DataMember(Name="kid", EmitDefaultValue=false)] + [DataMember(Name = "kid", EmitDefaultValue = false)] public string Kid { get; set; } /// @@ -60,20 +60,20 @@ public JwksKey() /// ///The cryptographic algorithm family used with the key. Currently, always `RSA`. /// - [DataMember(Name="kty", EmitDefaultValue=false)] + [DataMember(Name = "kty", EmitDefaultValue = false)] public string Kty { get; set; } /// ///The intended use of the public key. Possible values: -/// -///- `sig` - Verify the signature on data. + /// + ///- `sig` - Verify the signature on data. /// /// ///The intended use of the public key. Possible values: -/// -///- `sig` - Verify the signature on data. + /// + ///- `sig` - Verify the signature on data. /// - [DataMember(Name="use", EmitDefaultValue=false)] + [DataMember(Name = "use", EmitDefaultValue = false)] public string Use { get; set; } /// @@ -82,7 +82,7 @@ public JwksKey() /// ///The RSA modulus value. /// - [DataMember(Name="n", EmitDefaultValue=false)] + [DataMember(Name = "n", EmitDefaultValue = false)] public string N { get; set; } /// @@ -91,7 +91,7 @@ public JwksKey() /// ///The RSA exponent value. /// - [DataMember(Name="e", EmitDefaultValue=false)] + [DataMember(Name = "e", EmitDefaultValue = false)] public string E { get; set; } /// diff --git a/authentication/source/Model/OidcSpec.gen.cs b/authentication/source/Model/OidcSpec.gen.cs index 27fbccb..0f51a98 100644 --- a/authentication/source/Model/OidcSpec.gen.cs +++ b/authentication/source/Model/OidcSpec.gen.cs @@ -33,7 +33,7 @@ namespace Autodesk.Authentication.Model { /// - /// OIDC Specification + /// Represents a successful response to a Get OIDC Specification operation. /// [DataContract] public partial class OidcSpec @@ -79,7 +79,7 @@ public OidcSpec() ///The endpoint for querying information about the authenticated user. /// [DataMember(Name="userinfo_endpoint", EmitDefaultValue=false)] - public string UserinfoEndpoint { get; set; } + public string UserInfoEndpoint { get; set; } /// ///The endpoint for retrieving public keys used by APS, in the JWKS format. diff --git a/authentication/source/Model/RefreshToken.gen.cs b/authentication/source/Model/RefreshToken.gen.cs deleted file mode 100644 index 7b3160a..0000000 --- a/authentication/source/Model/RefreshToken.gen.cs +++ /dev/null @@ -1,82 +0,0 @@ -/* - * 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 - * - * OAuth2 token management APIs. - * - * 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.Linq; -using System.IO; -using System.Text; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; - -namespace Autodesk.Authentication.Model -{ - /// - /// Refresh token response body. - /// - [DataContract] - public partial class RefreshToken - { - /// - /// Initializes a new instance of the class. - /// - public RefreshToken() - { - } - - /// - ///Gets or Sets AccessToken - /// - [DataMember(Name="access_token", EmitDefaultValue=false)] - public string AccessToken { get; set; } - - /// - ///Gets or Sets TokenType - /// - [DataMember(Name="token_type", EmitDefaultValue=false)] - public string TokenType { get; set; } - - /// - ///Gets or Sets ExpiresIn - /// - [DataMember(Name="expires_in", EmitDefaultValue=false)] - public int? ExpiresIn { get; set; } - - /// - ///Gets or Sets _RefreshToken - /// - [DataMember(Name="refresh_token", EmitDefaultValue=false)] - public string _RefreshToken { 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/source/Model/ResponseType.cs b/authentication/source/Model/ResponseType.gen.cs similarity index 99% rename from authentication/source/Model/ResponseType.cs rename to authentication/source/Model/ResponseType.gen.cs index c1927cc..2a9938d 100644 --- a/authentication/source/Model/ResponseType.cs +++ b/authentication/source/Model/ResponseType.gen.cs @@ -58,7 +58,7 @@ public enum ResponseType /// Enum Idtoken for value: id_token /// [EnumMember(Value = "id_token")] - Idtoken + IdToken } } diff --git a/authentication/source/Model/Scopes.gen.cs b/authentication/source/Model/Scopes.gen.cs index 72cbb86..ce96d47 100644 --- a/authentication/source/Model/Scopes.gen.cs +++ b/authentication/source/Model/Scopes.gen.cs @@ -42,12 +42,6 @@ namespace Autodesk.Authentication.Model public enum Scopes { - /// - /// Enum UserProfileread for value: user-profile:read - /// - [EnumMember(Value = "user-profile:read")] - UserProfileRead, - /// /// Enum Userread for value: user:read /// @@ -60,6 +54,12 @@ public enum Scopes [EnumMember(Value = "user:write")] UserWrite, + /// + /// Enum UserProfileread for value: user-profile:read + /// + [EnumMember(Value = "user-profile:read")] + UserProfileRead, + /// /// Enum Viewablesread for value: viewables:read /// @@ -76,7 +76,7 @@ public enum Scopes /// Enum DatareadURNOFRESOURCE for value: data:read:<URN_OF_RESOURCE> /// [EnumMember(Value = "data:read:")] - DatareadURNOFRESOURCE, + DataReadURNOFRESOURCE, /// /// Enum Datawrite for value: data:write diff --git a/authentication/source/Model/ThreeLeggedToken.gen.cs b/authentication/source/Model/ThreeLeggedToken.gen.cs index d81e3b5..9a35cc6 100644 --- a/authentication/source/Model/ThreeLeggedToken.gen.cs +++ b/authentication/source/Model/ThreeLeggedToken.gen.cs @@ -33,10 +33,10 @@ namespace Autodesk.Authentication.Model { /// - /// ThreeLeggedToken + /// Represents the payload returned in response to an authorization code grant request. /// [DataContract] - public partial class ThreeLeggedToken + public partial class ThreeLeggedToken { /// /// Initializes a new instance of the class. @@ -44,37 +44,76 @@ public partial class ThreeLeggedToken public ThreeLeggedToken() { } - + + private int? _expiresIn; + + private long? _expiresAt; + /// - ///Gets or Sets TokenType + ///Will always be Bearer. /// - [DataMember(Name="token_type", EmitDefaultValue=false)] + /// + ///Will always be Bearer. + /// + [DataMember(Name = "token_type", EmitDefaultValue = false)] public string TokenType { get; set; } /// - ///Gets or Sets ExpiresIn + ///Access token time to expiration (in seconds). /// - [DataMember(Name="expires_in", EmitDefaultValue=false)] - public int? ExpiresIn { get; set; } + /// + ///Access token time to expiration (in seconds). + /// + [DataMember(Name = "expires_in", EmitDefaultValue = false)] + public int? ExpiresIn + { + get { return _expiresIn; } + set + { + _expiresIn = value; + _expiresAt = DateTimeOffset.Now.ToUnixTimeSeconds() + _expiresIn; + + } + } /// - ///Gets or Sets RefreshToken + /// 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 refresh token. /// - [DataMember(Name="refresh_token", EmitDefaultValue=false)] + /// + ///The refresh token. + /// + [DataMember(Name = "refresh_token", EmitDefaultValue = false)] public string RefreshToken { get; set; } /// - ///Gets or Sets AccessToken + ///The access token. /// - [DataMember(Name="access_token", EmitDefaultValue=false)] + /// + ///The access token. + /// + [DataMember(Name = "access_token", EmitDefaultValue = false)] public string AccessToken { get; set; } /// - ///Gets or Sets IdToken + ///The ID token, if openid scope was specified in /authorize request. /// - [DataMember(Name="id_token", EmitDefaultValue=false)] + /// + ///The ID token, if openid scope was specified in /authorize request. + /// + [DataMember(Name = "id_token", EmitDefaultValue = false)] public string IdToken { get; set; } + /// /// Returns the string presentation of the object /// diff --git a/authentication/source/Model/TokenTypeHint.cs b/authentication/source/Model/TokenTypeHint.gen.cs similarity index 97% rename from authentication/source/Model/TokenTypeHint.cs rename to authentication/source/Model/TokenTypeHint.gen.cs index d4d000f..f5f66e6 100644 --- a/authentication/source/Model/TokenTypeHint.cs +++ b/authentication/source/Model/TokenTypeHint.gen.cs @@ -46,13 +46,13 @@ public enum TokenTypeHint /// Enum Accesstoken for value: access_token /// [EnumMember(Value = "access_token")] - Accesstoken, + AccessToken, /// /// Enum Refreshtoken for value: refresh_token /// [EnumMember(Value = "refresh_token")] - Refreshtoken + RefreshToken } } diff --git a/authentication/source/Model/TwoLeggedToken.gen.cs b/authentication/source/Model/TwoLeggedToken.gen.cs index 96666aa..e8c209a 100644 --- a/authentication/source/Model/TwoLeggedToken.gen.cs +++ b/authentication/source/Model/TwoLeggedToken.gen.cs @@ -33,35 +33,69 @@ namespace Autodesk.Authentication.Model { /// - /// Client credentials grant response body. + /// Represents the payload returned in response to a client credentials grant request. /// [DataContract] - public partial class TwoLeggedToken + public partial class TwoLeggedToken { /// /// Initializes a new instance of the class. /// + + public TwoLeggedToken() { + } - + + private int? _expiresIn; + + private long? _expiresAt; /// - ///Gets or Sets AccessToken + ///The access token. /// - [DataMember(Name="access_token", EmitDefaultValue=false)] + /// + ///The access token. + /// + [DataMember(Name = "access_token", EmitDefaultValue = false)] public string AccessToken { get; set; } /// - ///Gets or Sets TokenType + ///Will always be Bearer. /// - [DataMember(Name="token_type", EmitDefaultValue=false)] + /// + ///Will always be Bearer. + /// + [DataMember(Name = "token_type", EmitDefaultValue = false)] public string TokenType { get; set; } /// - ///Gets or Sets ExpiresIn + ///Access token expiration time (in seconds). + /// + /// + ///Access token expiration time (in seconds). + /// + [DataMember(Name = "expires_in", EmitDefaultValue = false)] + public int? ExpiresIn + { + get { return _expiresIn; } + set + { + _expiresIn = value; + _expiresAt = DateTimeOffset.Now.ToUnixTimeSeconds() + _expiresIn; + + } + } + + /// + ///Access token expiration time, in Unix seconds. /// - [DataMember(Name="expires_in", EmitDefaultValue=false)] - public int? ExpiresIn { get; set; } + /// + ///Access token expiration time, in Unix seconds. + /// + [DataMember(Name = "expires_at", EmitDefaultValue = false)] + public long? ExpiresAt { get { return _expiresAt; } } + /// /// Returns the string presentation of the object diff --git a/authentication/source/Model/UserInfo.gen.cs b/authentication/source/Model/UserInfo.gen.cs index fa2f12e..06865c9 100644 --- a/authentication/source/Model/UserInfo.gen.cs +++ b/authentication/source/Model/UserInfo.gen.cs @@ -33,7 +33,7 @@ namespace Autodesk.Authentication.Model { /// - /// UserInfo + /// Represents a successful response to a Get User Info operation. /// [DataContract] public partial class UserInfo @@ -330,7 +330,7 @@ public UserInfo() ///An array of key-value pairs containing image URLs for various thumbnail sizes of the user's profile picture. The key is named `sizeX<NUMBER>` where `<NUMBER>` is the width and height of the thumbnail, in pixels. The corresponding value is the URL pointing to the thumbnail. For example, `sizeX200` would contain the URL for the 200x200 pixel thumbnail. /// [DataMember(Name = "thumbnails", EmitDefaultValue = false)] - public List Thumbnails { get; set; } + public Dictionary Thumbnails { get; set; } /// /// Returns the string presentation of the object diff --git a/authentication/source/ServiceApiException.cs b/authentication/source/ServiceApiException.cs index a55f5e8..734a147 100644 --- a/authentication/source/ServiceApiException.cs +++ b/authentication/source/ServiceApiException.cs @@ -24,20 +24,27 @@ namespace Autodesk.Authentication { + + /// + /// An object that is returned when an API call fails. + /// public abstract class ServiceApiException : HttpRequestException { - public HttpResponseMessage HttpResponseMessage {get; set;} + public HttpResponseMessage HttpResponseMessage { get; set; } - public ServiceApiException(string message) : base(message) {} + public ServiceApiException(string message) : base(message) { } public ServiceApiException(string message, HttpResponseMessage httpResponseMessage, Exception exception) : base(message, exception) { this.HttpResponseMessage = httpResponseMessage; } } + /// + /// An object that is returned when an API call to the Authentication service fails. + /// public class AuthenticationApiException : ServiceApiException { - public AuthenticationApiException(string message) : base(message) {} - public AuthenticationApiException(string message, HttpResponseMessage httpResponseMessage, Exception exception) : base(message, httpResponseMessage, exception) {} + public AuthenticationApiException(string message) : base(message) { } + public AuthenticationApiException(string message, HttpResponseMessage httpResponseMessage, Exception exception) : base(message, httpResponseMessage, exception) { } } } diff --git a/authentication/source/custom-code/AuthenticationClient.cs b/authentication/source/custom-code/AuthenticationClient.cs index b57cc08..795363e 100644 --- a/authentication/source/custom-code/AuthenticationClient.cs +++ b/authentication/source/custom-code/AuthenticationClient.cs @@ -6,6 +6,7 @@ using Autodesk.Authentication.Client; using System.Net.Http; using System.Net.Cache; +using System.Text.Json.Nodes; namespace Autodesk.Authentication { @@ -35,12 +36,14 @@ public AuthenticationClient(SDKManager.SDKManager sDKManager) ///Retrieves information about the authenticated user. /// /// Thrown when fails to make API call - /// YOUR_3_LEGGED_ACCESS_TOKEN - /// Task of <UserInfo> + /// + /// The 3-legged access token of the currently logged in user. + /// + /// Task of ApiResponse<UserInfo> public async System.Threading.Tasks.Task GetUserInfoAsync(string authorization, bool throwOnError = true) { - var response = await this.usersApi.GetUserinfoAsync(authorization, throwOnError); + var response = await this.usersApi.GetUserInfoAsync(authorization, throwOnError); return response.Content; } @@ -64,18 +67,13 @@ public async System.Threading.Tasks.Task GetUserInfoAsync(string autho /// /// ///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 string you specify for this parameter must not exceed 2000 characters and it cannot contain more than 50 scopes. /// /// Task of <TwoLeggedToken> public async System.Threading.Tasks.Task GetTwoLeggedTokenAsync(string clientId, string clientSecret, List scopes, bool throwOnError = true) { var clientIdSecret = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}")); - var strScopes = String.Join(" ", scopes.Select(x => Utils.GetEnumString(x))); - var grantType = Utils.GetEnumString(GrantType.ClientCredentials); - var response = await this.tokenApi.FetchTokenAsync(authorization: clientIdSecret, scope: strScopes, grantType: grantType, throwOnError: throwOnError); + var response = await this.tokenApi.FetchTokenAsync(authorization: clientIdSecret, scopes: scopes, grantType: GrantType.ClientCredentials, throwOnError: throwOnError); return await LocalMarshalling.DeserializeAsync(response.Content); - } /// @@ -90,7 +88,6 @@ public async System.Threading.Tasks.Task GetTwoLeggedTokenAsync( /// ///**Note:** This operation is intended for use with client-side applications only. It is not suitable for server-side applications. /// - /// Thrown when fails to make API call /// ///The Client ID of the calling application, as registered with APS. /// @@ -115,8 +112,6 @@ public async System.Threading.Tasks.Task GetTwoLeggedTokenAsync( /// /// ///A URL-encoded space-delimited 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 string you specify for this parameter must not exceed 2000 characters and it cannot contain more than 50 scopes. (optional) /// /// ///Specifies how the authorization response should be returned. Valid values are: @@ -146,11 +141,9 @@ public async System.Threading.Tasks.Task GetTwoLeggedTokenAsync( ///- `S256`- Hashes the code verifier using the SHA-256 algorithm and then applies Base64 URL encoding. (optional) /// /// string - public string Authorize(string clientId, ResponseType responseType, string redirectUri, List scopes) + public string Authorize(string clientId, ResponseType responseType, string redirectUri, List scopes, string nonce = default(string), string state = default(string), string responseMode = default(string), string prompt = default(string), string authoptions = default(string), string codeChallenge = default(string), string codeChallengeMethod = default(string)) { - var strResponseType = Utils.GetEnumString(responseType); - var strScopes = String.Join(" ", scopes.Select(x => Utils.GetEnumString(x))); - return this.tokenApi.Authorize(clientId: clientId, redirectUri: redirectUri, responseType: strResponseType, scope: strScopes); + return this.tokenApi.Authorize(clientId, responseType, redirectUri, nonce, state, scopes, responseMode, prompt, authoptions, codeChallenge, codeChallengeMethod); } /// @@ -169,29 +162,29 @@ public string Authorize(string clientId, ResponseType responseType, string redir ///**Note** The clientSecret is required only for Traditional Web Apps and Server-to-Server Apps. It is not required for Desktop, Mobile, and Single-Page Apps. (optional) /// /// - ///The authorization code that was passed to your application when the user granted access permission to your application. It was passed as the [code` query parameter to the redirect URI when you called `Authorize User](/en/docs/oauth/v2/reference/http/authorize-GET/). + ///The authorization code that was passed to your application when the user granted access permission to your application. It was passed as the `code` query parameter to the redirect URI when you called [Authorize User](/en/docs/oauth/v2/reference/http/authorize-GET/). /// /// ///The URI that APS redirects users to after they grant or deny access permission to the application. Must match the Callback URL for the application registered with APS. /// /// - ///A random URL-encoded string between 43 characters and 128 characters. In a PKCE grant flow, the authentication server uses this string to verify the code challenge that was passed when you called [Authorize User](/en/docs/oauth/v2/reference/http/authorize-GET/). Required if [`code_challenge` was specified when you called `Authorize User](/en/docs/oauth/v2/reference/http/authorize-GET/). (optional) + ///A random URL-encoded string between 43 characters and 128 characters. In a PKCE grant flow, the authentication server uses this string to verify the code challenge that was passed when you called [Authorize User](/en/docs/oauth/v2/reference/http/authorize-GET/). Required if [`code_challenge` was specified when you called [Authorize User](/en/docs/oauth/v2/reference/http/authorize-GET/). (optional) /// /// Task of <ThreeLeggedToken> - public async System.Threading.Tasks.Task GetThreeLeggedTokenAsync(string clientId, string code, string redirect_uri, string clientSecret = default(string), string code_verifier = default(string), bool throwOnError = true) + public async System.Threading.Tasks.Task GetThreeLeggedTokenAsync(string clientId, string code, string redirectUri, string clientSecret = default(string), string codeVerifier = default(string), bool throwOnError = true) { if (!string.IsNullOrEmpty(clientSecret)) - { + { // for private clients var clientIdSecret = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}")); - var grant_type = Utils.GetEnumString(GrantType.AuthorizationCode); - var response = await this.tokenApi.FetchTokenAsync(authorization: clientIdSecret, code: code, grantType: grant_type, redirectUri: redirect_uri, throwOnError: throwOnError); + var response = await this.tokenApi.FetchTokenAsync(authorization: clientIdSecret, code: code, grantType: GrantType.AuthorizationCode, redirectUri: redirectUri, throwOnError: throwOnError); return await LocalMarshalling.DeserializeAsync(response.Content); + } else - { - var grant_type = Utils.GetEnumString(GrantType.AuthorizationCode); - var response = await this.tokenApi.FetchTokenAsync(clientId: clientId, code: code, grantType: grant_type, redirectUri: redirect_uri, codeVerifier: code_verifier, throwOnError: throwOnError); + { // for public clients + var response = await this.tokenApi.FetchTokenAsync(clientId: clientId, code: code, grantType: GrantType.AuthorizationCode, redirectUri: redirectUri, codeVerifier: codeVerifier, throwOnError: throwOnError); return await LocalMarshalling.DeserializeAsync(response.Content); + } } @@ -199,7 +192,7 @@ public string Authorize(string clientId, ResponseType responseType, string redir /// Acquire Refresh Token /// /// - ///Returns new access token using the refresh token provided in the request. + ///Returns a new 3-legged access token using the refresh token provided in the request. ///This operation has a rate limit of 500 calls per minute. /// /// Thrown when fails to make API call @@ -215,30 +208,22 @@ public string Authorize(string clientId, ResponseType responseType, string redir /// /// ///A URL-encoded space-delimited 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 string you specify for this parameter must not exceed 2000 characters and it cannot contain more than 50 scopes. ///If specified, scopes have to be primarily same with or a subset of the scopes used to generate the refresh_token.(optional) /// - /// Task of <RefreshToken> - public async System.Threading.Tasks.Task GetRefreshTokenAsync(string clientId, string clientSecret, string refreshToken, List scopes = null) + /// Task of <ThreeLeggedToken> + public async System.Threading.Tasks.Task RefreshTokenAsync(string clientId, string clientSecret, string refreshToken, List scopes = null, bool throwOnError = true) { - string strScopes = null; - if (scopes != null && scopes.Any()) - { - strScopes = String.Join(" ", scopes.Select(x => Utils.GetEnumString(x))); - } if (!string.IsNullOrEmpty(clientSecret)) - { + { // for private clients var clientIdSecret = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}")); - var grant_type = Utils.GetEnumString(GrantType.RefreshToken); - var response = await this.tokenApi.FetchTokenAsync(authorization: clientIdSecret, scope: strScopes, grantType: grant_type, refreshToken: refreshToken); - return await LocalMarshalling.DeserializeAsync(response.Content); + var response = await this.tokenApi.FetchTokenAsync(authorization: clientIdSecret, scopes: scopes, grantType: GrantType.RefreshToken, refreshToken: refreshToken, throwOnError: throwOnError); + return await LocalMarshalling.DeserializeAsync(response.Content); } else - { - var grant_type = Utils.GetEnumString(GrantType.RefreshToken); - var response = await this.tokenApi.FetchTokenAsync(clientId: clientId, scope: strScopes, grantType: grant_type, refreshToken: refreshToken); - return await LocalMarshalling.DeserializeAsync(response.Content); + { // for public clients + var response = await this.tokenApi.FetchTokenAsync(clientId: clientId, scopes: scopes, grantType: GrantType.RefreshToken, refreshToken: refreshToken, throwOnError: throwOnError); + return await LocalMarshalling.DeserializeAsync(response.Content); } } @@ -259,9 +244,9 @@ public async System.Threading.Tasks.Task GetRefreshTokenAsync(stri /// Thrown when fails to make API call /// Task of <Jwks>> - public async System.Threading.Tasks.Task GetKeysAsync() + public async System.Threading.Tasks.Task GetKeysAsync(bool throwOnError = true) { - var response = await this.tokenApi.GetKeysAsync(); + var response = await this.tokenApi.GetKeysAsync(throwOnError); return response.Content; } @@ -273,9 +258,9 @@ public async System.Threading.Tasks.Task GetKeysAsync() /// /// Thrown when fails to make API call /// Task of <OidcSpec>> - public async System.Threading.Tasks.Task GetOidcSpecAsync() + public async System.Threading.Tasks.Task GetOidcSpecAsync(bool throwOnError = true) { - var response = await this.tokenApi.GetOidcSpecAsync(); + var response = await this.tokenApi.GetOidcSpecAsync(throwOnError); return response.Content; } @@ -302,17 +287,17 @@ public async System.Threading.Tasks.Task GetOidcSpecAsync() ///The Client ID of the calling application, as registered with APS. /// /// Task of <IntrospectToken>> - public async System.Threading.Tasks.Task IntrospectTokenAsync(string token, string clientId, string clientSecret = default(string)) + public async System.Threading.Tasks.Task IntrospectTokenAsync(string token, string clientId, string clientSecret = default(string), bool throwOnError = true) { if (!string.IsNullOrEmpty(clientSecret)) - { // for private client + { // for private clients var clientIdSecret = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}")); - var response = await this.tokenApi.IntrospectTokenAsync(token, clientIdSecret, null); + var response = await this.tokenApi.IntrospectTokenAsync(token: token, authorization: clientIdSecret, throwOnError: throwOnError); return response.Content; } else { // for public clients - var response = await this.tokenApi.IntrospectTokenAsync(token, null, clientId); + var response = await this.tokenApi.IntrospectTokenAsync(token: token, clientId: clientId, throwOnError: throwOnError); return response.Content; } } @@ -350,7 +335,7 @@ public async System.Threading.Tasks.Task GetOidcSpecAsync() /// ///This operation has a rate limit of 100 calls per minute. /// - /// Thrown when fails to make API call + /// Thrown when fails to make API call /// ///The token to be revoked. /// @@ -366,17 +351,16 @@ public async System.Threading.Tasks.Task GetOidcSpecAsync() /// /// Task of HttpResponseMessage - public async System.Threading.Tasks.Task RevokeAsync(string token, string clientId, string clientSecret = default(string), TokenTypeHint tokenTypeHint = default(TokenTypeHint)) + public async System.Threading.Tasks.Task RevokeAsync(string token, string clientId, string clientSecret = default(string), TokenTypeHint tokenTypeHint = default(TokenTypeHint), bool throwOnError = true) { - var token_type_hint = Utils.GetEnumString(tokenTypeHint); if (!string.IsNullOrEmpty(clientSecret)) - { // request is for private client + { // for private clients var clientIdSecret = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}")); - return await this.tokenApi.RevokeAsync(token, clientIdSecret, token_type_hint, null); + return await this.tokenApi.RevokeAsync(token: token, tokenTypeHint: tokenTypeHint, authorization: clientIdSecret, throwOnError: throwOnError); } else - { // request is for public client - return await this.tokenApi.RevokeAsync(token, token_type_hint, clientId); + { // for public clients + return await this.tokenApi.RevokeAsync(token: token, tokenTypeHint: tokenTypeHint, clientId: clientId, throwOnError: throwOnError); } diff --git a/authentication/source/custom-code/utils.cs b/authentication/source/custom-code/utils.cs deleted file mode 100644 index 6321ed8..0000000 --- a/authentication/source/custom-code/utils.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Runtime.Serialization; - - -namespace Autodesk.Authentication -{ - public static class Utils - { - - - internal static string GetEnumString(T enumVal) - { - var enumType = typeof(T); - var memInfo = enumType.GetMember(enumVal?.ToString()); - var attr = memInfo[0].GetCustomAttributes(false).OfType().FirstOrDefault(); - if (attr != null) - { - return attr.Value; - } - return null; - } - - } - - -} \ No newline at end of file diff --git a/samples/authentication.cs b/samples/authentication.cs index d65093b..b9c2559 100644 --- a/samples/authentication.cs +++ b/samples/authentication.cs @@ -1,3 +1,4 @@ +using System.Threading.Tasks; using Autodesk.Authentication; using Autodesk.Authentication.Model; using Autodesk.SDKManager; @@ -15,7 +16,7 @@ class Authentication string authorization_code = "code"; public void Initialise() - { + { // Instantiate SDK manager as below. SDKManager sdkManager = SdkManagerBuilder .Create() // Creates SDK Manager Builder itself. @@ -30,14 +31,23 @@ public async Task Get2LeggedTokenAsync() // Get 2Legged token. // Pass the client Id and secret as in your app. The method // will convert it in '${Base64(:)}' format - TwoLeggedToken twoLeggedToken = await authenticationClient.GetTwoLeggedTokenAsync(client_id, client_secret, new List() { Scopes.DataRead, Scopes.BucketRead }); + try + { + TwoLeggedToken twoLeggedToken = await authenticationClient.GetTwoLeggedTokenAsync(client_id, client_secret, new List() { Scopes.DataRead, Scopes.BucketRead }); + string accessToken = twoLeggedToken.AccessToken; + } + catch (AuthenticationApiException ex) + { + Console.Write(ex.Message); + } } public void GetAuthorizeURL() { // Get Authorize url - string url = authenticationClient.Authorize(client_id, ResponseType.Code, redirectUri: redirect_uri, new List() { Scopes.DataRead, Scopes.BucketRead }); + // List() { Scopes.DataRead, Scopes.BucketRead }); } @@ -46,51 +56,91 @@ public async Task Get3LeggedTokenAsync() // Get 3Legged token. // Pass the client Id and secret as in your app. The method // will convert it in Basic ${Base64(:)} format - - ThreeLeggedToken threeLeggedToken = await authenticationClient.GetThreeLeggedTokenAsync(client_id, client_secret, authorization_code, redirect_uri); - string threeLeggedToken_accesstoken = threeLeggedToken.AccessToken; + try + { + ThreeLeggedToken threeLeggedToken = await authenticationClient.GetThreeLeggedTokenAsync(client_id, authorization_code,redirect_uri, clientSecret: client_secret); + string accessToken = threeLeggedToken.AccessToken; + } + catch (AuthenticationApiException ex) + { + Console.Write(ex.Message); + } } - public async Task GetRefreshTokenAsync() + public async Task RefreshTokenAsync() { // Get Refresh token - RefreshToken newToken = await authenticationClient.GetRefreshTokenAsync(client_id, client_secret, "refreshToken"); - string refreshToken = newToken._RefreshToken; - int? expiresIn = newToken.ExpiresIn; + try + { + ThreeLeggedToken newToken = await authenticationClient.RefreshTokenAsync(client_id, client_secret, "refreshToken"); + string accessToken = newToken.AccessToken; + + } + catch (AuthenticationApiException ex) + { + Console.Write(ex.Message); + } } public async Task GetKeysAsync() { //Retrieves the list of public keys in the JWKS format (JSON Web Key Set) - Jwks jwks = await authenticationClient.GetKeysAsync(); - JwksKey jwksKey = jwks.Keys[1]; + try + { + Jwks jwks = await authenticationClient.GetKeysAsync(); + JwksKey jwksKey = jwks.Keys[1]; + } + catch (AuthenticationApiException ex) + { + Console.Write(ex.Message); + } } public async Task GetOidcSpecAsync() { // Retrieves the metadata as a JSON listing of OpenID/OAuth endpoints - OidcSpec oidcSpec = await authenticationClient.GetOidcSpecAsync(); - string issuer = oidcSpec.Issuer; + try + { + OidcSpec oidcSpec = await authenticationClient.GetOidcSpecAsync(); + string issuer = oidcSpec.Issuer; + } + catch (AuthenticationApiException ex) + { + Console.Write(ex.Message); + } } public async Task GetUserInfoAsync() { - // Retrieves basic information for the given authenticated user. - UserInfo userInfo = await authenticationClient.GetUserInfoAsync("threeLeggedToken_accesstoken"); - string userEmail = userInfo.Email; + try + { + // Retrieves basic information for the given authenticated user. + UserInfo userInfo = await authenticationClient.GetUserInfoAsync(token); + string userEmail = userInfo.Email; + } + catch (AuthenticationApiException ex) + { + Console.Write(ex.Message); + } } - public async Task TestIntrospectTokenAsync() + public async Task IntrospectTokenAsync() { // Returns the status information of the tokens. - IntrospectToken introspectToken = await authenticationClient.IntrospectTokenAsync(token, client_id, client_secret); - string tokenType = introspectToken.TokenType; + try + { + IntrospectToken introspectToken = await authenticationClient.IntrospectTokenAsync(token, client_id, client_secret); + } + catch (AuthenticationApiException ex) + { + Console.Write(ex.Message); + } } @@ -98,20 +148,36 @@ public async Task TestIntrospectTokenAsync() public async Task RevokeTokenAsync() { // This API endpoint takes an access token or refresh token and revokes it. - HttpResponseMessage response = await authenticationClient.RevokeAsync(token, client_id, client_secret); - + try + { + HttpResponseMessage response = await authenticationClient.RevokeAsync(token, client_id, client_secret); + } + catch (AuthenticationApiException ex) + { + Console.Write(ex.Message); + } } - public async void Main() + public void GetLogoutUrl() { + string logoutUrl = authenticationClient.Logout(); + } + public static async void Main() + { + Authentication authentication = new Authentication(); // Initialise SDKManager & AuthClient - Initialise(); + authentication.Initialise(); // Call respective methods - await Get2LeggedTokenAsync(); - await Get3LeggedTokenAsync(); - GetAuthorizeURL(); + await authentication.Get2LeggedTokenAsync(); + authentication.GetAuthorizeURL(); + await authentication.Get3LeggedTokenAsync(); + await authentication.RefreshTokenAsync(); + await authentication.GetOidcSpecAsync(); + await authentication.GetKeysAsync(); + authentication.GetLogoutUrl(); + }