Skip to content
This repository was archived by the owner on Nov 14, 2024. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 src/Invictus.Testing.ResourceApi/ResourceApiAuthentication.cs
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
Copy link
Contributor

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?

Copy link
Author

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.

Copy link
Contributor

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?

Copy link
Author

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.

{
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();
}
}
}
Loading