This repository was archived by the owner on Nov 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
🚧 Provide a Resource API Helper and example for testing Application Insights #61
Open
paul-warwick-cdt
wants to merge
1
commit into
invictus-integration:master
Choose a base branch
from
paul-warwick-cdt:feature/pw/baseline-1-resourceapi
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
31 changes: 31 additions & 0 deletions
31
src/Invictus.Testing.ResourceApi/Invictus.Testing.ResourceApi.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFramework>netstandard2.0</TargetFramework> | ||
| <Authors>Codit</Authors> | ||
| <Company>Codit</Company> | ||
| <RepositoryType>Git</RepositoryType> | ||
| <PackageTags>Azure;Resource Api;Testing</PackageTags> | ||
| <Description>Provides capabilities for easily testing Azure resources via Api.</Description> | ||
| <Copyright>Copyright (c) Codit</Copyright> | ||
| <PackageLicenseUrl>https://github.com/invictus-integration/testing-framework/blob/master/LICENSE</PackageLicenseUrl> | ||
| <PackageProjectUrl>https://github.com/invictus-integration/testing-framework</PackageProjectUrl> | ||
| <RepositoryUrl>https://github.com/invictus-integration/testing-framework</RepositoryUrl> | ||
| <PackageIconUrl>https://raw.githubusercontent.com/invictus-integration/testing-framework/master/docs/images/invictus-small.png</PackageIconUrl> | ||
| <GeneratePackageOnBuild>true</GeneratePackageOnBuild> | ||
| <GenerateDocumentationFile>true</GenerateDocumentationFile> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Arcus.Security.Core" Version="1.2.0" /> | ||
| <PackageReference Include="Arcus.Testing.Logging" Version="0.1.0" /> | ||
| <PackageReference Include="Guard.NET" Version="1.2.0" /> | ||
| <PackageReference Include="Microsoft.Azure.Management.Logic" Version="4.1.0" /> | ||
| <PackageReference Include="Microsoft.Bcl.AsyncInterfaces" Version="1.1.1" /> | ||
| <PackageReference Include="Microsoft.CSharp" Version="4.7.0" /> | ||
| <PackageReference Include="Microsoft.Rest.ClientRuntime.Azure.Authentication" Version="2.4.0" /> | ||
| <PackageReference Include="Newtonsoft.Json" Version="12.0.3" /> | ||
| <PackageReference Include="Polly-Signed" Version="5.9.0" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
137 changes: 137 additions & 0 deletions
137
src/Invictus.Testing.ResourceApi/ResourceApiAuthentication.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| using GuardNet; | ||
| using System.Net.Http; | ||
| using System.Collections.Generic; | ||
| using System.Globalization; | ||
| using Newtonsoft.Json.Linq; | ||
| using System.Threading.Tasks; | ||
| using System; | ||
|
|
||
| using ISecretProvider = Arcus.Security.Core.ISecretProvider; | ||
| using Microsoft.IdentityModel.Clients.ActiveDirectory; | ||
|
|
||
| namespace Codit.Testing.ResourceApi | ||
| { | ||
| /// <summary> | ||
| /// Authentication representation to authenticate with resources running on Azure. | ||
| /// </summary> | ||
| public class ResourceApiAuthentication | ||
| { | ||
| private readonly Func<Task<string>> _authenticateAsync; | ||
| private ResourceApiAuthentication(Func<Task<string>> authenticateAsync) | ||
| { | ||
| Guard.NotNull(authenticateAsync, nameof(authenticateAsync)); | ||
|
|
||
| _authenticateAsync = authenticateAsync; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Uses the service principal to authenticate with Azure. | ||
| /// </summary> | ||
| /// <param name="tenantId">The ID where the resources are located on Azure.</param> | ||
| /// <param name="subscriptionId">The ID that identifies the subscription on Azure.</param> | ||
| /// <param name="clientId">The ID of the client or application that has access to the logic apps running on Azure.</param> | ||
| /// <param name="clientSecretKey">The secret of the client or application that has access to the logic apps running on Azure.</param> | ||
| /// <param name="secretProvider">The provider to get the client secret; using the <paramref name="clientSecretKey"/>.</param> | ||
| public static ResourceApiAuthentication UsingServicePrincipal(string tenantId, string subscriptionId, string clientId, string clientSecretKey, ISecretProvider secretProvider) | ||
| { | ||
| Guard.NotNullOrWhitespace(tenantId, nameof(tenantId)); | ||
| Guard.NotNullOrWhitespace(subscriptionId, nameof(subscriptionId)); | ||
| Guard.NotNullOrWhitespace(clientId, nameof(clientId)); | ||
| Guard.NotNullOrWhitespace(clientSecretKey, nameof(clientSecretKey)); | ||
| Guard.NotNull(secretProvider, nameof(secretProvider)); | ||
|
|
||
| return new ResourceApiAuthentication(async () => | ||
| { | ||
| string clientSecret = await secretProvider.GetRawSecretAsync(clientSecretKey); | ||
| var managementClient = await AuthenticateResourceManagerAsync(subscriptionId, tenantId, clientId, clientSecret); | ||
| return managementClient; | ||
| }); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Uses the service principal to authenticate with Azure. | ||
| /// </summary> | ||
| /// <param name="tenantId">The ID where the resources are located on Azure.</param> | ||
| /// <param name="subscriptionId">The ID that identifies the subscription on Azure.</param> | ||
| /// <param name="clientId">The ID of the client or application that has access to the logic apps running on Azure.</param> | ||
| /// <param name="clientSecret">The secret of the client or application that has access to the logic apps running on Azure.</param> | ||
| public static ResourceApiAuthentication UsingServicePrincipal(string tenantId, string subscriptionId, string clientId, string clientSecret) | ||
| { | ||
| Guard.NotNullOrWhitespace(tenantId, nameof(tenantId)); | ||
| Guard.NotNullOrWhitespace(subscriptionId, nameof(subscriptionId)); | ||
| Guard.NotNullOrWhitespace(clientId, nameof(clientId)); | ||
| Guard.NotNullOrWhitespace(clientSecret, nameof(clientSecret)); | ||
|
|
||
| return new ResourceApiAuthentication( | ||
| () => AuthenticateResourceManagerAsync(subscriptionId, tenantId, clientId, clientSecret)); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Uses the service principal to authenticate with Azure. | ||
| /// </summary> | ||
| /// <param name="tenantId">The ID where the resources are located on Azure.</param> | ||
| /// <param name="subscriptionId">The ID that identifies the subscription on Azure.</param> | ||
| /// <param name="clientId">The ID of the client or application that has access to the logic apps running on Azure.</param> | ||
| /// <param name="clientSecret">The secret of the client or application that has access to the logic apps running on Azure.</param> | ||
| /// <param name="resource">The resource string for Auth context.</param> | ||
| /// <param name="authUri">The authUri context.</param> | ||
| public static ResourceApiAuthentication UsingServicePrincipal(string tenantId, string subscriptionId, string clientId, string clientSecret, string resource, string authUri) | ||
| { | ||
| Guard.NotNullOrWhitespace(tenantId, nameof(tenantId)); | ||
| Guard.NotNullOrWhitespace(clientId, nameof(clientId)); | ||
| Guard.NotNullOrWhitespace(clientSecret, nameof(clientSecret)); | ||
| Guard.NotNullOrWhitespace(subscriptionId, nameof(authUri)); | ||
| Guard.NotNullOrWhitespace(subscriptionId, nameof(resource)); | ||
|
|
||
| string authority = string.Format(CultureInfo.InvariantCulture, authUri, tenantId); | ||
|
|
||
| return new ResourceApiAuthentication( | ||
| () => AccessTokenUmt(clientId, clientSecret, resource, authority)); | ||
| } | ||
| /// <summary> | ||
| /// Authenticate with Azure with the previously chosen authentication mechanism. | ||
| /// </summary> | ||
| /// <returns> | ||
| /// The management client to interact with logic app resources running on Azure. | ||
| /// </returns> | ||
| public async Task<string> AuthenticateAsync() | ||
| { | ||
| return await _authenticateAsync(); | ||
| } | ||
|
|
||
| private static Task<string> AccessTokenUmt(string clientId, string clientSecret, string adAppId, string authContext) | ||
| { | ||
| Task<string> token = Task<string>.Factory.StartNew(() => | ||
| { | ||
| var clientCredential = new ClientCredential(clientId, clientSecret); | ||
| AuthenticationContext context = new AuthenticationContext(authContext, false); | ||
| AuthenticationResult authenticationResult = context.AcquireTokenAsync(adAppId, clientCredential).Result; | ||
|
|
||
| return authenticationResult.AccessToken; | ||
| }); | ||
| return token; | ||
| } | ||
|
|
||
| private static async Task<string> AuthenticateResourceManagerAsync(string subscriptionId, string tenantId, string clientId, string clientSecret) | ||
| { | ||
| string baseAddress = string.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{0}/oauth2/token", tenantId); | ||
| string resource = "https://management.azure.com/"; | ||
| string grant_type = "client_credentials"; | ||
|
|
||
| var form = new Dictionary<string, string> | ||
| { | ||
| {"grant_type", grant_type}, | ||
| {"client_id", clientId}, | ||
| {"client_secret", clientSecret}, | ||
| {"resource", resource}, | ||
| }; | ||
|
|
||
| var httpClient = new System.Net.Http.HttpClient(); | ||
| HttpResponseMessage tokenResponse = await httpClient.PostAsync(baseAddress, new FormUrlEncodedContent(form)); | ||
| var jsonContent = await tokenResponse.Content.ReadAsStringAsync(); | ||
| dynamic data = JObject.Parse(jsonContent); | ||
| var token = ((Newtonsoft.Json.Linq.JValue)((Newtonsoft.Json.Linq.JProperty)((Newtonsoft.Json.Linq.JContainer)data).Last).Value).Value; | ||
| return token.ToString(); | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can't we refactor our existing authentication and use that?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes the token output of the Logic Apps is the same.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes that is correct, but I think we should be able to re-use the authentication since it's the same, no?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes a refactor of the Authenticator to give it generic naming and decouple from being Logic App specific would allow this PR to be re-factored and retested. Will proceed on that basis.