Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds TokenCredential PrincipalId lookup #43

Closed
wants to merge 1 commit into from
Closed
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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -348,3 +348,6 @@ MigrationBackup/

# Ionide (cross platform F# VS Code tools) working folder
.ionide/

# Ignore jetbrains rider
.idea/
26 changes: 26 additions & 0 deletions src/AzureCacheForRedis.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,32 @@ public static async Task<ConfigurationOptions> ConfigureForAzureWithTokenCredent
PrincipalId = userName,
TokenCredential = tokenCredential
}).ConfigureAwait(false);

/// <summary>
/// Configures a Redis connection authenticated using a TokenCredential.
/// </summary>
/// <param name="configurationOptions">The configuration to update.</param>
/// <param name="tokenCredential">The TokenCredential to be used.</param>
/// <returns></returns>
public static async Task<ConfigurationOptions> ConfigureForAzureWithTokenCredentialAsync(this ConfigurationOptions configurationOptions, TokenCredential tokenCredential)
{
var client = CacheIdentityClient.CreateForTokenCredential(tokenCredential);
var token = await client.GetTokenAsync();

if(!TokenHelpers.TryGetOidFromToken(token.Token, out var oid))
{
throw new InvalidOperationException("Token does not contain an OID claim.");
}

return await ConfigureForAzureAsync(
configurationOptions,
new AzureCacheOptions
{
PrincipalId = oid,
TokenCredential = tokenCredential
})
.ConfigureAwait(false);
}

/// <summary>
/// Configures a connection to an Azure Cache for Redis using advanced options.
Expand Down
3 changes: 2 additions & 1 deletion src/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
#nullable enable
#nullable enable
static StackExchange.Redis.AzureCacheForRedis.ConfigureForAzureWithTokenCredentialAsync(this StackExchange.Redis.ConfigurationOptions! configurationOptions, Azure.Core.TokenCredential! tokenCredential) -> System.Threading.Tasks.Task<StackExchange.Redis.ConfigurationOptions!>!
50 changes: 50 additions & 0 deletions src/TokenHelpers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Buffers.Text;

namespace StackExchange.Redis
{
internal static class TokenHelpers
{
public static bool TryGetOidFromToken(string token, out string? oid)
{
oid = null;

if (string.IsNullOrEmpty(token))
{
return false;
}

var parts = token.Split('.');

if (parts.Length < 2)
{
return false;
}

try
{
var decoded = Convert.FromBase64String(parts[1]);

var json = System.Text.Encoding.UTF8.GetString(decoded);

var jwt = System.Text.Json.JsonDocument.Parse(json);

if (jwt.RootElement.TryGetProperty("oid", out var oidElement))
{
oid = oidElement.GetString();
return true;
}

return false;
}
catch
{
return false;
}
}
}
}
98 changes: 98 additions & 0 deletions tests/TokenHelpersTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using StackExchange.Redis;

namespace Microsoft.Azure.StackExchangeRedis.Tests
{
[TestClass]
public sealed class TokenHelpersTests
{
[TestMethod]
public void TryGetOidFromToken_Should_ReturnFalse_When_TokenIsEmpty()
{
// Arrange
const string token = "";

// Act
var result = TokenHelpers.TryGetOidFromToken(token, out var oid);

// Assert
Assert.IsFalse(result);
Assert.IsNull(oid);
}

[TestMethod]
public void TryGetOidFromToken_Should_ReturnFalse_When_TokenHasLessThanTwoParts()
{
// Arrange
const string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";

// Act
var result = TokenHelpers.TryGetOidFromToken(token, out var oid);

// Assert
Assert.IsFalse(result);
Assert.IsNull(oid);
}

[TestMethod]
public void TryGetOidFromToken_Should_ReturnFalse_When_TokenIsValidButNoOid()
{
// Arrange
const string token =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJvdGhlciI6IjEyMzQ1Njc4OTAifQ==";

// Act
var result = TokenHelpers.TryGetOidFromToken(token, out var oid);

// Assert
Assert.IsFalse(result);
Assert.IsNull(oid);
}

[TestMethod]
public void TryGetOidFromToken_Should_ReturnTrueAndOid_When_TokenIsValid()
{
// Arrange
const string token =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJvaWQiOiIxMjM0NTY3ODkwIn0=";

// Act
var result = TokenHelpers.TryGetOidFromToken(token, out var oid);

// Assert
Assert.IsTrue(result);
Assert.AreEqual("1234567890", oid);
}

[TestMethod]
public void TryGetOidFromToken_Should_ReturnFalse_When_TokenIsInvalidBase64String()
{
// Arrange
const string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.invalidbase64";

// Act
var result = TokenHelpers.TryGetOidFromToken(token, out var oid);

// Assert
Assert.IsFalse(result);
Assert.IsNull(oid);
}

[TestMethod]
public void TryGetOidFromToken_Should_ThrowFormatException_When_TokenHasInvalidJsonFormat()
{
// Arrange
const string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.W10="; // W10= -> []

// Act
var result = TokenHelpers.TryGetOidFromToken(token, out var oid);

// Assert
Assert.IsFalse(result);
Assert.IsNull(oid);
}
}
}