public static string GetContainerId(string hub_id, string project_id) { credentials = Credentials.FromFile(Path.Combine( Directory.GetCurrentDirectory(), "token.json")); string container_id = String.Empty; TwoLeggedApi oauth = new TwoLeggedApi(); dynamic bearer = oauth.Authenticate(FORGE_CLIENT_ID, FORGE_CLIENT_SECRET, "client_credentials", new Scope[] { Scope.DataRead }); RestClient client = new RestClient(BASE_URL); RestRequest request = new RestRequest("project/v1/hubs/{hub_id}/projects", RestSharp.Method.GET); request.AddHeader("Authorization", "Bearer " + credentials.TokenInternal); request.AddParameter("hub_id", hub_id, ParameterType.UrlSegment); request.AddParameter("page[limit]", 99, ParameterType.QueryString); IRestResponse response = client.Execute(request); dynamic projects = JObject.Parse(response.Content); foreach (var project in projects.data) { if (project.id.ToString() == project_id) { container_id = project.relationships.issues.data.id.ToString(); } } return(container_id); }
private async Task <Auth> GetAccessToken(Scope[] scopes) { Auth cachedAuth; var cacheKey = string.Join("+", from scope in scopes select scope.ToString()); if (!authCache.TryGetValue(cacheKey, out cachedAuth) || cachedAuth.ExpiresAt >= DateTime.Now) { var client = new TwoLeggedApi(); var response = await client.AuthenticateAsync(clientId, clientSecret, "client_credentials", scopes); cachedAuth = new Auth { AccessToken = response.access_token, ExpiresIn = response.expires_in, ExpiresAt = DateTime.Now.AddSeconds(response.expires_in) }; if (authCache.ContainsKey(cacheKey)) { authCache.Remove(cacheKey); } authCache.Add(cacheKey, cachedAuth); } return(new Auth { AccessToken = cachedAuth.AccessToken, ExpiresAt = cachedAuth.ExpiresAt, ExpiresIn = (long)cachedAuth.ExpiresAt.Subtract(DateTime.Now).TotalSeconds }); }
public String GetPublic() { TwoLeggedApi oauth = new TwoLeggedApi(); string grantType = "client_credentials"; string forgeId = WebConfigurationManager.AppSettings["FORGE_CLIENT_ID"]; string forgeClient = WebConfigurationManager.AppSettings["FORGE_CLIENT_SECRET"]; RestClient _client = new RestClient("https://developer.api.autodesk.com"); RestRequest authReq = new RestRequest(); authReq.Resource = "authentication/v1/authenticate"; authReq.Method = Method.POST; authReq.AddHeader("Content-Type", "application/x-www-form-urlencoded"); authReq.AddParameter("client_id", forgeId); authReq.AddParameter("client_secret", forgeClient); authReq.AddParameter("grant_type", grantType); authReq.AddParameter("scope", "data:read data:write bucket:create bucket:read"); IRestResponse result = _client.Execute(authReq); if (result.StatusCode == System.Net.HttpStatusCode.OK) { responseString = result.Content; } return(responseString); }
public async Task <string> GetContainerIdAsync(string hubId, string projectId) { var containerId = string.Empty; var oauth = new TwoLeggedApi(); var bearer = await oauth.AuthenticateAsync(ForgeClientId, ForgeClientSecret, "client_credentials", new[] { Scope.DataRead }); var client = new RestClient(BaseUrl); var request = new RestRequest("project/v1/hubs/{hub_id}/projects", Method.GET); request.AddHeader("Authorization", "Bearer " + Credentials.TokenInternal); request.AddParameter("hub_id", hubId, ParameterType.UrlSegment); request.AddParameter("page[limit]", 99, ParameterType.QueryString); var response = await client.ExecuteAsync(request); dynamic projects = JObject.Parse(response.Content); foreach (var project in projects.data) { if (project.id.ToString() == projectId) { containerId = project.relationships.issues.data.id.ToString(); } } return(containerId); }
async Task <IAuthenticationToken> GetAuthToken() { var twoLeggedApi = new TwoLeggedApi(); ApiResponse <dynamic> apiResponse; try { apiResponse = await twoLeggedApi.AuthenticateAsyncWithHttpInfo(_clientId, _clientSecret, oAuthConstants.CLIENT_CREDENTIALS, new[] { Scope.BucketRead, Scope.BucketCreate, Scope.DataRead, Scope.DataWrite }); if (apiResponse == null) { _logger.Log(LogType.Error, "NULL API response during authorization"); return(null); } if (apiResponse.StatusCode != 200) { _logger.Log(LogType.Error, "API response not expected during authorization: " + apiResponse.StatusCode); return(null); } Configuration.Default.AccessToken = apiResponse.Data.access_token; } catch (Exception e) { _logger.Log(LogType.Error, "Exception while attempting to get access token: " + e); return(null); } return(new AuthenticationToken(apiResponse.Data.access_token, apiResponse.Data.expires_in)); }
public async Task <JArray> GetProjectByUser(string hubId) { TwoLeggedApi oauth = new TwoLeggedApi(); dynamic bearer = await oauth.AuthenticateAsync(Credentials.GetAppSetting("FORGE_CLIENT_ID"), Credentials.GetAppSetting("FORGE_CLIENT_SECRET"), "client_credentials", new Scope[] { Scope.AccountRead, Scope.DataRead }); JArray users = await GetUsers(hubId, bearer.access_token); foreach (dynamic user in users) { user.projects = new JArray(); user.projects_count = 0; if (user.uid == null) { continue; // not activated yet } dynamic projects = await GetProjectsAsync(hubId, (string)user.uid, (string)bearer.access_token); if (projects == null) { continue; } foreach (dynamic project in projects.data) { dynamic projectInfo = new JObject(); projectInfo.name = project.attributes.name; projectInfo.id = project.id; user.projects.Add(projectInfo); } user.projects_count = ((JArray)user.projects).Count; } return(new JArray(users.OrderByDescending(u => (int)u["projects_count"]))); }
private async void btnAuthenticate_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(txtClientId.Text) || string.IsNullOrWhiteSpace(txtClientSecret.Text)) { return; } // get the access token TwoLeggedApi oAuth = new TwoLeggedApi(); Bearer token = (await oAuth.AuthenticateAsync( txtClientId.Text, txtClientSecret.Text, oAuthConstants.CLIENT_CREDENTIALS, new Scope[] { Scope.BucketRead, Scope.BucketCreate, Scope.DataRead, Scope.DataWrite })).ToObject <Bearer>(); txtAccessToken.Text = token.AccessToken; _expiresAt = DateTime.Now.AddSeconds(token.ExpiresIn.Value); // keep track on time _tokenTimer.Tick += new EventHandler(tickTokenTimer); _tokenTimer.Interval = 1000; _tokenTimer.Enabled = true; btnRefreshToken_Click(null, null); }
/// <summary> /// Perform the OAuth authorization via code /// </summary> /// <param name="code"></param> /// <returns></returns> public static async Task <Credentials> CreateFromCodeAsync(string code, IResponseCookies cookies) { ThreeLeggedApi oauth = new ThreeLeggedApi(); TwoLeggedApi da4rOauth = new TwoLeggedApi(); // added for DA4R dynamic credentialInternal = await oauth.GettokenAsync( GetAppSetting("FORGE_CLIENT_ID"), GetAppSetting("FORGE_CLIENT_SECRET"), oAuthConstants.AUTHORIZATION_CODE, code, GetAppSetting("FORGE_CALLBACK_URL")); dynamic credentialPublic = await oauth.RefreshtokenAsync( GetAppSetting("FORGE_CLIENT_ID"), GetAppSetting("FORGE_CLIENT_SECRET"), "refresh_token", credentialInternal.refresh_token, new Scope[] { Scope.ViewablesRead }); // added for DA4R dynamic credentialDa4rInternal = await da4rOauth.AuthenticateAsync( GetAppSetting("FORGE_CLIENT_ID"), GetAppSetting("FORGE_CLIENT_SECRET"), "client_credentials", new Scope[] { Scope.BucketCreate, Scope.BucketRead, Scope.BucketUpdate, Scope.DataRead, Scope.DataWrite, Scope.DataCreate, Scope.CodeAll }); Credentials credentials = new Credentials(); credentials.TokenInternal = credentialInternal.access_token; credentials.DA4RTokenInternal = credentialDa4rInternal.access_token; //added for DA4R credentials.TokenPublic = credentialPublic.access_token; credentials.RefreshToken = credentialPublic.refresh_token; credentials.ExpiresAt = DateTime.Now.AddSeconds(credentialInternal.expires_in); cookies.Append(FORGE_COOKIE, JsonConvert.SerializeObject(credentials)); return(credentials); }
public static string Authenticate(ApplicationOptions options) { try { TwoLeggedApi _twoLeggedApi = null; if (string.IsNullOrWhiteSpace(options.BaseUrl)) { _twoLeggedApi = new TwoLeggedApi(); } else { _twoLeggedApi = new TwoLeggedApi(options.BaseUrl); } ApiResponse <dynamic> bearer = _twoLeggedApi.AuthenticateWithHttpInfo(options.ForgeClientId, options.ForgeClientSecret, oAuthConstants.CLIENT_CREDENTIALS, _scope); if (bearer.StatusCode != 200) { throw new Exception("Request failed! (with HTTP response " + bearer.StatusCode + ")"); } if (bearer.Data == null) { Log.Info("You were not granted a new access_token!"); return(null); } // The call returned successfully and you got a valid access_token. string token = bearer.Data.token_type + " " + bearer.Data.access_token; return(bearer.Data.access_token); } catch (Exception ex) { throw ex; } }
private async Task <bool> IsAccountAdmin(string hubId, Credentials credentials) { UserProfileApi userApi = new UserProfileApi(); userApi.Configuration.AccessToken = credentials.TokenInternal; dynamic profile = await userApi.GetUserProfileAsync(); // 2-legged account:read token TwoLeggedApi oauth = new TwoLeggedApi(); dynamic bearer = await oauth.AuthenticateAsync(Config.GetAppSetting("FORGE_CLIENT_ID"), Config.GetAppSetting("FORGE_CLIENT_SECRET"), "client_credentials", new Scope[] { Scope.AccountRead }); RestClient client = new RestClient(Config.BaseUrl); RestRequest thisUserRequest = new RestRequest("/hq/v1/accounts/{account_id}/users/search?email={email}&limit=1", RestSharp.Method.GET); thisUserRequest.AddParameter("account_id", hubId.Replace("b.", string.Empty), ParameterType.UrlSegment); thisUserRequest.AddParameter("email", profile.emailId, ParameterType.UrlSegment); thisUserRequest.AddHeader("Authorization", "Bearer " + bearer.access_token); IRestResponse thisUserResponse = await client.ExecuteTaskAsync(thisUserRequest); dynamic thisUser = JArray.Parse(thisUserResponse.Content); string role = thisUser[0].role; return(role == "account_admin"); }
public async Task <JObject> CreateProjectAsync(string hubId, [FromBody] JObject data) { string accountId = hubId.Replace("b.", string.Empty); // 2-legged account:read token TwoLeggedApi oauth = new TwoLeggedApi(); dynamic bearer = await oauth.AuthenticateAsync(Credentials.GetAppSetting("FORGE_CLIENT_ID"), Credentials.GetAppSetting("FORGE_CLIENT_SECRET"), "client_credentials", new Scope[] { Scope.AccountRead, Scope.AccountWrite }); Credentials credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies); if (!await IsAccountAdmin(hubId, bearer.access_token, credentials)) { return(null); } RestClient client = new RestClient(BASE_URL); RestRequest requestCreateProject = new RestRequest("/hq/v1/accounts/{account_id}/projects", RestSharp.Method.POST); requestCreateProject.AddParameter("account_id", accountId, ParameterType.UrlSegment); requestCreateProject.AddParameter("application/json", Newtonsoft.Json.JsonConvert.SerializeObject(data), ParameterType.RequestBody); requestCreateProject.AddHeader("Authorization", "Bearer " + bearer.access_token); IRestResponse response = await client.ExecuteTaskAsync(requestCreateProject); return(JObject.Parse(response.Content)); }
private async Task <JObject> Get2LeggedTokenAsync(Scope[] scopes) { TwoLeggedApi oauth = new TwoLeggedApi(); string grantType = "client_credentials"; dynamic bearer = await oauth.AuthenticateAsync(ClientId, ClientSecret, grantType, scopes); return(JObject.FromObject(bearer)); }
private static async Task <dynamic> Get2LeggedTokenAsync(Scope[] scopes) { TwoLeggedApi oauth = new TwoLeggedApi(); string grantType = "client_cridentials"; dynamic bearer = await oauth.AuthenticateAsync(GetAppSetting(clientId), GetAppSetting(secret), grantType, scopes); return(bearer); }
public static async Task <dynamic> Get2LeggedTokenAsync(Scope[] scopes) { TwoLeggedApi apiInstance = new TwoLeggedApi(); string grantType = "client_credentials"; dynamic bearer = await apiInstance.AuthenticateAsync("BmNe4PXIAdDC3DfrWqX4jaaKcUVLHzGs", "FvjXbdJbWzQUjkL0", grantType, scopes); return(bearer); }
public static async Task <dynamic> Get2LeggedTokenAsync(Scope[] scopes) { TwoLeggedApi apiInstance = new TwoLeggedApi(); string grantType = "client_credentials"; dynamic bearer = await apiInstance.AuthenticateAsync(Config.FORGE_CLIENT_ID, Config.FORGE_CLIENT_SECRET, grantType, scopes); return(bearer); }
/// <summary> /// Get the access token from Autodesk /// </summary> private static async Task <dynamic> Get2LeggedTokenAsync(Scope[] scopes) { TwoLeggedApi oauth = new TwoLeggedApi(); string grantType = "client_credentials"; string clientId = GetAppSetting("FORGE_CLIENT_ID"); string clientSecret = GetAppSetting("FORGE_CLIENT_SECRET"); dynamic bearer = await oauth.AuthenticateAsync(clientId, clientSecret, grantType, scopes); return(bearer); }
public async Task <bool> GetIsAccountAdmin(string hubId) { Credentials credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies); // 2-legged account:read token TwoLeggedApi oauth = new TwoLeggedApi(); dynamic bearer = await oauth.AuthenticateAsync(Credentials.GetAppSetting("FORGE_CLIENT_ID"), Credentials.GetAppSetting("FORGE_CLIENT_SECRET"), "client_credentials", new Scope[] { Scope.AccountRead }); return(await IsAccountAdmin(hubId, bearer.access_token, credentials)); }
// Initialize the 2-legged OAuth 2.0 client, and optionally set specific scopes. private static void initializeOAuth() { // You must provide at least one valid scope Scope[] scopes = new Scope[] { Scope.DataRead, Scope.DataWrite, Scope.BucketCreate, Scope.BucketRead }; // TLS enforce due to https://forge.autodesk.com/ja/node/1098 System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; oauth2TwoLegged = new TwoLeggedApi(); twoLeggedCredentials = oauth2TwoLegged.AuthenticateAsync(FORGE_CLIENT_ID, FORGE_CLIENT_SECRET, oAuthConstants.CLIENT_CREDENTIALS, scopes).Result; objectsApi.Configuration.AccessToken = twoLeggedCredentials.access_token; }
/// <summary> /// Get the access token from Autodesk. /// </summary> /// <param name="scopes">The scopes<see cref="Scope[]"/>.</param> /// <returns>The <see cref="Task{dynamic}"/>.</returns> public async Task <dynamic> Get2LeggedTokenAsync(Scope[] scopes) { TwoLeggedApi oauth = new TwoLeggedApi(); string grantType = "client_credentials"; dynamic bearer = await oauth.AuthenticateAsync(config.ClientId, config.ClientSecret, grantType, scopes); return(bearer); }
public async Task <string> GetToken() { TwoLeggedApi oauthApi = new TwoLeggedApi(); dynamic bearer = await oauthApi.AuthenticateAsync( "mUAnGJsDnZAALOTZdNGDcV68ReVuscXO", "coCCQ99xevcPpLjD", "client_credentials", new Scope[] { Scope.DataRead }); return((string)bearer.access_token); }
/** * Initialize the 2-legged OAuth 2.0 client, and optionally set specific scopes. */ private static void initializeOAuth() { // You must provide at least one valid scope Scope[] scopes = new Scope[] { Scope.DataRead, Scope.DataWrite, Scope.BucketCreate, Scope.BucketRead }; oauth2TwoLegged = new TwoLeggedApi(); twoLeggedCredentials = oauth2TwoLegged.Authenticate(FORGE_CLIENT_ID, FORGE_CLIENT_SECRET, oAuthConstants.CLIENT_CREDENTIALS, scopes); bucketsApi.Configuration.AccessToken = twoLeggedCredentials.access_token; objectsApi.Configuration.AccessToken = twoLeggedCredentials.access_token; derivativesApi.Configuration.AccessToken = twoLeggedCredentials.access_token; }
/// <summary> /// Fetches the token based on the scope argument /// </summary> /// <returns>token</returns> private async static Task <dynamic> Get2LeggedTokenAsync(Scope[] scopes) { TwoLeggedApi oauth = new TwoLeggedApi(); string grantType = "client_credentials"; dynamic bearer = await oauth.AuthenticateAsync( ConsumerKey, ConsumerSecret, grantType, scopes); return(bearer); }
public static async Task <IRestResponse> GetUsersAsync(string accountId, Region region) { TwoLeggedApi oauth = new TwoLeggedApi(); dynamic bearer = await oauth.AuthenticateAsync(Credentials.GetAppSetting("FORGE_CLIENT_ID"), Credentials.GetAppSetting("FORGE_CLIENT_SECRET"), "client_credentials", new Scope[] { Scope.AccountRead, Scope.DataRead }); RestClient client = new RestClient(BASE_URL); RestRequest request = new RestRequest("/hq/v1/" + region.Resource + "/{account_id}/users?limit=100", RestSharp.Method.GET); request.AddParameter("account_id", accountId.Replace("b.", string.Empty), ParameterType.UrlSegment); request.AddHeader("Authorization", "Bearer " + bearer.access_token); return(await client.ExecuteTaskAsync(request)); }
/// <summary> /// Get the access token from Autodesk /// </summary> private static async Task <dynamic> Get2LeggedTokenAsync(Scope[] scopes) { TwoLeggedApi oauth = new TwoLeggedApi(); string grantType = "client_credentials"; dynamic bearer = await oauth.AuthenticateAsync( Environment.GetEnvironmentVariable("FORGE_CLIENT_ID"), Environment.GetEnvironmentVariable("FORGE_CLIENT_SECRET"), grantType, scopes); return(bearer); }
private async Task <IRestResponse> GetProjectUsers(string accountId, string projectId, Nullable <int> pageOffset = null, Nullable <int> pageLimit = null) { TwoLeggedApi oauth = new TwoLeggedApi(); dynamic bearer = await oauth.AuthenticateAsync(Credentials.GetAppSetting("FORGE_CLIENT_ID"), Credentials.GetAppSetting("FORGE_CLIENT_SECRET"), "client_credentials", new Scope[] { Scope.AccountRead }); RestClient client = new RestClient(BASE_URL); RestRequest request = new RestRequest("/bim360/admin/v1/projects/{project_id}/users", RestSharp.Method.GET); request.AddParameter("project_id", projectId.Replace("b.", string.Empty), ParameterType.UrlSegment); request.AddHeader("Authorization", "Bearer " + bearer.access_token); return(await client.ExecuteTaskAsync(request)); }
public async Task <HttpResponseMessage> GetToken() { TwoLeggedApi oauthApi = new TwoLeggedApi(); dynamic bearer = await oauthApi.AuthenticateAsync(WebConfigurationManager.AppSettings["FORGE_CLIENT_ID"], WebConfigurationManager.AppSettings["FORGE_CLIENT_SECRET"], "client_credentials", new Scope[] { Scope.DataRead } ); var response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StringContent(bearer.access_token, System.Text.Encoding.UTF8, "text/plain"); return(response); }
public static async Task <string> GetAccessToken(string clientId, string clientSecret) { TwoLeggedApi oauth = new TwoLeggedApi(); dynamic reply = await oauth.AuthenticateAsync( clientId, clientSecret, oAuthConstants.CLIENT_CREDENTIALS, new Scope[] { Scope.CodeAll }); string accessToken = reply.access_token; Console.WriteLine(accessToken); return(accessToken); }
public async Task <JArray> GetQualityIssuesAsync(string hubId, string projectId) { Credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies); if (Credentials == null) { return(null); } TwoLeggedApi oauth = new TwoLeggedApi(); dynamic bearer = await oauth.AuthenticateAsync(Credentials.GetAppSetting("FORGE_CLIENT_ID"), Credentials.GetAppSetting("FORGE_CLIENT_SECRET"), "client_credentials", new Scope[] { Scope.AccountRead }); JArray users = await GetUsers(hubId, bearer.access_token); JArray issues = new JArray(); dynamic response = null; int offset = 0; do { response = await GetResourceAsync(await GetContainerAsync(hubId, projectId), "quality-issues", offset); issues.Merge(response.data); offset += 50; } while (!string.IsNullOrEmpty((string)response.links.next)); foreach (dynamic issue in issues) { if (issue.attributes.created_by != null) { issue.attributes.owner = GetUserById(users, (string)issue.attributes.owner); } if (issue.attributes.created_by != null) { issue.attributes.created_by = GetUserById(users, (string)issue.attributes.created_by); } if (issue.attributes.created_by != null) { issue.attributes.assigned_to = GetUserById(users, (string)issue.attributes.assigned_to); } if (issue.attributes.created_by != null) { issue.attributes.answered_by = GetUserById(users, (string)issue.attributes.answered_by); } } return(issues); }
public Auth() { api = new TwoLeggedApi(); scopes = new Scope[] { Scope.BucketCreate, Scope.BucketDelete, Scope.BucketRead, Scope.DataCreate, Scope.DataRead, Scope.DataWrite, Scope.CodeAll }; this.clientID = GetEnvVariable("FORGE_CLIENT_ID"); this.clientSecret = GetEnvVariable("FORGE_CLIENT_SECRET"); }
private async Task <ApiResponse <dynamic> > oauthExecAsync() { try { _2LEGGED = ""; TwoLeggedApi _twoLeggedApi = new TwoLeggedApi(); ApiResponse <dynamic> bearer = await _twoLeggedApi.AuthenticateAsyncWithHttpInfo( FORGE_CLIENT_ID, FORGE_CLIENT_SECRET, oAuthConstants.CLIENT_CREDENTIALS, _scope); httpErrorHandler(bearer, "Failed to get your token"); _2LEGGED = bearer.Data.access_token; return(bearer); } catch (Exception ex) { MessageBox.Show("Exception when calling TwoLeggedApi.AuthenticateAsyncWithHttpInfo : " + ex.Message, APP_NAME, MessageBoxButton.OK, MessageBoxImage.Error); return(null); } }