Skip to content

Commit

Permalink
Remove test reference to deprecated ADAL library (#2360)
Browse files Browse the repository at this point in the history
  • Loading branch information
David-Engel authored Mar 1, 2024
1 parent 1a009b4 commit ced726a
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 66 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,11 @@
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace Microsoft.Data.SqlClient.ManualTesting.Tests
{
public static class AADUtility
{
public static async Task<string> AzureActiveDirectoryAuthenticationCallback(string authority, string resource, string scope)
{
var authContext = new AuthenticationContext(authority);
ClientCredential clientCred = new ClientCredential(DataTestUtility.AKVClientId, DataTestUtility.AKVClientSecret);
AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);
if (result == null)
{
throw new Exception($"Failed to retrieve an access token for {resource}");
}

return result.AccessToken;
}

public static async Task<string> GetManagedIdentityToken(string clientId = null) =>
await new MockManagedIdentityTokenProvider().AcquireTokenAsync(clientId).ConfigureAwait(false);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,21 @@
// See the LICENSE file in the project root for more information.

using System;
using System.IdentityModel.Tokens.Jwt;
using System.Collections.Concurrent;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Azure.Identity;

namespace Microsoft.Data.SqlClient.ManualTesting.Tests
{
public class SqlClientCustomTokenCredential : TokenCredential
{
private const string DEFAULT_PREFIX = "/.default";
private static readonly ConcurrentDictionary<string, ClientSecretCredential> s_clientSecretCredentials = new();

string _authority = "";
string _resource = "";
string _akvUrl = "";
Expand Down Expand Up @@ -70,40 +71,8 @@ private async Task<AccessToken> AcquireTokenAsync()
_akvUrl = DataTestUtility.AKVUrl;
}

string strAccessToken = await AzureActiveDirectoryAuthenticationCallback(_authority, _resource);
DateTime expiryTime = InterceptAccessTokenForExpiry(strAccessToken);
return new AccessToken(strAccessToken, new DateTimeOffset(expiryTime));
}

private DateTime InterceptAccessTokenForExpiry(string accessToken)
{
if (null == accessToken)
{
throw new ArgumentNullException(accessToken);
}

var jwtHandler = new JwtSecurityTokenHandler();
var jwtOutput = string.Empty;

// Check Token Format
if (!jwtHandler.CanReadToken(accessToken))
throw new FormatException(accessToken);

JwtSecurityToken token = jwtHandler.ReadJwtToken(accessToken);

// Re-serialize the Token Headers to just Key and Values
var jwtHeader = JsonConvert.SerializeObject(token.Header.Select(h => new { h.Key, h.Value }));
jwtOutput = $"{{\r\n\"Header\":\r\n{JToken.Parse(jwtHeader)},";

// Re-serialize the Token Claims to just Type and Values
var jwtPayload = JsonConvert.SerializeObject(token.Claims.Select(c => new { c.Type, c.Value }));
jwtOutput += $"\r\n\"Payload\":\r\n{JToken.Parse(jwtPayload)}\r\n}}";

// Output the whole thing to pretty JSON object formatted.
string jToken = JToken.Parse(jwtOutput).ToString(Formatting.Indented);
JToken payload = JObject.Parse(jToken).GetValue("Payload");

return new DateTime(1970, 1, 1).AddSeconds((long)payload[4]["Value"]);
AccessToken accessToken = await AzureActiveDirectoryAuthenticationCallback(_authority, _resource);
return accessToken;
}

private static string ValidateChallenge(string challenge)
Expand All @@ -127,16 +96,20 @@ private static string ValidateChallenge(string challenge)
/// <param name="authority">Authorization URL</param>
/// <param name="resource">Resource</param>
/// <returns></returns>
public static async Task<string> AzureActiveDirectoryAuthenticationCallback(string authority, string resource)
public static async Task<AccessToken> AzureActiveDirectoryAuthenticationCallback(string authority, string resource)
{
var authContext = new AuthenticationContext(authority);
ClientCredential clientCred = new ClientCredential(DataTestUtility.AKVClientId, DataTestUtility.AKVClientSecret);
AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);
if (result == null)
{
throw new InvalidOperationException($"Failed to retrieve an access token for {resource}");
}
return result.AccessToken;
using CancellationTokenSource cts = new();
cts.CancelAfter(30000); // Hard coded for tests
string[] scopes = new string[] { resource + DEFAULT_PREFIX };
TokenRequestContext tokenRequestContext = new(scopes);
int separatorIndex = authority.LastIndexOf('/');
string authorityHost = authority.Remove(separatorIndex + 1);
string audience = authority.Substring(separatorIndex + 1);
TokenCredentialOptions tokenCredentialOptions = new TokenCredentialOptions() { AuthorityHost = new Uri(authorityHost) };
ClientSecretCredential clientSecretCredential = s_clientSecretCredentials.GetOrAdd(authority + "|--|" + resource,
new ClientSecretCredential(audience, DataTestUtility.AKVClientId, DataTestUtility.AKVClientSecret, tokenCredentialOptions));
AccessToken accessToken = await clientSecretCredential.GetTokenAsync(tokenRequestContext, cts.Token).ConfigureAwait(false);
return accessToken;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -332,17 +332,14 @@
<PackageReference Include="Microsoft.DotNet.XUnitExtensions" Version="$(MicrosoftDotNetXUnitExtensionsVersion)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" />
<PackageReference Condition="$(ReferenceType.Contains('Package'))" Include="Microsoft.Identity.Client" Version="$(MicrosoftIdentityClientVersion)" />
<PackageReference Condition="$(ReferenceType.Contains('Package'))" Include="Microsoft.Win32.Registry" Version="$(MicrosoftWin32RegistryVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(AddOnsPath)AzureKeyVaultProvider\Microsoft.Data.SqlClient.AlwaysEncrypted.AzureKeyVaultProvider.csproj" />
<PackageReference Include="Azure.Identity" Version="$(AzureIdentityVersion)" />
<PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="$(MicrosoftIdentityModelClientsActiveDirectoryVersion)" />
<PackageReference Include="System.Runtime.Caching" Version="$(SystemRuntimeCachingVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="$(MicrosoftNETTestSdkVersion)" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="$(SystemIdentityModelTokensJwtVersion)" />
<PackageReference Condition="'$(TargetGroup)'=='netfx'" Include="Microsoft.SqlServer.Types" Version="$(MicrosoftSqlServerTypesVersion)" />
<PackageReference Condition="'$(TargetGroup)'=='netcoreapp'" Include="Microsoft.SqlServer.Types" Version="$(MicrosoftSqlServerTypesVersionNet)" />
<PackageReference Condition="'$(TargetGroup)'=='netcoreapp'" Include="Microsoft.DotNet.RemoteExecutor" Version="$(MicrosoftDotnetRemoteExecutorVersion)" />
Expand Down
2 changes: 0 additions & 2 deletions tools/props/Versions.props
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,10 @@
<PropertyGroup>
<MicrosoftDotNetXUnitExtensionsVersion>9.0.0-beta.23613.3</MicrosoftDotNetXUnitExtensionsVersion>
<MicrosoftDotNetPlatformAbstractionsVersion>3.1.6</MicrosoftDotNetPlatformAbstractionsVersion>
<MicrosoftIdentityModelClientsActiveDirectoryVersion>5.2.9</MicrosoftIdentityModelClientsActiveDirectoryVersion>
<MicrosoftNETTestSdkVersion>17.8.0</MicrosoftNETTestSdkVersion>
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
<SystemRuntimeInteropServicesRuntimeInformationVersion>4.3.0</SystemRuntimeInteropServicesRuntimeInformationVersion>
<SystemDataOdbcVersion>6.0.1</SystemDataOdbcVersion>
<SystemIdentityModelTokensJwtVersion>6.35.0</SystemIdentityModelTokensJwtVersion>
<XunitVersion>2.6.3</XunitVersion>
<XunitrunnervisualstudioVersion>2.5.5</XunitrunnervisualstudioVersion>
<MicrosoftNETFrameworkReferenceAssembliesVersion>1.0.3</MicrosoftNETFrameworkReferenceAssembliesVersion>
Expand Down

0 comments on commit ced726a

Please sign in to comment.