public void TestAsyncOperationWithEmptyPayload() { var tokenCredentials = new TokenCredentials("123", "abc"); var handler = new PlaybackTestHandler(MockAsyncOperaionWithEmptyBody()); var fakeClient = new RedisManagementClient(tokenCredentials, handler); fakeClient.LongRunningOperationInitialTimeout = fakeClient.LongRunningOperationRetryTimeout = 0; var error = Assert.Throws<CloudException>(() => fakeClient.RedisOperations.Delete("rg", "redis", "1234")); Assert.Equal("The response from long running operation does not contain a body.", error.Message); }
public void TokenCloudCredentialAddsHeader() { var tokenCredentials = new TokenCredentials("abc"); var handler = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; var fakeClient = new FakeServiceClientWithCredentials(tokenCredentials); fakeClient = new FakeServiceClientWithCredentials(tokenCredentials, handler); fakeClient.DoStuff().Wait(); Assert.Equal("Bearer", handler.RequestHeaders.Authorization.Scheme); Assert.Equal("abc", handler.RequestHeaders.Authorization.Parameter); }
public void TestCreateOrUpdateWithAsyncHeader() { var tokenCredentials = new TokenCredentials("123", "abc"); var handler = new PlaybackTestHandler(MockCreateOrUpdateWithTwoTries()); var fakeClient = new RedisManagementClient(tokenCredentials, handler); fakeClient.LongRunningOperationInitialTimeout = fakeClient.LongRunningOperationRetryTimeout = 0; fakeClient.RedisOperations.CreateOrUpdate("rg", "redis", new RedisCreateOrUpdateParameters(), "1234"); Assert.Equal(HttpMethod.Put, handler.Requests[0].Method); Assert.Equal("https://management.azure.com/subscriptions/1234/resourceGroups/rg/providers/Microsoft.Cache/Redis/redis", handler.Requests[0].RequestUri.ToString()); Assert.Equal(HttpMethod.Get, handler.Requests[1].Method); Assert.Equal("http://custom/status", handler.Requests[1].RequestUri.ToString()); Assert.Equal(HttpMethod.Get, handler.Requests[2].Method); Assert.Equal("https://management.azure.com/subscriptions/1234/resourceGroups/rg/providers/Microsoft.Cache/Redis/redis", handler.Requests[2].RequestUri.ToString()); }
public async Task <IHttpActionResult> Get(string username, string roles) { var result = new EmbedConfig(); try { result = new EmbedConfig { Username = username, Roles = roles }; var error = GetWebConfigErrors(); if (error != null) { result.ErrorMessage = error; return(Ok(AirFusion.WindEdition.API.ResponseResult <EmbedConfig> .GetResult(result))); } var credential = new UserPasswordCredential(Username, Password); // Authenticate using created credentials var authenticationContext = new AuthenticationContext(AuthorityUrl); var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ApplicationId, credential); if (authenticationResult == null) { result.ErrorMessage = "Authentication Failed."; return(Ok(AirFusion.WindEdition.API.ResponseResult <EmbedConfig> .GetResult(result))); } var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer"); using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials)) { // Get a list of reports. var reports = await client.Reports.GetReportsInGroupAsync(WorkspaceId); // No reports retrieved for the given workspace. if (reports.Value.Count() == 0) { result.ErrorMessage = "No reports were found in the workspace"; return(Ok(AirFusion.WindEdition.API.ResponseResult <EmbedConfig> .GetResult(result))); } Report report; if (string.IsNullOrWhiteSpace(ReportId)) { // Get the first report in the workspace. report = reports.Value.FirstOrDefault(); } else { report = reports.Value.FirstOrDefault(r => r.Id == ReportId); } if (report == null) { result.ErrorMessage = "No report with the given ID was found in the workspace. Make sure ReportId is valid."; return(Ok(AirFusion.WindEdition.API.ResponseResult <EmbedConfig> .GetResult(result))); } var datasets = await client.Datasets.GetDatasetByIdInGroupAsync(WorkspaceId, report.DatasetId); result.IsEffectiveIdentityRequired = datasets.IsEffectiveIdentityRequired; result.IsEffectiveIdentityRolesRequired = datasets.IsEffectiveIdentityRolesRequired; GenerateTokenRequest generateTokenRequestParameters; // This is how you create embed token with effective identities if (!string.IsNullOrWhiteSpace(username)) { var rls = new EffectiveIdentity(username, new List <string> { report.DatasetId }); if (!string.IsNullOrWhiteSpace(roles)) { var rolesList = new List <string>(); rolesList.AddRange(roles.Split(',')); rls.Roles = rolesList; } // Generate Embed Token with effective identities. generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view", identities: new List <EffectiveIdentity> { rls }); } else { // Generate Embed Token for reports without effective identities. generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view"); } var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(WorkspaceId, report.Id, generateTokenRequestParameters); if (tokenResponse == null) { result.ErrorMessage = "Failed to generate embed token."; return(Ok(AirFusion.WindEdition.API.ResponseResult <EmbedConfig> .GetResult(result))); } // Generate Embed Configuration. result.EmbedToken = tokenResponse; result.EmbedUrl = report.EmbedUrl; result.Id = report.Id; var json = new JavaScriptSerializer().Serialize(result); return(Ok(AirFusion.WindEdition.API.ResponseResult <EmbedConfig> .GetResult(result))); } } catch (Exception ex) { result.ErrorMessage = "Error Occured"; } return(Ok(AirFusion.WindEdition.API.ResponseResult <EmbedConfig> .GetResult(result))); }
private void SetupDynamics(IServiceCollection services) { string dynamicsOdataUri = Configuration["DYNAMICS_ODATA_URI"]; string aadTenantId = Configuration["DYNAMICS_AAD_TENANT_ID"]; string serverAppIdUri = Configuration["DYNAMICS_SERVER_APP_ID_URI"]; string clientKey = Configuration["DYNAMICS_CLIENT_KEY"]; string clientId = Configuration["DYNAMICS_CLIENT_ID"]; string ssgUsername = Configuration["SSG_USERNAME"]; string ssgPassword = Configuration["SSG_PASSWORD"]; AuthenticationResult authenticationResult = null; // authenticate using ADFS. if (string.IsNullOrEmpty(ssgUsername) || string.IsNullOrEmpty(ssgPassword)) { var authenticationContext = new AuthenticationContext( "https://login.windows.net/" + aadTenantId); ClientCredential clientCredential = new ClientCredential(clientId, clientKey); var task = authenticationContext.AcquireTokenAsync(serverAppIdUri, clientCredential); task.Wait(); authenticationResult = task.Result; } services.AddTransient(new Func <IServiceProvider, IDynamicsClient>((serviceProvider) => { ServiceClientCredentials serviceClientCredentials = null; if (string.IsNullOrEmpty(ssgUsername) || string.IsNullOrEmpty(ssgPassword)) { var authenticationContext = new AuthenticationContext( "https://login.windows.net/" + aadTenantId); ClientCredential clientCredential = new ClientCredential(clientId, clientKey); var task = authenticationContext.AcquireTokenAsync(serverAppIdUri, clientCredential); task.Wait(); authenticationResult = task.Result; string token = authenticationResult.CreateAuthorizationHeader().Substring("Bearer ".Length); serviceClientCredentials = new TokenCredentials(token); } else { serviceClientCredentials = new BasicAuthenticationCredentials() { UserName = ssgUsername, Password = ssgPassword }; } IDynamicsClient client = new DynamicsClient(new Uri(Configuration["DYNAMICS_ODATA_URI"]), serviceClientCredentials); // set the native client URI if (string.IsNullOrEmpty(Configuration["DYNAMICS_NATIVE_ODATA_URI"])) { client.NativeBaseUri = new Uri(Configuration["DYNAMICS_ODATA_URI"]); } else { client.NativeBaseUri = new Uri(Configuration["DYNAMICS_NATIVE_ODATA_URI"]); } return(client); })); // add SharePoint. string sharePointServerAppIdUri = Configuration["SHAREPOINT_SERVER_APPID_URI"]; string sharePointOdataUri = Configuration["SHAREPOINT_ODATA_URI"]; string sharePointWebname = Configuration["SHAREPOINT_WEBNAME"]; string sharePointAadTenantId = Configuration["SHAREPOINT_AAD_TENANTID"]; string sharePointClientId = Configuration["SHAREPOINT_CLIENT_ID"]; string sharePointCertFileName = Configuration["SHAREPOINT_CERTIFICATE_FILENAME"]; string sharePointCertPassword = Configuration["SHAREPOINT_CERTIFICATE_PASSWORD"]; string sharePointNativeBaseURI = Configuration["SHAREPOINT_NATIVE_BASE_URI"]; if (!string.IsNullOrEmpty(sharePointOdataUri)) { services.AddTransient <SharePointFileManager>(_ => new SharePointFileManager(sharePointServerAppIdUri, sharePointOdataUri, sharePointWebname, sharePointAadTenantId, sharePointClientId, sharePointCertFileName, sharePointCertPassword, ssgUsername, ssgPassword, sharePointNativeBaseURI)); } // add BCeID Web Services string bceidUrl = Configuration["BCEID_SERVICE_URL"]; string bceidSvcId = Configuration["BCEID_SERVICE_SVCID"]; string bceidUserid = Configuration["BCEID_SERVICE_USER"]; string bceidPasswd = Configuration["BCEID_SERVICE_PASSWD"]; services.AddTransient <BCeIDBusinessQuery>(_ => new BCeIDBusinessQuery(bceidSvcId, bceidUserid, bceidPasswd, bceidUrl)); }
static async Task <Tuple <int, HttpResponseMessage, string> > GetDynamicsHttpClientNew(IConfiguration configuration, String model, String endPointName) { Console.WriteLine(DateTime.Now + " In GetDynamicsHttpClientNew"); var builder = new ConfigurationBuilder() .AddEnvironmentVariables() .AddUserSecrets <Program>(); // must also define a project guid for secrets in the .cspro – add tag <UserSecretsId> containing a guid var Configuration = builder.Build(); Console.WriteLine(DateTime.Now + " Build Configuration"); string dynamicsOdataUri = Configuration["DYNAMICS_ODATA_URI"]; // Dynamics ODATA endpoint string dynamicsJobName = endPointName; // Configuration["DYNAMICS_JOB_NAME"]; // Dynamics Job Name if (string.IsNullOrEmpty(dynamicsOdataUri)) { throw new Exception("Configuration setting DYNAMICS_ODATA_URI is blank."); } // Cloud - x.dynamics.com string aadTenantId = Configuration["DYNAMICS_AAD_TENANT_ID"]; // Cloud AAD Tenant ID string serverAppIdUri = Configuration["DYNAMICS_SERVER_APP_ID_URI"]; // Cloud Server App ID URI string appRegistrationClientKey = Configuration["DYNAMICS_APP_REG_CLIENT_KEY"]; // Cloud App Registration Client Key string appRegistrationClientId = Configuration["DYNAMICS_APP_REG_CLIENT_ID"]; // Cloud App Registration Client Id // One Premise ADFS (2016) string adfsOauth2Uri = Configuration["ADFS_OAUTH2_URI"]; // ADFS OAUTH2 URI - usually /adfs/oauth2/token on STS string applicationGroupResource = Configuration["DYNAMICS_APP_GROUP_RESOURCE"]; // ADFS 2016 Application Group resource (URI) string applicationGroupClientId = Configuration["DYNAMICS_APP_GROUP_CLIENT_ID"]; // ADFS 2016 Application Group Client ID string applicationGroupSecret = Configuration["DYNAMICS_APP_GROUP_SECRET"]; // ADFS 2016 Application Group Secret string serviceAccountUsername = Configuration["DYNAMICS_USERNAME"]; // Service account username string serviceAccountPassword = Configuration["DYNAMICS_PASSWORD"]; // Service account password // API Gateway to NTLM user. This is used in v8 environments. Note that the SSG Username and password are not the same as the NTLM user. string ssgUsername = Configuration["SSG_USERNAME"]; // BASIC authentication username string ssgPassword = Configuration["SSG_PASSWORD"]; // BASIC authentication password Console.WriteLine(DateTime.Now + " Variables have been set"); ServiceClientCredentials serviceClientCredentials = null; if (!string.IsNullOrEmpty(appRegistrationClientId) && !string.IsNullOrEmpty(appRegistrationClientKey) && !string.IsNullOrEmpty(serverAppIdUri) && !string.IsNullOrEmpty(aadTenantId)) // Cloud authentication - using an App Registration's client ID, client key. Add the App Registration to Dynamics as an Application User. { Console.WriteLine(DateTime.Now + " Trying Cloud Authentication"); var authenticationContext = new AuthenticationContext( "https://login.windows.net/" + aadTenantId); ClientCredential clientCredential = new ClientCredential(appRegistrationClientId, appRegistrationClientKey); var task = authenticationContext.AcquireTokenAsync(serverAppIdUri, clientCredential); task.Wait(); var authenticationResult = task.Result; string token = authenticationResult.CreateAuthorizationHeader().Substring("Bearer ".Length); serviceClientCredentials = new TokenCredentials(token); } if (!string.IsNullOrEmpty(adfsOauth2Uri) && !string.IsNullOrEmpty(applicationGroupResource) && !string.IsNullOrEmpty(applicationGroupClientId) && !string.IsNullOrEmpty(applicationGroupSecret) && !string.IsNullOrEmpty(serviceAccountUsername) && !string.IsNullOrEmpty(serviceAccountPassword)) // ADFS 2016 authentication - using an Application Group Client ID and Secret, plus service account credentials. { Console.WriteLine(DateTime.Now + " Trying ADFS Authentication"); // create a new HTTP client that is just used to get a token. var stsClient = new HttpClient(); //stsClient.DefaultRequestHeaders.Add("x-client-SKU", "PCL.CoreCLR"); //stsClient.DefaultRequestHeaders.Add("x-client-Ver", "5.1.0.0"); //stsClient.DefaultRequestHeaders.Add("x-ms-PKeyAuth", "1.0"); stsClient.DefaultRequestHeaders.Add("client-request-id", Guid.NewGuid().ToString()); stsClient.DefaultRequestHeaders.Add("return-client-request-id", "true"); stsClient.DefaultRequestHeaders.Add("Accept", "application/json"); // Construct the body of the request var pairs = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("resource", applicationGroupResource), new KeyValuePair <string, string>("client_id", applicationGroupClientId), new KeyValuePair <string, string>("client_secret", applicationGroupSecret), new KeyValuePair <string, string>("username", serviceAccountUsername), new KeyValuePair <string, string>("password", serviceAccountPassword), new KeyValuePair <string, string>("scope", "openid"), new KeyValuePair <string, string>("response_mode", "form_post"), new KeyValuePair <string, string>("grant_type", "password") }; Console.WriteLine(DateTime.Now + " Set ADFS variables and headers"); // This will also set the content type of the request var content = new FormUrlEncodedContent(pairs); Console.WriteLine(DateTime.Now + " content: " + content); // send the request to the ADFS server Console.WriteLine(DateTime.Now + " About to send request to ADFS"); var _httpResponse = stsClient.PostAsync(adfsOauth2Uri, content).GetAwaiter().GetResult(); var _responseContent = _httpResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult(); // response should be in JSON format. try { Dictionary <string, string> result = JsonConvert.DeserializeObject <Dictionary <string, string> >(_responseContent); string token = result["access_token"]; Console.WriteLine(DateTime.Now + " Got a token"); // set the bearer token. serviceClientCredentials = new TokenCredentials(token); // Code to perform Scheduled task var client = new HttpClient(); client.DefaultRequestHeaders.Add("x-client-SKU", "PCL.CoreCLR"); client.DefaultRequestHeaders.Add("x-client-Ver", "5.1.0.0"); client.DefaultRequestHeaders.Add("x-ms-PKeyAuth", "1.0"); client.DefaultRequestHeaders.Add("client-request-id", Guid.NewGuid().ToString()); client.DefaultRequestHeaders.Add("return-client-request-id", "true"); client.DefaultRequestHeaders.Add("Accept", "application/json"); client = new HttpClient(); var Authorization = $"Bearer {token}"; client.DefaultRequestHeaders.Add("Authorization", Authorization); client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0"); client.DefaultRequestHeaders.Add("OData-Version", "4.0"); client.DefaultRequestHeaders.Add("Accept", "application/json"); //client.DefaultRequestHeaders.Add("content-type", "application/json"); //client.DefaultRequestHeaders.Add("Content-Type", "application/json; charset=utf-8"); string url = dynamicsOdataUri + dynamicsJobName; Console.WriteLine(DateTime.Now + " Set full URL to speak to Dynamics: " + url); HttpRequestMessage _httpRequest = new HttpRequestMessage(HttpMethod.Post, url); _httpRequest.Content = new StringContent(model, Encoding.UTF8, "application/json"); //_httpRequest.Content = new StringContent(System.IO.File.ReadAllText(@"C:\Temp\VSD-RestSampleData3.txt"), Encoding.UTF8, "application/json"); Console.WriteLine(DateTime.Now + " Got HTTP Request ready"); var _httpResponse2 = await client.SendAsync(_httpRequest); HttpStatusCode _statusCode = _httpResponse2.StatusCode; var _responseString = _httpResponse2.ToString(); Console.WriteLine(DateTime.Now + " Got HTTP Response");//: " + _responseString); var _responseContent2 = await _httpResponse2.Content.ReadAsStringAsync(); Console.Out.WriteLine(DateTime.Now + " model: " + model); Console.Out.WriteLine(DateTime.Now + " responseString: " + _responseString); Console.Out.WriteLine(DateTime.Now + " responseContent2: " + _responseContent2); Console.WriteLine(DateTime.Now + " Exit GetDynamicsHttpClientNew"); return(new Tuple <int, HttpResponseMessage, string>((int)_statusCode, _httpResponse2, _responseContent2)); // End of scheduled task } catch (Exception e) { return(new Tuple <int, HttpResponseMessage, string>(100, null, "Error")); throw new Exception(e.Message + " " + _responseContent); } } else if (!string.IsNullOrEmpty(ssgUsername) && !string.IsNullOrEmpty(ssgPassword)) // Authenticate using BASIC authentication - used for API Gateways with BASIC authentication. Add the NTLM user associated with the API gateway entry to Dynamics as a user. { serviceClientCredentials = new BasicAuthenticationCredentials() { UserName = ssgUsername, Password = ssgPassword }; } else { throw new Exception("No configured connection to Dynamics."); } return(new Tuple <int, HttpResponseMessage, string>(100, null, "Error")); }
public void TestCreateOrUpdateNoErrorBody() { var tokenCredentials = new TokenCredentials("123", "abc"); var handler = new PlaybackTestHandler(MockCreateOrUpdateWithNoErrorBody()); var fakeClient = new RedisManagementClient(tokenCredentials, handler); fakeClient.LongRunningOperationInitialTimeout = fakeClient.LongRunningOperationRetryTimeout = 0; try { fakeClient.RedisOperations.CreateOrUpdate("rg", "redis", new RedisCreateOrUpdateParameters(), "1234"); Assert.False(true, "Expected exception was not thrown."); } catch (CloudException ex) { Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode); } }
public void TestDeleteOperationWithoutLocationHeaderInResponse() { var tokenCredentials = new TokenCredentials("123", "abc"); var handler = new PlaybackTestHandler(MockDeleteOperaionWithoutLocationHeaderInResponse()); var fakeClient = new RedisManagementClient(tokenCredentials, handler); fakeClient.LongRunningOperationInitialTimeout = fakeClient.LongRunningOperationRetryTimeout = 0; fakeClient.RedisOperations.Delete("rg", "redis", "1234"); Assert.Equal(3, handler.Requests.Count); Assert.Equal("http://custom/status", handler.Requests[1].RequestUri.ToString()); Assert.Equal("http://custom/status", handler.Requests[2].RequestUri.ToString()); }
public void CanGetUserInfoFromPatToken() { TokenClient client = null !; UmaClient umaClient = null !; string patToken = null !; string idToken = null !; string ticketId = null !; string rptToken = null !; string resourceId = null !; "Given a token client".x( () => { client = new TokenClient( TokenCredentials.FromClientCredentials("clientCredentials", "clientCredentials"), _fixture.Client, new Uri(WellKnownOpenidConfiguration)); }); "and a UMA client".x(() => { umaClient = new UmaClient(_fixture.Client, new Uri(BaseUrl)); }); "and a PAT token".x( async() => { var response = await client.GetToken( TokenRequest.FromPassword("administrator", "password", new[] { "uma_protection" })) .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result; Assert.NotNull(response); Assert.NotNull(response.Item.AccessToken); Assert.NotNull(response.Item.IdToken); patToken = response.Item.AccessToken; idToken = response.Item.IdToken; }); "and a registered resource".x( async() => { var resourceSet = new ResourceSet { Description = "Test resource", Name = "Test resource", Scopes = new[] { "read" }, Type = "Test resource" }; var response = await umaClient.AddResource(resourceSet, patToken).ConfigureAwait(false) as Option <AddResourceSetResponse> .Result; Assert.NotNull(response); resourceId = response.Item.Id; }); "and an updated authorization policy".x( async() => { var resourceSet = new ResourceSet { Id = resourceId, AuthorizationPolicies = new[] { new PolicyRule { ClientIdsAllowed = new[] { "clientCredentials" }, Scopes = new[] { "read" } } }, Description = "Test resource", Name = "Test resource", Scopes = new[] { "read" }, Type = "Test resource" }; var response = await umaClient.UpdateResource(resourceSet, patToken).ConfigureAwait(false) as Option <UpdateResourceSetResponse> .Result; Assert.NotNull(response); resourceId = response.Item.Id; }); "When getting a ticket".x( async() => { var ticketResponse = await umaClient.RequestPermission( patToken, requests: new PermissionRequest { ResourceSetId = resourceId, Scopes = new[] { "read" } }) .ConfigureAwait(false) as Option <TicketResponse> .Result; Assert.NotNull(ticketResponse); ticketId = ticketResponse.Item.TicketId; }); "and getting an RPT token".x( async() => { var rptResponse = await client.GetToken(TokenRequest.FromTicketId(ticketId, idToken)) .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result; Assert.NotNull(rptResponse); rptToken = rptResponse.Item.AccessToken; }); "then can introspect RPT token using PAT token as authentication".x( async() => { var introspectResult = await umaClient .Introspect(IntrospectionRequest.Create(rptToken, "access_token", patToken)) .ConfigureAwait(false); Assert.IsType <Option <UmaIntrospectionResponse> .Result>(introspectResult); }); }
public EmbedService() { m_tokenCredentials = null; m_embedConfig = new EmbedConfig(); m_tileEmbedConfig = new TileEmbedConfig(); }
static void Main(string[] args) { const string baseUrl = "https://api.sherweb.com/distributor/v1"; const string clientId = "your client id"; const string clientSecret = "your client secret"; const string subscriptionKey = "your subscription key"; // Optional. This should follow [RFC 7231, section 5.3.5: Accept-Language]: https://tools.ietf.org/html/rfc7231#section-5.3.5 // Example: en, en-CA;q=0.8, fr-CA;q=0.7 const string acceptLanguageHeader = null; // Get Bearer Token from Authorization API var authorizationClient = new AuthorizationService(new Uri("https://api.sherweb.com/auth")); var token = authorizationClient.TokenMethod( clientId, clientSecret, "distributor", // Scope : distributor for Distributor API "client_credentials"); // Instantiate Distributor API client using Bearer token var credentials = new TokenCredentials(token.AccessToken, "Bearer"); var distributorConfiguration = new DistributorServiceConfiguration { Uri = new Uri(baseUrl), Credentials = credentials, RetryCount = 0 }; var distributorServiceFactory = new DistributorServiceFactory(distributorConfiguration, new SubscriptionKeyHandler(subscriptionKey)); var distributorClient = distributorServiceFactory.Create(); PayableCharges payableCharges = null; try { payableCharges = distributorClient.GetPayableCharges(acceptLanguage: acceptLanguageHeader); } catch (HttpOperationException exception) { // ProblemDetails returned by the API are handled and converted to a HttpOperationException in the ProblemDetailsHandler of the API Client // https://github.com/sherweb/Public-Apis/blob/7bd9a0ecc37f0fbe3d9085c3e911ade3ca9a0c66/NugetPackagesSourceCode/Sherweb.Apis.Distributor/DelegatingHandlers/OnProblemDetailsHandler.cs Console.WriteLine($"{nameof(exception.Message)}={exception.Message}"); return; } Console.WriteLine($"{nameof(payableCharges.PeriodFrom)}={payableCharges.PeriodFrom}"); Console.WriteLine($"{nameof(payableCharges.PeriodTo)}={payableCharges.PeriodTo}"); foreach (var charge in payableCharges.Charges) { var customerDisplayName = charge.Tags.SingleOrDefault(x => x.Name == "CustomerDisplayName")?.Value; Console.WriteLine("-------------------------------------------------"); Console.WriteLine($"{nameof(customerDisplayName)}={customerDisplayName}"); Console.WriteLine($"{nameof(charge.ProductName)}={charge.ProductName}"); Console.WriteLine($"{nameof(charge.ChargeName)}={charge.ChargeName}"); Console.WriteLine($"{nameof(charge.Quantity)}={charge.Quantity}"); Console.WriteLine($"{nameof(charge.SubTotal)}={charge.SubTotal}"); } }
private async void buttonPickupAccount_Click(object sender, EventArgs e) { AddAMSAccount1 addaccount1 = new AddAMSAccount1(); if (addaccount1.ShowDialog() == DialogResult.OK) { if (addaccount1.SelectedMode == AddAccountMode.BrowseSubscriptions) { environment = addaccount1.GetEnvironment(); AuthenticationContext authContext = new AuthenticationContext( // authority: environment.Authority, authority: environment.AADSettings.AuthenticationEndpoint.ToString() + "common", validateAuthority: true ); AuthenticationResult accessToken; try { accessToken = await authContext.AcquireTokenAsync( resource : environment.AADSettings.TokenAudience.ToString(), clientId : environment.ClientApplicationId, redirectUri : new Uri("urn:ietf:wg:oauth:2.0:oob"), parameters : new PlatformParameters(addaccount1.SelectUser ? PromptBehavior.SelectAccount : PromptBehavior.Auto) ); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } TokenCredentials credentials = new TokenCredentials(accessToken.AccessToken, "Bearer"); SubscriptionClient subscriptionClient = new SubscriptionClient(environment.ArmEndpoint, credentials); Microsoft.Rest.Azure.IPage <Microsoft.Azure.Management.ResourceManager.Models.Subscription> subscriptions = subscriptionClient.Subscriptions.List(); // tenants browsing myTenants tenants = new myTenants(); string URL = environment.ArmEndpoint + "tenants?api-version=2017-08-01"; HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Remove("Authorization"); client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken.AccessToken); HttpResponseMessage response = await client.GetAsync(URL); if (response.IsSuccessStatusCode) { string str = await response.Content.ReadAsStringAsync(); tenants = (myTenants)JsonConvert.DeserializeObject(str, typeof(myTenants)); } AddAMSAccount2Browse addaccount2 = new AddAMSAccount2Browse(credentials, subscriptions, environment, tenants.value, new PlatformParameters(addaccount1.SelectUser ? PromptBehavior.SelectAccount : PromptBehavior.Auto)); if (addaccount2.ShowDialog() == DialogResult.OK) { // Getting Media Services accounts... AzureMediaServicesClient mediaServicesClient = new AzureMediaServicesClient(environment.ArmEndpoint, credentials); CredentialsEntryV3 entry = new CredentialsEntryV3(addaccount2.selectedAccount, environment, addaccount1.SelectUser ? PromptBehavior.SelectAccount : PromptBehavior.Auto, false, addaccount2.selectedTenantId, false ); CredentialList.MediaServicesAccounts.Add(entry); AddItemToListviewAccounts(entry); SaveCredentialsToSettings(); } else { return; } } // Get info from the Azure CLI JSON else if (addaccount1.SelectedMode == AddAccountMode.FromAzureCliJson) { string example = @"{ ""AadClientId"": ""00000000-0000-0000-0000-000000000000"", ""AadEndpoint"": ""https://login.microsoftonline.com"", ""AadSecret"": ""00000000-0000-0000-0000-000000000000"", ""AadTenantId"": ""00000000-0000-0000-0000-000000000000"", ""AccountName"": ""amsaccount"", ""ArmAadAudience"": ""https://management.core.windows.net/"", ""ArmEndpoint"": ""https://management.azure.com/"", ""Region"": ""West Europe"", ""ResourceGroup"": ""amsResourceGroup"", ""SubscriptionId"": ""00000000-0000-0000-0000-000000000000"" }"; EditorXMLJSON form = new EditorXMLJSON("Enter the JSON output of Azure Cli Service Principal creation (az ams account sp create)", example, true, false, true, "The Service Principal secret is stored encrypted in the application settings."); if (form.ShowDialog() == DialogResult.OK) { JsonFromAzureCli json = null; try { json = (JsonFromAzureCli)JsonConvert.DeserializeObject(form.TextData, typeof(JsonFromAzureCli)); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error reading the json", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } string resourceId = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Media/mediaservices/{2}", json.SubscriptionId, json.ResourceGroup, json.AccountName); string AADtenantId = json.AadTenantId; ActiveDirectoryServiceSettings aadSettings = new ActiveDirectoryServiceSettings() { AuthenticationEndpoint = json.AadEndpoint, TokenAudience = json.ArmAadAudience, ValidateAuthority = true }; AzureEnvironment env = new AzureEnvironment(AzureEnvType.Custom) { AADSettings = aadSettings, ArmEndpoint = json.ArmEndpoint }; CredentialsEntryV3 entry = new CredentialsEntryV3( new SubscriptionMediaService(resourceId, json.AccountName, null, null, json.Region), env, PromptBehavior.Auto, true, AADtenantId, false ) { ADSPClientId = json.AadClientId, ClearADSPClientSecret = json.AadSecret }; CredentialList.MediaServicesAccounts.Add(entry); AddItemToListviewAccounts(entry); SaveCredentialsToSettings(); } else { return; } } else if (addaccount1.SelectedMode == AddAccountMode.ManualEntry) { AddAMSAccount2Manual form = new AddAMSAccount2Manual(); if (form.ShowDialog() == DialogResult.OK) { string accountnamecc = form.textBoxAMSResourceId.Text.Split('/').Last(); CredentialsEntryV3 entry = new CredentialsEntryV3( new SubscriptionMediaService(form.textBoxAMSResourceId.Text, accountnamecc, null, null, form.textBoxLocation.Text), addaccount1.GetEnvironment(), PromptBehavior.Auto, form.radioButtonAADServicePrincipal.Checked, form.textBoxAADtenantId.Text, true ); CredentialList.MediaServicesAccounts.Add(entry); AddItemToListviewAccounts(entry); SaveCredentialsToSettings(); } else { return; } } } }
static async Task MainAsync() { // https://msdn.microsoft.com/en-us/library/azure/dn790557.aspx#bk_portal string token = await GetAuthorizationHeaderAsync().ConfigureAwait(false); TokenCredentials creds = new TokenCredentials(token); ServiceBusManagementClient client = new ServiceBusManagementClient(creds) { SubscriptionId = subscriptionId }; //// 1. Create Primary Namespace (optional) var namespaceParams = new SBNamespace { Location = "South Central US", Sku = new SBSku { Name = SkuName.Premium, Capacity = 1 } }; var namespace1 = await client.Namespaces.CreateOrUpdateAsync(resourceGroupName, geoDRPrimaryNS, namespaceParams) .ConfigureAwait(false); //// 2. Create Secondary Namespace (optional if you already have an empty namespace available) var namespaceParams2 = new SBNamespace { Location = "North Central US", Sku = new SBSku { Name = SkuName.Premium, Capacity = 1 } }; //// If you re-run this program while namespaces are still paired this operation will fail with a bad request. //// this is because we block all updates on secondary namespaces once it is paired var namespace2 = await client.Namespaces.CreateOrUpdateAsync(resourceGroupName, geoDRSecondaryNS, namespaceParams2) .ConfigureAwait(false); // 3. Pair the namespaces to enable DR. ArmDisasterRecovery drStatus = await client.DisasterRecoveryConfigs.CreateOrUpdateAsync( resourceGroupName, geoDRPrimaryNS, alias, new ArmDisasterRecovery { PartnerNamespace = geoDRSecondaryNS }) .ConfigureAwait(false); while (drStatus.ProvisioningState != ProvisioningStateDR.Succeeded) { Console.WriteLine("Waiting for DR to be setup. Current State: " + drStatus.ProvisioningState); drStatus = client.DisasterRecoveryConfigs.Get( resourceGroupName, geoDRPrimaryNS, alias); Thread.CurrentThread.Join(TimeSpan.FromSeconds(30)); } await client.Topics.CreateOrUpdateAsync(resourceGroupName, geoDRPrimaryNS, "myTopic", new SBTopic()) .ConfigureAwait(false); await client.Subscriptions.CreateOrUpdateAsync(resourceGroupName, geoDRPrimaryNS, "myTopic", "myTopic-Sub1", new SBSubscription()) .ConfigureAwait(false); // sleeping to allow metadata to sync across primary and secondary await Task.Delay(TimeSpan.FromSeconds(60)); // 6. Failover. Note that this Failover operations is ALWAYS run against the secondary ( because primary might be down at time of failover ) // client.DisasterRecoveryConfigs.FailOver(resourceGroupName, geoDRSecondaryNS, alias); // other possible DR operations // 7. Break Pairing // client.DisasterRecoveryConfigs.BreakPairing(resourceGroupName, geoDRPrimaryNS, alias); // 8. Delete DR config (alias) // note that this operation needs to run against the namespace that the alias is currently pointing to // client.DisasterRecoveryConfigs.Delete(resourceGroupName, geoDRPrimaryNS, alias); }
public async Task <ActionResult> EmbedReport(string username, string roles) { var result = new EmbedConfig(); try { result = new EmbedConfig { Username = username, Roles = roles }; var error = GetWebConfigErrors(); if (error != null) { result.ErrorMessage = error; return(View(result)); } // Create a user password cradentials. var credential = new UserPasswordCredential(Username, Password); // Authenticate using created credentials var authenticationContext = new AuthenticationContext(AuthorityUrl); var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ApplicationId, credential); if (authenticationResult == null) { result.ErrorMessage = "Authentication Failed."; return(View(result)); } var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer"); // Create a Power BI Client object. It will be used to call Power BI APIs. using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials)) { // Get a list of reports. var reports = await client.Reports.GetReportsInGroupAsync(WorkspaceId); // No reports retrieved for the given workspace. if (reports.Value.Count() == 0) { result.ErrorMessage = "No reports were found in the workspace"; return(View(result)); } Report report; if (string.IsNullOrWhiteSpace(ReportId)) { // Get the first report in the workspace. report = reports.Value.FirstOrDefault(); } else { report = reports.Value.FirstOrDefault(r => r.Id == ReportId); } if (report == null) { result.ErrorMessage = "No report with the given ID was found in the workspace. Make sure ReportId is valid."; return(View(result)); } var datasets = await client.Datasets.GetDatasetByIdInGroupAsync(WorkspaceId, report.DatasetId); result.IsEffectiveIdentityRequired = datasets.IsEffectiveIdentityRequired; result.IsEffectiveIdentityRolesRequired = datasets.IsEffectiveIdentityRolesRequired; GenerateTokenRequest generateTokenRequestParameters; // This is how you create embed token with effective identities if (!string.IsNullOrWhiteSpace(username)) { var rls = new EffectiveIdentity(username, new List <string> { report.DatasetId }); if (!string.IsNullOrWhiteSpace(roles)) { var rolesList = new List <string>(); rolesList.AddRange(roles.Split(',')); rls.Roles = rolesList; } // Generate Embed Token with effective identities. generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view", identities: new List <EffectiveIdentity> { rls }); } else { // Generate Embed Token for reports without effective identities. generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view"); } var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(WorkspaceId, report.Id, generateTokenRequestParameters); if (tokenResponse == null) { result.ErrorMessage = "Failed to generate embed token."; return(View(result)); } // Generate Embed Configuration. result.EmbedToken = tokenResponse; result.EmbedUrl = report.EmbedUrl; result.Id = report.Id; return(View(result)); } } catch (HttpOperationException exc) { result.ErrorMessage = string.Format("Status: {0} ({1})\r\nResponse: {2}\r\nRequestId: {3}", exc.Response.StatusCode, (int)exc.Response.StatusCode, exc.Response.Content, exc.Response.Headers["RequestId"].FirstOrDefault()); } catch (Exception exc) { result.ErrorMessage = exc.ToString(); } return(View(result)); }
public async Task <ActionResult> EmbedTile() { var error = GetWebConfigErrors(); if (error != null) { return(View(new TileEmbedConfig() { ErrorMessage = error })); } // Create a user password cradentials. var credential = new UserPasswordCredential(Username, Password); // Authenticate using created credentials var authenticationContext = new AuthenticationContext(AuthorityUrl); var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ApplicationId, credential); if (authenticationResult == null) { return(View(new TileEmbedConfig() { ErrorMessage = "Authentication Failed." })); } var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer"); // Create a Power BI Client object. It will be used to call Power BI APIs. using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials)) { // Get a list of dashboards. var dashboards = await client.Dashboards.GetDashboardsInGroupAsync(WorkspaceId); // Get the first report in the workspace. var dashboard = dashboards.Value.FirstOrDefault(); if (dashboard == null) { return(View(new TileEmbedConfig() { ErrorMessage = "Workspace has no dashboards." })); } var tiles = await client.Dashboards.GetTilesInGroupAsync(WorkspaceId, dashboard.Id); // Get the first tile in the workspace. var tile = tiles.Value.FirstOrDefault(); // Generate Embed Token for a tile. var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view"); var tokenResponse = await client.Tiles.GenerateTokenInGroupAsync(WorkspaceId, dashboard.Id, tile.Id, generateTokenRequestParameters); if (tokenResponse == null) { return(View(new TileEmbedConfig() { ErrorMessage = "Failed to generate embed token." })); } // Generate Embed Configuration. var embedConfig = new TileEmbedConfig() { EmbedToken = tokenResponse, EmbedUrl = tile.EmbedUrl, Id = tile.Id, dashboardId = dashboard.Id }; return(View(embedConfig)); } }
public void TestPutOperationWithImmediateSuccess() { var tokenCredentials = new TokenCredentials("123", "abc"); var handler = new PlaybackTestHandler(MockPutOperaionWithImmediateSuccess()); var fakeClient = new RedisManagementClient(tokenCredentials, handler); fakeClient.LongRunningOperationInitialTimeout = fakeClient.LongRunningOperationRetryTimeout = 0; fakeClient.RedisOperations.CreateOrUpdate("rg", "redis", new RedisCreateOrUpdateParameters(), "1234"); Assert.Equal(1, handler.Requests.Count); }
public void TestPostOperationWithImmediateSuccessAndNoContentStatus() { var tokenCredentials = new TokenCredentials("123", "abc"); var handler = new PlaybackTestHandler(MockOperaionWithImmediateSuccessNoContentStatus()); var fakeClient = new RedisManagementClient(tokenCredentials, handler); fakeClient.LongRunningOperationInitialTimeout = fakeClient.LongRunningOperationRetryTimeout = 0; fakeClient.RedisOperations.Post("rg", "redis", "1234"); Assert.Equal(1, handler.Requests.Count); }
public static async Task CreateNetworkAsync( TokenCredentials credential, string vnetName, string subnetName, string nicName, string ipName, string groupName, string subscriptionId, string location) { Console.WriteLine("Creating the virtual network..."); var networkManagementClient = new NetworkManagementClient(credential); networkManagementClient.SubscriptionId = subscriptionId; var subnet = new Subnet { Name = subnetName, AddressPrefix = "10.0.0.0/24" }; var address = new AddressSpace { AddressPrefixes = new List <string> { "10.0.0.0/16" } }; var vnResult = await networkManagementClient.VirtualNetworks.CreateOrUpdateAsync( groupName, vnetName, new VirtualNetwork { Location = location, AddressSpace = address, Subnets = new List <Subnet> { subnet } } ); Console.WriteLine(vnResult.ProvisioningState); var subnetResponse = await networkManagementClient.Subnets.GetAsync( groupName, vnetName, subnetName ); var pubipResponse = await networkManagementClient.PublicIPAddresses.GetAsync(groupName, ipName); Console.WriteLine("Updating the network with the nic..."); var nicResult = await networkManagementClient.NetworkInterfaces.CreateOrUpdateAsync( groupName, nicName, new NetworkInterface { Location = location, IpConfigurations = new List <NetworkInterfaceIPConfiguration> { new NetworkInterfaceIPConfiguration { Name = "nicConfig1", PublicIPAddress = pubipResponse, Subnet = subnetResponse } } } ); Console.WriteLine(vnResult.ProvisioningState); }
public void TestCreateOrUpdateFailedStatus() { var tokenCredentials = new TokenCredentials("123", "abc"); var handler = new PlaybackTestHandler(MockCreateOrUpdateWithFailedStatus()); var fakeClient = new RedisManagementClient(tokenCredentials, handler); fakeClient.LongRunningOperationInitialTimeout = fakeClient.LongRunningOperationRetryTimeout = 0; try { fakeClient.RedisOperations.CreateOrUpdate("rg", "redis", new RedisCreateOrUpdateParameters(), "1234"); Assert.False(true, "Expected exception was not thrown."); } catch (CloudException ex) { Assert.Equal("Long running operation failed with status 'Failed'.", ex.Message); Assert.Contains(AzureAsyncOperation.FailedStatus, ex.Response.Content); } }
public static async Task CreateVirtualMachineAsync( TokenCredentials credential, string vmName, string groupName, string nicName, string avsetName, string storageName, string adminName, string adminPassword, string subscriptionId, string location) { var networkManagementClient = new NetworkManagementClient(credential); networkManagementClient.SubscriptionId = subscriptionId; var nic = await networkManagementClient.NetworkInterfaces.GetAsync(groupName, nicName); var computeManagementClient = new ComputeManagementClient(credential); computeManagementClient.SubscriptionId = subscriptionId; var avSet = await computeManagementClient.AvailabilitySets.GetAsync(groupName, avsetName); try { var sampleVM = await computeManagementClient.VirtualMachines.GetAsync("hbbu-res-group", "hbbu-vm"); Console.WriteLine($"{nameof(sampleVM.Name)}={sampleVM.Name}"); } catch (System.Exception ex) { Console.WriteLine($"{ex}"); } var vmSizes = await computeManagementClient.VirtualMachineSizes.ListAsync(location); foreach (var vmSize in vmSizes) { Console.WriteLine($"{nameof(vmSize.Name)}={vmSize.Name}"); Console.WriteLine($"{nameof(vmSize.MaxDataDiskCount)}={vmSize.MaxDataDiskCount}"); Console.WriteLine($"{nameof(vmSize.MemoryInMB)}={vmSize.MemoryInMB}"); Console.WriteLine($"{nameof(vmSize.NumberOfCores)}={vmSize.NumberOfCores}"); Console.WriteLine($"{nameof(vmSize.OsDiskSizeInMB)}={vmSize.OsDiskSizeInMB}"); Console.WriteLine($"{nameof(vmSize.ResourceDiskSizeInMB)}={vmSize.ResourceDiskSizeInMB}"); Console.WriteLine(); } Console.WriteLine("Creating the virtual machine..."); bool bCreateNewDataDisk = true; bool bAttcheExisting = true; var vm = await computeManagementClient.VirtualMachines.CreateOrUpdateAsync( groupName, vmName, new VirtualMachine { Location = location, AvailabilitySet = new Microsoft.Azure.Management.Compute.Models.SubResource { Id = avSet.Id }, HardwareProfile = new HardwareProfile { //VmSize = "Standard_A0" VmSize = "Standard_DS1_V2" }, OsProfile = new OSProfile { AdminUsername = adminName, AdminPassword = adminPassword, ComputerName = vmName, WindowsConfiguration = new WindowsConfiguration { ProvisionVMAgent = true } }, NetworkProfile = new NetworkProfile { NetworkInterfaces = new List <NetworkInterfaceReference> { new NetworkInterfaceReference { Id = nic.Id } } }, StorageProfile = new StorageProfile { ImageReference = new ImageReference { Publisher = "MicrosoftWindowsServer", Offer = "WindowsServer", Sku = "2012-R2-Datacenter", Version = "latest" }, OsDisk = new OSDisk { Name = "mytestod1", CreateOption = DiskCreateOptionTypes.FromImage, Vhd = new VirtualHardDisk { Uri = "https://" + storageName + ".blob.core.windows.net/vhds/mytestod1.vhd" } }, DataDisks = bCreateNewDataDisk? new List <DataDisk>() { new DataDisk() { Caching = CachingTypes.ReadOnly, CreateOption = bAttcheExisting? DiskCreateOptionTypes.Attach : DiskCreateOptionTypes.Empty, DiskSizeGB = 1023, Lun = 0, Name = "sssDataDisk0", Vhd = new VirtualHardDisk() { Uri = "https://" + storageName + ".blob.core.windows.net/vhds/sssDataDisk0.vhd" } }, new DataDisk() { Caching = CachingTypes.ReadOnly, CreateOption = bAttcheExisting? DiskCreateOptionTypes.Attach : DiskCreateOptionTypes.Empty, DiskSizeGB = 1023, Lun = 1, Name = "sssDataDisk1", Vhd = new VirtualHardDisk() { Uri = "https://" + storageName + ".blob.core.windows.net/vhds/sssDataDisk1.vhd" } } } : new List <DataDisk>() } } ); Console.WriteLine(vm.ProvisioningState); }
public void TestDeleteWithLocationHeaderErrorHandlingSecondTime() { var tokenCredentials = new TokenCredentials("123", "abc"); var handler = new PlaybackTestHandler(MockDeleteWithLocationHeaderErrorInSecondCall()); var fakeClient = new RedisManagementClient(tokenCredentials, handler); fakeClient.LongRunningOperationInitialTimeout = fakeClient.LongRunningOperationRetryTimeout = 0; var ex = Assert.Throws<CloudException>(()=>fakeClient.RedisOperations.Delete("rg", "redis", "1234")); Assert.Equal("Long running operation failed with status 'InternalServerError'.", ex.Message); }
public static async Task TestAzureOperationsAsync() { try { string token = await GetAuthorizationHeaderAsync(); var credential = new TokenCredentials(token); await GetSubscriptionsAsync(credential); var groupName = "sssgroupname"; var ipName = "sssipname"; var avSetName = "sssavsetname"; var nicName = "sssnicname"; var storageName = "sssstoragename"; var vmName = "sssvmname"; var vnetName = "sssvnetname"; var subnetName = "ssssubnetname"; var adminName = "sss"; var adminPassword = "******"; var location = "eastus"; var subscriptionId = "7315bf64-0ed9-46d8-b4e6-1a6082194d22"; await CreateResourceGroupAsync( credential, //TokenCredentials credential, groupName, //string groupName, subscriptionId, //string subscriptionId, location //string location ); //Console.ReadLine(); await CreateStorageAccountAsync( credential, storageName, groupName, subscriptionId, location); //Console.ReadLine(); await CreatePublicIPAddress( credential, ipName, groupName, subscriptionId, location ); await CreateNetworkAsync( credential, vnetName, subnetName, nicName, ipName, groupName, subscriptionId, location); await CreateAvailabilitySetAsync( credential, avSetName, groupName, subscriptionId, location); //Console.ReadLine(); await CreateVirtualMachineAsync( credential, vmName, groupName, nicName, avSetName, storageName, adminName, adminPassword, subscriptionId, location); //Console.ReadLine(); await PowerOnOffVirtualMachineAsync( credential, //TokenCredentials credential, vmName, //string vmName, groupName, //string groupName, subscriptionId //string subscriptionId ); bool toDeleteResource = false; if (toDeleteResource) { await DeleteResourceGroupAsync( credential, groupName, subscriptionId); } //Console.ReadLine(); } catch (System.Exception ex) { Console.WriteLine($"{ex.Message}"); Console.WriteLine($"{ex}"); throw; } }
public void SuccessfulResourceOwnerClaimsUpdate() { TokenClient client = null !; GrantedTokenResponse tokenResponse = null !; HttpResponseMessage updateResponse = null !; "and a properly configured token client".x( () => client = new TokenClient( TokenCredentials.FromBasicAuthentication("client", "client"), _fixture.Client, new Uri(WellKnownOpenidConfiguration))); "when requesting token".x( async() => { var response = await client .GetToken(TokenRequest.FromPassword("user", "password", new[] { "openid", "offline" })) .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result; tokenResponse = response.Item; }); "and valid access token is received".x( () => { var tokenHandler = new JwtSecurityTokenHandler(); var validationParameters = new TokenValidationParameters { IssuerSigningKeys = _jwks.GetSigningKeys(), ValidAudience = "client", ValidIssuer = "https://localhost" }; tokenHandler.ValidateToken(tokenResponse.AccessToken, validationParameters, out var token); Assert.NotEmpty(((JwtSecurityToken)token).Claims); }); "and updating own claims".x( async() => { var updateRequest = new UpdateResourceOwnerClaimsRequest { Subject = "user", Claims = new[] { new ClaimData { Type = "test", Value = "something" } } }; var json = JsonConvert.SerializeObject(updateRequest); var request = new HttpRequestMessage { Content = new StringContent(json, Encoding.UTF8, "application/json"), Method = HttpMethod.Post, RequestUri = new Uri(_fixture.Server.BaseAddress + "resource_owners/claims") }; request.Headers.Authorization = new AuthenticationHeaderValue( JwtBearerDefaults.AuthenticationScheme, tokenResponse.AccessToken); updateResponse = await _fixture.Client().SendAsync(request).ConfigureAwait(false); }); "then update is successful".x(() => { Assert.Equal(HttpStatusCode.OK, updateResponse.StatusCode); }); }
public async Task TestAddRemoveDeviceConnectionTest() { string deviceId = "id1"; var deviceProxyMock1 = new Mock <IDeviceProxy>(); deviceProxyMock1.SetupGet(dp => dp.IsActive).Returns(true); deviceProxyMock1.Setup(dp => dp.CloseAsync(It.IsAny <Exception>())) .Callback(() => deviceProxyMock1.SetupGet(dp => dp.IsActive).Returns(false)) .Returns(Task.FromResult(true)); var deviceCredentials = new TokenCredentials(new DeviceIdentity("iotHub", deviceId), "token", "abc", false); var edgeHub = new Mock <IEdgeHub>(); IClient client = GetDeviceClient(); var messageConverterProvider = Mock.Of <IMessageConverterProvider>(); var deviceClientProvider = new Mock <IClientProvider>(); deviceClientProvider.Setup(d => d.Create(It.IsAny <IIdentity>(), It.IsAny <ITokenProvider>(), It.IsAny <Client.ITransportSettings[]>())) .Returns(client); var credentialsManager = Mock.Of <ICredentialsCache>(); var edgeHubIdentity = Mock.Of <IIdentity>(i => i.Id == "edgeDevice/$edgeHub"); var cloudConnectionProvider = new CloudConnectionProvider( messageConverterProvider, 1, deviceClientProvider.Object, Option.None <UpstreamProtocol>(), Mock.Of <ITokenProvider>(), Mock.Of <IDeviceScopeIdentitiesCache>(), credentialsManager, edgeHubIdentity, TimeSpan.FromMinutes(60), true, TimeSpan.FromSeconds(20)); cloudConnectionProvider.BindEdgeHub(edgeHub.Object); IConnectionManager connectionManager = new ConnectionManager(cloudConnectionProvider, credentialsManager, GetIdentityProvider()); Try <ICloudProxy> cloudProxyTry = await connectionManager.CreateCloudConnectionAsync(deviceCredentials); Assert.True(cloudProxyTry.Success); var deviceListener = new DeviceMessageHandler(deviceCredentials.Identity, edgeHub.Object, connectionManager); Option <ICloudProxy> cloudProxy = await connectionManager.GetCloudConnection(deviceId); Assert.True(cloudProxy.HasValue); Assert.True(cloudProxy.OrDefault().IsActive); deviceListener.BindDeviceProxy(deviceProxyMock1.Object); Option <IDeviceProxy> deviceProxy = connectionManager.GetDeviceConnection(deviceId); Assert.True(deviceProxy.HasValue); Assert.True(deviceProxy.OrDefault().IsActive); Assert.True(deviceProxyMock1.Object.IsActive); cloudProxy = await connectionManager.GetCloudConnection(deviceId); Assert.True(cloudProxy.HasValue); Assert.True(cloudProxy.OrDefault().IsActive); await deviceListener.CloseAsync(); deviceProxy = connectionManager.GetDeviceConnection(deviceId); Assert.False(deviceProxy.HasValue); Assert.False(deviceProxyMock1.Object.IsActive); cloudProxy = await connectionManager.GetCloudConnection(deviceId); Assert.True(cloudProxy.HasValue); Assert.True(client.IsActive); }
public override void HandleMenuResponse(string response, List <Target> targets) { if (response == "w") { var settings = ActiveDirectoryServiceSettings.Azure; var authContext = new AuthenticationContext(settings.AuthenticationEndpoint + "common"); var token = authContext.AcquireToken(settings.TokenAudience.ToString(), "1950a258-227b-4e31-a9cf-717495945fc2", new Uri("urn:ietf:wg:oauth:2.0:oob"), promptBehavior: PromptBehavior.Always); var creds = new TokenCredentials(token.AccessToken); var client = new SubscriptionClient(creds); client.SubscriptionId = Guid.NewGuid().ToString(); //Just set any GUID or subscription client will complain. int i = 0; var subscriptions = client.Subscriptions.List(); foreach (var sub in subscriptions) { Console.WriteLine("[" + i + "] " + sub.DisplayName); i++; } Console.WriteLine("Select subscription:"); var subscription = subscriptions.ElementAt(Int32.Parse(Console.ReadLine())); var resClient = new ResourceManagementClient(creds); resClient.SubscriptionId = subscription.SubscriptionId; var resourceGroups = resClient.ResourceGroups.List(); i = 0; foreach (var resourceGroup in resourceGroups) { Console.WriteLine("[" + i + "] " + resourceGroup.Name); i++; } Console.WriteLine("Select Resource Group"); _resourceGroupname = resourceGroups.ElementAt(int.Parse(Console.ReadLine())).Name; _webSiteManagementClient = new WebSiteManagementClient(creds); _webSiteManagementClient.SubscriptionId = subscription.SubscriptionId; var sites = _webSiteManagementClient.Sites.GetSites(_resourceGroupname); i = 0; foreach (var site in sites.Value) { Console.WriteLine("[" + i + "] " + site.Name); i++; } Console.WriteLine("Select site"); _siteName = sites.Value.ElementAt(int.Parse(Console.ReadLine())).Name; Console.Write("Enter a host name: "); var hostName = Console.ReadLine(); // TODO: pull an existing host from the settings to default this value Console.Write("Enter a local folder path (local temp folder where the signature file will be saved before it is uploaded to the azure web site): "); var physicalPath = Console.ReadLine(); // TODO: make a system where they can execute a program/batch file to update whatever they need after install. var target = new Target() { Host = hostName, WebRootPath = physicalPath, PluginName = Name }; Program.Auto(target); } }
public async Task GetMultipleCloudProxiesTest() { // Arrange string edgeDeviceId = "edgeDevice"; string module1Id = "module1"; string token = TokenHelper.CreateSasToken(IotHubHostName); var module1Credentials = new TokenCredentials(new ModuleIdentity(IotHubHostName, edgeDeviceId, module1Id), token, DummyProductInfo, true); IClient client1 = GetDeviceClient(); IClient client2 = GetDeviceClient(); var messageConverterProvider = Mock.Of <IMessageConverterProvider>(); var deviceClientProvider = new Mock <IClientProvider>(); deviceClientProvider.SetupSequence(d => d.Create(It.IsAny <IIdentity>(), It.IsAny <ITokenProvider>(), It.IsAny <Client.ITransportSettings[]>())) .Returns(client1) .Returns(client2); ICredentialsCache credentialsCache = new CredentialsCache(new NullCredentialsCache()); await credentialsCache.Add(module1Credentials); var cloudConnectionProvider = new CloudConnectionProvider( messageConverterProvider, 1, deviceClientProvider.Object, Option.None <UpstreamProtocol>(), Mock.Of <ITokenProvider>(), Mock.Of <IDeviceScopeIdentitiesCache>(), credentialsCache, new ModuleIdentity(IotHubHostName, edgeDeviceId, "$edgeHub"), TimeSpan.FromMinutes(60), true, TimeSpan.FromSeconds(20)); cloudConnectionProvider.BindEdgeHub(Mock.Of <IEdgeHub>()); IConnectionManager connectionManager = new ConnectionManager(cloudConnectionProvider, credentialsCache, GetIdentityProvider()); // Act Task <Option <ICloudProxy> > getCloudProxyTask1 = connectionManager.GetCloudConnection(module1Credentials.Identity.Id); Task <Option <ICloudProxy> > getCloudProxyTask2 = connectionManager.GetCloudConnection(module1Credentials.Identity.Id); Task <Option <ICloudProxy> > getCloudProxyTask3 = connectionManager.GetCloudConnection(module1Credentials.Identity.Id); Task <Option <ICloudProxy> > getCloudProxyTask4 = connectionManager.GetCloudConnection(module1Credentials.Identity.Id); Option <ICloudProxy>[] cloudProxies = await Task.WhenAll(getCloudProxyTask1, getCloudProxyTask2, getCloudProxyTask3, getCloudProxyTask4); // Assert Assert.True(cloudProxies[0].HasValue); Assert.True(cloudProxies[1].HasValue); Assert.True(cloudProxies[2].HasValue); Assert.True(cloudProxies[3].HasValue); Assert.Equal(cloudProxies[0].OrDefault(), cloudProxies[1].OrDefault()); Assert.Equal(cloudProxies[0].OrDefault(), cloudProxies[2].OrDefault()); Assert.Equal(cloudProxies[0].OrDefault(), cloudProxies[3].OrDefault()); // Act await cloudProxies[0].OrDefault().CloseAsync(); Option <ICloudProxy> newCloudProxyTask1 = await connectionManager.GetCloudConnection(module1Credentials.Identity.Id); // Assert Assert.True(newCloudProxyTask1.HasValue); Assert.NotEqual(newCloudProxyTask1.OrDefault(), cloudProxies[0].OrDefault()); Mock.Get(client1).Verify(cp => cp.CloseAsync(), Times.Once); Mock.Get(client2).Verify(cp => cp.CloseAsync(), Times.Never); }
static PowerBIClient GetPowerBiClient() { var tokenCredentials = new TokenCredentials(GetAccessToken(), "Bearer"); return(new PowerBIClient(new Uri(urlPowerBiRestApiRoot), tokenCredentials)); }
public static HttpClient GenerateClient(IConfiguration Configuration) { string dynamicsOdataUri = Configuration["DYNAMICS_ODATA_URI"]; // Dynamics ODATA endpoint string token = ""; if (string.IsNullOrEmpty(dynamicsOdataUri)) { throw new Exception("Configuration setting DYNAMICS_ODATA_URI is blank."); } // Cloud - x.dynamics.com string aadTenantId = Configuration["DYNAMICS_AAD_TENANT_ID"]; // Cloud AAD Tenant ID string serverAppIdUri = Configuration["DYNAMICS_SERVER_APP_ID_URI"]; // Cloud Server App ID URI string appRegistrationClientKey = Configuration["DYNAMICS_APP_REG_CLIENT_KEY"]; // Cloud App Registration Client Key string appRegistrationClientId = Configuration["DYNAMICS_APP_REG_CLIENT_ID"]; // Cloud App Registration Client Id // One Premise ADFS (2016) string adfsOauth2Uri = Configuration["ADFS_OAUTH2_URI"]; // ADFS OAUTH2 URI - usually /adfs/oauth2/token on STS string applicationGroupResource = Configuration["DYNAMICS_APP_GROUP_RESOURCE"]; // ADFS 2016 Application Group resource (URI) string applicationGroupClientId = Configuration["DYNAMICS_APP_GROUP_CLIENT_ID"]; // ADFS 2016 Application Group Client ID string applicationGroupSecret = Configuration["DYNAMICS_APP_GROUP_SECRET"]; // ADFS 2016 Application Group Secret string serviceAccountUsername = Configuration["DYNAMICS_USERNAME"]; // Service account username string serviceAccountPassword = Configuration["DYNAMICS_PASSWORD"]; // Service account password ServiceClientCredentials serviceClientCredentials = null; if (!string.IsNullOrEmpty(appRegistrationClientId) && !string.IsNullOrEmpty(appRegistrationClientKey) && !string.IsNullOrEmpty(serverAppIdUri) && !string.IsNullOrEmpty(aadTenantId)) // Cloud authentication - using an App Registration's client ID, client key. Add the App Registration to Dynamics as an Application User. { var authenticationContext = new AuthenticationContext( "https://login.windows.net/" + aadTenantId); ClientCredential clientCredential = new ClientCredential(appRegistrationClientId, appRegistrationClientKey); var task = authenticationContext.AcquireTokenAsync(serverAppIdUri, clientCredential); task.Wait(); var authenticationResult = task.Result; token = authenticationResult.CreateAuthorizationHeader().Substring("Bearer ".Length); serviceClientCredentials = new TokenCredentials(token); } else if (!string.IsNullOrEmpty(adfsOauth2Uri) && !string.IsNullOrEmpty(applicationGroupResource) && !string.IsNullOrEmpty(applicationGroupClientId) && !string.IsNullOrEmpty(applicationGroupSecret) && !string.IsNullOrEmpty(serviceAccountUsername) && !string.IsNullOrEmpty(serviceAccountPassword)) // ADFS 2016 authentication - using an Application Group Client ID and Secret, plus service account credentials. { // create a new HTTP client that is just used to get a token. var stsClient = new HttpClient(); //stsClient.DefaultRequestHeaders.Add("x-client-SKU", "PCL.CoreCLR"); //stsClient.DefaultRequestHeaders.Add("x-client-Ver", "5.1.0.0"); //stsClient.DefaultRequestHeaders.Add("x-ms-PKeyAuth", "1.0"); stsClient.DefaultRequestHeaders.Add("client-request-id", Guid.NewGuid().ToString()); stsClient.DefaultRequestHeaders.Add("return-client-request-id", "true"); stsClient.DefaultRequestHeaders.Add("Accept", "application/json"); // Construct the body of the request var pairs = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("resource", applicationGroupResource), new KeyValuePair <string, string>("client_id", applicationGroupClientId), new KeyValuePair <string, string>("client_secret", applicationGroupSecret), new KeyValuePair <string, string>("username", serviceAccountUsername), new KeyValuePair <string, string>("password", serviceAccountPassword), new KeyValuePair <string, string>("scope", "openid"), new KeyValuePair <string, string>("response_mode", "form_post"), new KeyValuePair <string, string>("grant_type", "password") }; // This will also set the content type of the request var content = new FormUrlEncodedContent(pairs); // send the request to the ADFS server var _httpResponse = stsClient.PostAsync(adfsOauth2Uri, content).GetAwaiter().GetResult(); var _responseContent = _httpResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult(); // response should be in JSON format. try { Dictionary <string, string> result = JsonConvert.DeserializeObject <Dictionary <string, string> >(_responseContent); token = result["access_token"]; // set the bearer token. serviceClientCredentials = new TokenCredentials(token); } catch (Exception e) { throw new Exception(e.Message + " " + _responseContent); } } else { throw new Exception("No configured connection to Dynamics."); } HttpClient client = new HttpClient(); client.BaseAddress = new Uri(dynamicsOdataUri); string Authorization = $"Bearer {token}"; client.DefaultRequestHeaders.Add("Authorization", Authorization); client.DefaultRequestHeaders.Add("Cache-Control", "no-cache"); client.DefaultRequestHeaders.Add("OData-Version", "4.0"); client.DefaultRequestHeaders.Add("Accept", "application/json"); return(client); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, ILogger log) { string requestData = ""; string reportInfo = req.Query["id"]; string ResourceUrl = "https://analysis.windows.net/powerbi/api"; string ApiUrl = "https://api.powerbi.com/"; string ADdomain = Environment.GetEnvironmentVariable("ADdomain"); string ClientId = Environment.GetEnvironmentVariable("AppClientId"); string ClientSecret = Environment.GetEnvironmentVariable("AppClientSecret"); string GroupId = Environment.GetEnvironmentVariable("WorkspaceId"); var successful = true; try { // create object for response var authInfo = new xAuthen(); // create service principal credential var credential = new ClientCredential(ClientId, ClientSecret); // Authenticate using created credentials string AuthorityUrl = "https://login.microsoftonline.com/" + ADdomain + "/oauth2/v2.0/authorize"; var authenticationContext = new AuthenticationContext(AuthorityUrl); var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, credential); if (authenticationResult == null) { log.LogError("Authentication Failed."); } var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer"); // Create a Power BI Client object. It will be used to call Power BI APIs. using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials)) { var report = await client.Reports.GetReportInGroupAsync(GroupId, reportInfo); // Generate Embed Token. var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view"); var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(GroupId, report.Id, generateTokenRequestParameters); if (tokenResponse == null) { log.LogInformation("Failed to generate embed token."); } authInfo.accessToken = (string)tokenResponse.Token; authInfo.embedUrl = (string)report.EmbedUrl; authInfo.embedReportId = (string)report.Id; } requestData = JsonConvert.SerializeObject(authInfo); } catch (Exception ex) { log.LogError(ex.Message); successful = false; } if (!successful) { return(new BadRequestObjectResult("Issue processing the request.")); } else { var responsejson = new OkObjectResult(requestData); return(responsejson); } }
public void ExecuteDeviceAuthorizationFlowWithUserApproval() { const string clientId = "device"; ITokenClient tokenClient = null !; DeviceAuthorizationResponse response = null !; GrantedTokenResponse token = null !; Task <Option <GrantedTokenResponse> > pollingTask = null !; "Given a token client".x( () => { tokenClient = new TokenClient( TokenCredentials.AsDevice(), _fixture.Client, new Uri(WellKnownOpenidConfiguration)); Assert.NotNull(tokenClient); }); "and an access token".x( async() => { var authClient = new TokenClient( TokenCredentials.FromClientCredentials(clientId, "client"), _fixture.Client, new Uri(WellKnownOpenidConfiguration)); var tokenResponse = await authClient.GetToken( TokenRequest.FromPassword("user", "password", new[] { "openid" })) .ConfigureAwait(false); Assert.IsType <Option <GrantedTokenResponse> .Result>(tokenResponse); token = (tokenResponse as Option <GrantedTokenResponse> .Result).Item; }); "When a device requests authorization".x( async() => { var genericResponse = await tokenClient.GetAuthorization(new DeviceAuthorizationRequest(clientId)) .ConfigureAwait(false); Assert.IsType <Option <DeviceAuthorizationResponse> .Result>(genericResponse); response = (genericResponse as Option <DeviceAuthorizationResponse> .Result).Item; }); "and the device polls the token server".x( async() => { pollingTask = tokenClient.GetToken( TokenRequest.FromDeviceCode(clientId, response.DeviceCode, response.Interval)); Assert.False(pollingTask.IsCompleted); }); "and user successfully posts user code".x( async() => { var client = _fixture.Client(); var msg = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(response.VerificationUri), Content = new FormUrlEncodedContent( new[] { new KeyValuePair <string, string>("code", response.UserCode) }) }; msg.Headers.Authorization = new AuthenticationHeaderValue(token.TokenType, token.AccessToken); var approval = await client.SendAsync(msg).ConfigureAwait(false); Assert.Equal(HttpStatusCode.OK, approval.StatusCode); }); "then token is returned from polling".x( async() => { var tokenResponse = await pollingTask.ConfigureAwait(false); Assert.IsType <Option <GrantedTokenResponse> .Result>(tokenResponse); }); }
public void TestAsyncOperationWithNonSuccessStatusAndInvalidResponseContent() { var tokenCredentials = new TokenCredentials("123", "abc"); var handler = new PlaybackTestHandler(MockAsyncOperaionWithNonSuccessStatusAndInvalidResponseContent()); var fakeClient = new RedisManagementClient(tokenCredentials, handler); fakeClient.LongRunningOperationInitialTimeout = fakeClient.LongRunningOperationRetryTimeout = 0; var error = Assert.Throws<CloudException>(() => fakeClient.RedisOperations.Delete("rg", "redis", "1234")); Assert.Equal("Long running operation failed with status 'BadRequest'.", error.Message); Assert.Null(error.Body); }
private IPowerBIClient CreatePowerBIClient(HttpClientHandler handler) { var credentials = new TokenCredentials(AccessKey); return(new PowerBIClient(credentials, handler)); }
/// <summary> /// Builds a connection string for the storage account when none was specified during initialisation. /// </summary> /// <returns>Connection <see cref="string" /></returns> /// <exception cref="InvalidOperationException">If the Storage Namespace can not be resolved or access keys are not configured.</exception> internal async Task <string> BuildStorageConnection() { try { // If we already have the connection string for this instance - don't go get it again. if (ConnectionStrings.TryGetValue(_instanceName, out var connStr)) { return(connStr); } const string azureManagementAuthority = "https://management.azure.com/"; const string windowsLoginAuthority = "https://login.windows.net/"; string token; // Use Msi Config if it's been specified, otherwise, use Service principle. if (MsiConfig != null) { // Managed Service Identity (MSI) authentication. var provider = new AzureServiceTokenProvider(); token = provider.GetAccessTokenAsync(azureManagementAuthority, MsiConfig.TenantId).GetAwaiter().GetResult(); if (string.IsNullOrEmpty(token)) { throw new InvalidOperationException("Could not authenticate using Managed Service Identity, ensure the application is running in a secure context"); } _expiryTime = DateTime.Now.AddDays(1); } else { // Service Principle authentication // Grab an authentication token from Azure. var context = new AuthenticationContext($"{windowsLoginAuthority}{ServicePrincipleConfig.TenantId}"); var credential = new ClientCredential(ServicePrincipleConfig.AppId, ServicePrincipleConfig.AppSecret); var tokenResult = context.AcquireTokenAsync(azureManagementAuthority, credential).GetAwaiter().GetResult(); if (tokenResult == null || tokenResult.AccessToken == null) { throw new InvalidOperationException($"Could not authenticate to {windowsLoginAuthority}{ServicePrincipleConfig.TenantId} using supplied AppId: {ServicePrincipleConfig.AppId}"); } _expiryTime = tokenResult.ExpiresOn; token = tokenResult.AccessToken; } // Set credentials and grab the authenticated REST client. var tokenCredentials = new TokenCredentials(token); var client = RestClient.Configure() .WithEnvironment(AzureEnvironment.AzureGlobalCloud) .WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders) .WithCredentials(new AzureCredentials(tokenCredentials, tokenCredentials, string.Empty, AzureEnvironment.AzureGlobalCloud)) .WithRetryPolicy(new RetryPolicy(new HttpStatusCodeErrorDetectionStrategy(), new FixedIntervalRetryStrategy(3, TimeSpan.FromMilliseconds(500)))) .Build(); // Authenticate against the management layer. var azureManagement = Azure.Authenticate(client, string.Empty).WithSubscription(_subscriptionId); // Get the storage namespace for the passed in instance name. var storageNamespace = azureManagement.StorageAccounts.List().FirstOrDefault(n => n.Name == _instanceName); // If we cant find that name, throw an exception. if (storageNamespace == null) { throw new InvalidOperationException($"Could not find the storage instance {_instanceName} in the subscription Id specified"); } // Storage accounts use access keys - this will be used to build a connection string. var accessKeys = await storageNamespace.GetKeysAsync(); // If the access keys are not found (not configured for some reason), throw an exception. if (accessKeys == null) { throw new InvalidOperationException($"Could not find access keys for the storage instance {_instanceName}"); } // We just default to the first key. var key = accessKeys[0].Value; // Build the connection string. var connectionString = $"DefaultEndpointsProtocol=https;AccountName={_instanceName};AccountKey={key};EndpointSuffix=core.windows.net"; // Cache the connection string off so we don't have to reauthenticate. if (!ConnectionStrings.ContainsKey(_instanceName)) { ConnectionStrings.TryAdd(_instanceName, connectionString); } // Return connection string. return(connectionString); } catch (Exception e) { _expiryTime = null; Logger?.LogError(e, "An exception occured during connection to Table storage"); throw new InvalidOperationException("An exception occurred during service connection, see inner exception for more detail", e); } }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); //Get body values string tenantId = req.Query["tenantId"]; string applicationId = req.Query["applicationId"]; string authenticationKey = req.Query["authenticationKey"]; string subscriptionId = req.Query["subscriptionId"]; string resourceGroup = req.Query["resourceGroup"]; string factoryName = req.Query["factoryName"]; string pipelineName = req.Query["pipelineName"]; string runId = req.Query["runId"]; string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); tenantId = tenantId ?? data?.tenantId; applicationId = applicationId ?? data?.applicationId; authenticationKey = authenticationKey ?? data?.authenticationKey; subscriptionId = subscriptionId ?? data?.subscriptionId; resourceGroup = resourceGroup ?? data?.resourceGroup; factoryName = factoryName ?? data?.factoryName; pipelineName = pipelineName ?? data?.pipelineName; runId = runId ?? data?.runId; //Check body for values if ( tenantId == null || applicationId == null || authenticationKey == null || subscriptionId == null || factoryName == null || pipelineName == null || runId == null ) { return(new BadRequestObjectResult("Invalid request body, value missing.")); } //Create a data factory management client var context = new AuthenticationContext("https://login.windows.net/" + tenantId); ClientCredential cc = new ClientCredential(applicationId, authenticationKey); AuthenticationResult result = context.AcquireTokenAsync( "https://management.azure.com/", cc).Result; ServiceClientCredentials cred = new TokenCredentials(result.AccessToken); var client = new DataFactoryManagementClient(cred) { SubscriptionId = subscriptionId }; //Get pipeline status with provided run id PipelineRun pipelineRun; string pipelineStatus = String.Empty; string outputString; pipelineRun = client.PipelineRuns.Get(resourceGroup, factoryName, runId); pipelineStatus = pipelineRun.Status; //Prepare output outputString = "{ \"PipelineName\": \"" + pipelineName + "\", \"RunIdUsed\": \"" + runId + "\", \"Status\": \"" + pipelineRun.Status + "\" }"; JObject json = JObject.Parse(outputString); return(new OkObjectResult(json)); }
public void TestDeleteOperationWithNonRetryableErrorInResponse() { var tokenCredentials = new TokenCredentials("123", "abc"); var handler = new PlaybackTestHandler(MockDeleteOperaionWithNoRetryableErrorInResponse()); var fakeClient = new RedisManagementClient(tokenCredentials, handler); fakeClient.LongRunningOperationInitialTimeout = fakeClient.LongRunningOperationRetryTimeout = 0; var error = Assert.Throws<CloudException>(() => fakeClient.RedisOperations.Delete("rg", "redis", "1234")); Assert.Equal("Long running operation failed with status 'BadRequest'.", error.Message); Assert.Equal(2, handler.Requests.Count); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string tenantId = req.Query["tenantId"]; string applicationId = req.Query["applicationId"]; string authenticationKey = req.Query["authenticationKey"]; string subscriptionId = req.Query["subscriptionId"]; string resourceGroup = req.Query["resourceGroup"]; string factoryName = req.Query["factoryName"]; string pipelineName = req.Query["pipelineName"]; int daysOfRuns = int.Parse(Environment.GetEnvironmentVariable("DefaultDaysForPipelineRuns")); string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); tenantId = tenantId ?? data?.tenantId; applicationId = applicationId ?? data?.applicationId; authenticationKey = authenticationKey ?? data?.authenticationKey; subscriptionId = subscriptionId ?? data?.subscriptionId; resourceGroup = resourceGroup ?? data?.resourceGroup; factoryName = factoryName ?? data?.factoryName; pipelineName = pipelineName ?? data?.pipelineName; if ( tenantId == null || applicationId == null || authenticationKey == null || subscriptionId == null || factoryName == null || pipelineName == null ) { return(new BadRequestObjectResult("Invalid request body, value missing.")); } // Authenticate and create a data factory management client var context = new AuthenticationContext("https://login.windows.net/" + tenantId); ClientCredential cc = new ClientCredential(applicationId, authenticationKey); AuthenticationResult result = context.AcquireTokenAsync( "https://management.azure.com/", cc).Result; ServiceClientCredentials cred = new TokenCredentials(result.AccessToken); var client = new DataFactoryManagementClient(cred) { SubscriptionId = subscriptionId }; //Get pipeline status PipelineRun pipelineRuns; //used to find latest pipeline run id PipelineRun pipelineRun; //used to get the status of the last pipeline ActivityRunsQueryResponse queryResponse; //used if not successful string runId = String.Empty; string errorDetails = String.Empty; string outputString; DateTime today = DateTime.Now; DateTime lastWeek = DateTime.Now.AddDays(-daysOfRuns); /* * https://docs.microsoft.com/en-us/rest/api/datafactory/pipelineruns/querybyfactory#runqueryfilteroperand */ //Query data factory for pipeline runs IList <string> pipelineList = new List <string> { pipelineName }; IList <RunQueryFilter> moreParams = new List <RunQueryFilter>(); moreParams.Add(new RunQueryFilter { Operand = RunQueryFilterOperand.PipelineName, OperatorProperty = RunQueryFilterOperator.Equals, Values = pipelineList }); RunFilterParameters filterParams = new RunFilterParameters(lastWeek, today, null, moreParams, null); var requiredRuns = client.PipelineRuns.QueryByFactory(resourceGroup, factoryName, filterParams); var enumerator = requiredRuns.Value.GetEnumerator(); //Get latest run id for (bool hasMoreRuns = enumerator.MoveNext(); hasMoreRuns;) { pipelineRuns = enumerator.Current; hasMoreRuns = enumerator.MoveNext(); if (!hasMoreRuns && pipelineRuns.PipelineName == pipelineName) //&& just incase, filter above should deal with this { //Get run id runId = pipelineRuns.RunId; } } //Wait for success or fail while (true) { pipelineRun = client.PipelineRuns.Get(resourceGroup, factoryName, runId); //Console.WriteLine("Status: " + pipelineRun.Status); if (pipelineRun.Status == "InProgress" || pipelineRun.Status == "Queued") { System.Threading.Thread.Sleep(15000); } else { break; } } //Get error details if (pipelineRun.Status != "Succeeded") { // Check the pipeline if it wasn't successful RunFilterParameters filterParamsForError = new RunFilterParameters(lastWeek, today); queryResponse = client.ActivityRuns.QueryByPipelineRun(resourceGroup, factoryName, runId, filterParamsForError); errorDetails = queryResponse.Value.First().Error.ToString(); } //Prepare output outputString = "{ \"PipelineName\": \"" + pipelineName + "\", \"RunIdUsed\": \"" + runId + "\", \"Status\": \"" + pipelineRun.Status + "\" }"; JObject json = JObject.Parse(outputString); return(pipelineRun.Status == "Succeeded" ? (ActionResult) new OkObjectResult(json) : new BadRequestObjectResult($"{errorDetails}")); }
public void TestPostWithResponse() { var tokenCredentials = new TokenCredentials("123", "abc"); var handler = new PlaybackTestHandler(MockPostWithResourceSku()); var fakeClient = new RedisManagementClient(tokenCredentials, handler); fakeClient.LongRunningOperationInitialTimeout = fakeClient.LongRunningOperationRetryTimeout = 0; var resource = fakeClient.RedisOperations.Post("rg", "redis", "1234"); Assert.Equal(2, handler.Requests.Count); Assert.Equal(HttpMethod.Post, handler.Requests[0].Method); Assert.Equal("https://management.azure.com/subscriptions/1234/resourceGroups/rg/providers/Microsoft.Cache/Redis/redis", handler.Requests[0].RequestUri.ToString()); Assert.Equal(HttpMethod.Get, handler.Requests[1].Method); Assert.Equal("http://custom/status", handler.Requests[1].RequestUri.ToString()); Assert.Equal("Family", resource.Family); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); //Get body values string tenantId = req.Query["tenantId"]; string applicationId = req.Query["applicationId"]; string authenticationKey = req.Query["authenticationKey"]; string subscriptionId = req.Query["subscriptionId"]; string resourceGroup = req.Query["resourceGroup"]; string factoryName = req.Query["factoryName"]; string pipelineName = req.Query["pipelineName"]; int daysOfRuns = int.Parse(Environment.GetEnvironmentVariable("DefaultDaysForPipelineRuns")); string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); tenantId = tenantId ?? data?.tenantId; applicationId = applicationId ?? data?.applicationId; authenticationKey = authenticationKey ?? data?.authenticationKey; subscriptionId = subscriptionId ?? data?.subscriptionId; resourceGroup = resourceGroup ?? data?.resourceGroup; factoryName = factoryName ?? data?.factoryName; pipelineName = pipelineName ?? data?.pipelineName; //Check body for values if ( tenantId == null || applicationId == null || authenticationKey == null || subscriptionId == null || factoryName == null || pipelineName == null ) { return(new BadRequestObjectResult("Invalid request body, value missing.")); } //Create a data factory management client var context = new AuthenticationContext("https://login.windows.net/" + tenantId); ClientCredential cc = new ClientCredential(applicationId, authenticationKey); AuthenticationResult result = context.AcquireTokenAsync("https://management.azure.com/", cc).Result; ServiceClientCredentials cred = new TokenCredentials(result.AccessToken); var client = new DataFactoryManagementClient(cred) { SubscriptionId = subscriptionId }; //Get pipeline status PipelineRun pipelineRuns; //used to find latest pipeline run id PipelineRun pipelineRun; //used to get the status of the last pipeline string pipelineStatus = String.Empty; string runId = String.Empty; string outputString; DateTime today = DateTime.Now; DateTime lastWeek = DateTime.Now.AddDays(-daysOfRuns); /* * https://docs.microsoft.com/en-us/rest/api/datafactory/pipelineruns/querybyfactory#runqueryfilteroperand */ //Query data factory for pipeline runs IList <string> pipelineList = new List <string> { pipelineName }; IList <RunQueryFilter> moreParams = new List <RunQueryFilter>(); moreParams.Add(new RunQueryFilter { Operand = RunQueryFilterOperand.PipelineName, OperatorProperty = RunQueryFilterOperator.Equals, Values = pipelineList }); RunFilterParameters filterParams = new RunFilterParameters(lastWeek, today, null, moreParams, null); var requiredRuns = client.PipelineRuns.QueryByFactory(resourceGroup, factoryName, filterParams); var enumerator = requiredRuns.Value.GetEnumerator(); //Get latest run id for (bool hasMoreRuns = enumerator.MoveNext(); hasMoreRuns;) { pipelineRuns = enumerator.Current; hasMoreRuns = enumerator.MoveNext(); if (!hasMoreRuns && pipelineRuns.PipelineName == pipelineName) { //Get status for run id runId = pipelineRuns.RunId; pipelineStatus = client.PipelineRuns.Get(resourceGroup, factoryName, runId).Status; } } //Prepare output outputString = "{ \"PipelineName\": \"" + pipelineName + "\", \"RunIdUsed\": \"" + runId + "\", \"Status\": \"" + pipelineStatus + "\" }"; JObject json = JObject.Parse(outputString); return(new OkObjectResult(json)); }
public void TestCreateOrUpdateErrorHandling() { var tokenCredentials = new TokenCredentials("123", "abc"); var handler = new PlaybackTestHandler(MockCreateOrUpdateWithImmediateServerError()); var fakeClient = new RedisManagementClient(tokenCredentials, handler); fakeClient.LongRunningOperationInitialTimeout = fakeClient.LongRunningOperationRetryTimeout = 0; try { fakeClient.RedisOperations.CreateOrUpdate("rg", "redis", new RedisCreateOrUpdateParameters(), "1234"); Assert.False(true, "Expected exception was not thrown."); } catch(CloudException ex) { Assert.Equal("The provided database ‘foo’ has an invalid username.", ex.Message); } }
public void DefaultPolicyTicketAuthentication() { AddResourceSetResponse resourceSetResponse = null !; UmaClient umaClient = null !; TokenClient client = null !; GrantedTokenResponse result = null !; string ticketId = null !; "and a properly configured token client".x( () => client = new TokenClient( TokenCredentials.FromClientCredentials("post_client", "post_client"), _fixture.Client, new Uri(WellKnownOpenidConfiguration))); "when requesting token".x( async() => { var response = await client .GetToken(TokenRequest.FromPassword("user", "password", new[] { "uma_protection" })) .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result; result = response.Item; }); "then has valid access token".x( () => { var tokenHandler = new JwtSecurityTokenHandler(); var validationParameters = new TokenValidationParameters { IssuerSigningKeys = _jwks.GetSigningKeys(), ValidAudience = "post_client", ValidIssuer = "https://localhost" }; tokenHandler.ValidateToken(result.AccessToken, validationParameters, out var token); Assert.NotEmpty(((JwtSecurityToken)token).Claims); }); "given a uma client".x( () => { umaClient = new UmaClient(_fixture.Client, new Uri("https://localhost/")); }); "when creating resource set without a policy".x( async() => { var resourceSet = new ResourceSet { Name = "Local", Scopes = new[] { "api1" }, Type = "url", AuthorizationPolicies = null }; var resourceResponse = await umaClient.AddResource(resourceSet, result.AccessToken).ConfigureAwait(false) as Option <AddResourceSetResponse> .Result; resourceSetResponse = resourceResponse.Item; Assert.NotNull(resourceResponse); }); "then can get redirection".x( async() => { var request = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri("http://localhost/data/" + resourceSetResponse.Id) }; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); var response = await _fixture.Client().SendAsync(request).ConfigureAwait(false); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); var httpHeaderValueCollection = response.Headers.WwwAuthenticate; Assert.True(httpHeaderValueCollection != null); var match = Regex.Match( httpHeaderValueCollection.First().Parameter, ".+ticket=\"(.+)\".*", RegexOptions.Compiled); ticketId = match.Groups[1].Value; }); "when requesting token".x( async() => { var response = await client.GetToken(TokenRequest.FromTicketId(ticketId, result.IdToken)) .ConfigureAwait(false); Assert.IsType <Option <GrantedTokenResponse> .Error>(response); }); }
public void TestDeleteWithLocationHeaderErrorHandling() { var tokenCredentials = new TokenCredentials("123", "abc"); var handler = new PlaybackTestHandler(MockDeleteWithLocationHeaderError()); var fakeClient = new RedisManagementClient(tokenCredentials, handler); fakeClient.LongRunningOperationInitialTimeout = fakeClient.LongRunningOperationRetryTimeout = 0; try { fakeClient.RedisOperations.Delete("rg", "redis", "1234"); Assert.False(true, "Expected exception was not thrown."); } catch (CloudException ex) { Assert.Null(ex.Body); } }
public void UnsuccessfulTicketAuthentication() { Option <GrantedTokenResponse> ticketResponse = null !; AddResourceSetResponse resourceSetResponse = null !; UmaClient umaClient = null !; TokenClient client = null !; GrantedTokenResponse result = null !; string ticketId = null !; "and a properly configured token client".x( () => client = new TokenClient( TokenCredentials.FromClientCredentials("post_client", "post_client"), _fixture.Client, new Uri(WellKnownOpenidConfiguration))); "when requesting token".x( async() => { var response = await client .GetToken(TokenRequest.FromPassword("user", "password", new[] { "uma_protection" })) .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result; result = response.Item; }); "then has valid access token".x( () => { var tokenHandler = new JwtSecurityTokenHandler(); var validationParameters = new TokenValidationParameters { IssuerSigningKeys = _jwks.GetSigningKeys(), ValidAudience = "post_client", ValidIssuer = "https://localhost" }; tokenHandler.ValidateToken(result.AccessToken, validationParameters, out var token); Assert.NotEmpty(((JwtSecurityToken)token).Claims); }); "given a uma client".x( () => { umaClient = new UmaClient( _fixture.Client, new Uri("https://localhost/.well-known/uma2-configuration")); }); "when creating resource set with deviating scopes".x( async() => { var resourceSet = new ResourceSet { Name = "Local", Scopes = new[] { "api1" }, Type = "url", AuthorizationPolicies = new[] { new PolicyRule { Scopes = new[] { "anotherApi" }, Claims = new[] { new ClaimData { Type = "sub", Value = "user" } }, ClientIdsAllowed = new[] { "post_client" }, IsResourceOwnerConsentNeeded = false } } }; var resourceResponse = await umaClient.AddResource(resourceSet, result.AccessToken).ConfigureAwait(false) as Option <AddResourceSetResponse> .Result; Assert.NotNull(resourceResponse); resourceSetResponse = resourceResponse.Item; }); "and requesting permission ticket".x( async() => { var permission = new PermissionRequest { ResourceSetId = resourceSetResponse.Id, Scopes = new[] { "api1" } }; var permissionResponse = await umaClient.RequestPermission(result.AccessToken, requests: permission) .ConfigureAwait(false) as Option <TicketResponse> .Result; Assert.NotNull(permissionResponse); ticketId = permissionResponse.Item.TicketId; }); "and requesting token from ticket".x( async() => { ticketResponse = await client.GetToken(TokenRequest.FromTicketId(ticketId, result.IdToken)) .ConfigureAwait(false); }); "then has error".x(() => { Assert.IsType <Option <GrantedTokenResponse> .Error>(ticketResponse); }); }
public void TestDeleteWithRetryAfter() { var tokenCredentials = new TokenCredentials("123", "abc"); var handler = new PlaybackTestHandler(MockDeleteWithRetryAfterTwoTries()); var fakeClient = new RedisManagementClient(tokenCredentials, handler); var now = DateTime.Now; fakeClient.RedisOperations.Delete("rg", "redis", "1234"); Assert.True(DateTime.Now - now >= TimeSpan.FromSeconds(2)); }
public void SuccessfulTicketAuthentication() { GrantedTokenResponse umaToken = null !; AddResourceSetResponse resourceSetResponse = null !; UmaClient umaClient = null !; TokenClient client = null !; GrantedTokenResponse result = null !; string ticketId = null !; "and a properly configured token client".x( () => client = new TokenClient( TokenCredentials.FromClientCredentials("post_client", "post_client"), _fixture.Client, new Uri(WellKnownOpenidConfiguration))); "when requesting token".x( async() => { var response = await client .GetToken(TokenRequest.FromPassword("user", "password", new[] { "uma_protection", "offline" })) .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result; result = response.Item; }); "then has valid access token".x( () => { var tokenHandler = new JwtSecurityTokenHandler(); var validationParameters = new TokenValidationParameters { IssuerSigningKeys = _jwks.GetSigningKeys(), ValidAudience = "post_client", ValidIssuer = "https://localhost" }; tokenHandler.ValidateToken(result.AccessToken, validationParameters, out var token); Assert.NotEmpty(((JwtSecurityToken)token).Claims); }); "given a uma client".x( () => { umaClient = new UmaClient( _fixture.Client, new Uri("https://localhost/.well-known/uma2-configuration")); }); "when creating resource set".x( async() => { var resourceSet = new ResourceSet { Name = "Local", Scopes = new[] { "api1" }, Type = "url", }; var resourceResponse = await umaClient.AddResource(resourceSet, result.AccessToken).ConfigureAwait(false) as Option <AddResourceSetResponse> .Result; resourceSetResponse = resourceResponse.Item; Assert.NotNull(resourceResponse); }); "and setting access policy".x( async() => { var resourceSet = new ResourceSet { Id = resourceSetResponse.Id, Name = "Local", Scopes = new[] { "api1" }, Type = "url", AuthorizationPolicies = new[] { new PolicyRule { Scopes = new[] { "api1" }, Claims = new[] { new ClaimData { Type = ClaimTypes.NameIdentifier, Value = "user" } }, ClientIdsAllowed = new[] { "post_client" }, IsResourceOwnerConsentNeeded = false } } }; var resourceResponse = await umaClient.UpdateResource(resourceSet, result.AccessToken).ConfigureAwait(false) as Option <UpdateResourceSetResponse> .Result; Assert.NotNull(resourceResponse); }); "then can get redirection".x( async() => { var request = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri("http://localhost/data/" + resourceSetResponse.Id) }; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); var response = await _fixture.Client().SendAsync(request).ConfigureAwait(false); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); var httpHeaderValueCollection = response.Headers.WwwAuthenticate; Assert.True(httpHeaderValueCollection != null); var match = Regex.Match( httpHeaderValueCollection.First().Parameter, ".+ticket=\"(.+)\".*", RegexOptions.Compiled); ticketId = match.Groups[1].Value; }); "when requesting token".x( async() => { var response = await client.GetToken(TokenRequest.FromTicketId(ticketId, result.IdToken)) .ConfigureAwait(false) as Option <GrantedTokenResponse> .Result; umaToken = response.Item; Assert.NotNull(umaToken.AccessToken); }); "then can get resource with token".x( async() => { var request = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri("http://localhost/data/" + resourceSetResponse.Id) }; request.Headers.Authorization = new AuthenticationHeaderValue( umaToken.TokenType, umaToken.AccessToken); var response = await _fixture.Client().SendAsync(request).ConfigureAwait(false); var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("\"Hello\"", content); }); }
public void TestAsyncOperationWithMissingProvisioningState() { var tokenCredentials = new TokenCredentials("123", "abc"); var handler = new PlaybackTestHandler(MockAsyncOperaionWithMissingProvisioningState()); var fakeClient = new RedisManagementClient(tokenCredentials, handler); fakeClient.LongRunningOperationInitialTimeout = fakeClient.LongRunningOperationRetryTimeout = 0; var resource = fakeClient.RedisOperations.CreateOrUpdate("rg", "redis", new RedisCreateOrUpdateParameters(), "1234"); Assert.Equal("100", resource.Id); }
public SCAggView() { m_tokenCredentials = null; m_embedConfig = new EmbedConfig(); m_tileEmbedConfig = new TileEmbedConfig(); }