Skip to content
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
Expand Up @@ -15,6 +15,7 @@
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
Expand All @@ -28,6 +29,35 @@ namespace Microsoft.Graph.PowerShell.Authentication.Core.Utilities
/// </summary>
public static class AuthenticationHelpers
{
private static readonly TimeSpan AccessTokenRefreshWindow = TimeSpan.FromMinutes(5);

/// <summary>
/// Gets a cached access token, refreshing it when forced or within five minutes of expiry.
/// </summary>
public static async Task<(SecureString Token, DateTimeOffset ExpiresOn)> GetAccessTokenAsync(
IAuthContext authContext, string[] scopes, bool forceRefresh = false, CancellationToken cancellationToken = default)
{
if (authContext is null)
throw new AuthenticationException(ErrorConstants.Message.MissingAuthContext);
if (scopes == null || !scopes.Any())
throw new ArgumentException("At least one scope is required.", nameof(scopes));

string cacheKey = string.Join(" ", scopes.OrderBy(scope => scope, StringComparer.OrdinalIgnoreCase));
bool hasCachedToken = GraphSession.Instance.AccessTokenCache.TryGetValue(cacheKey, out AccessToken accessToken);
if (forceRefresh || !hasCachedToken || accessToken.ExpiresOn - DateTimeOffset.UtcNow < AccessTokenRefreshWindow)
{
var tokenCredential = await GetTokenCredentialAsync(authContext, cancellationToken).ConfigureAwait(false);
accessToken = await tokenCredential.GetTokenAsync(new TokenRequestContext(scopes), cancellationToken).ConfigureAwait(false);
GraphSession.Instance.AccessTokenCache[cacheKey] = accessToken;
}

var secureToken = new SecureString();
foreach (char character in accessToken.Token)
secureToken.AppendChar(character);
secureToken.MakeReadOnly();
return (secureToken, accessToken.ExpiresOn);
}

/// <summary>
/// Gets a <see cref="TokenCredential"/> using the provide <see cref="IAuthContext"/>.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using Azure.Core;
using Azure.Identity;
using Microsoft.Graph.Authentication.Test.Mocks;
using Microsoft.Graph.PowerShell;
using Microsoft.Graph.PowerShell.Authentication;
using Microsoft.Graph.PowerShell.Authentication.Core.Extensions;
using Microsoft.Graph.PowerShell.Authentication.Core.TokenCache;
using Microsoft.Graph.PowerShell.Authentication.Core.Utilities;
using System;
Expand Down Expand Up @@ -31,6 +33,86 @@ public AuthenticationHelpersTests()
mockAuthRecord.SerializeToFile();
}

[Fact]
public async Task GetAccessTokenAcquiresAndCachesTokenAsync()
{
GraphSession.Instance.InMemoryTokenCache = new InMemoryTokenCache(Encoding.UTF8.GetBytes(MockConstants.DummyAccessToken));
var authContext = new AuthContext { AuthType = AuthenticationType.UserProvidedAccessToken };

var result = await AuthenticationHelpers.GetAccessTokenAsync(authContext, new[] { "User.Read" });

using (result.Token)
{
Assert.True(result.Token.IsReadOnly());
Assert.Equal(MockConstants.DummyAccessToken, result.Token.ConvertToString());
var cachedToken = Assert.Single(GraphSession.Instance.AccessTokenCache).Value;
Assert.Equal(MockConstants.DummyAccessToken, cachedToken.Token);
Assert.Equal(cachedToken.ExpiresOn, result.ExpiresOn);
}
}

[Fact]
public async Task GetAccessTokenReusesCacheForReorderedScopesAsync()
{
var expiresOn = DateTimeOffset.UtcNow.AddHours(1);
GraphSession.Instance.AccessTokenCache["Mail.Read User.Read"] = new AccessToken("cached-token", expiresOn);
var authContext = new AuthContext { AuthType = AuthenticationType.UserProvidedAccessToken };

var result = await AuthenticationHelpers.GetAccessTokenAsync(authContext, new[] { "User.Read", "Mail.Read" });

using (result.Token)
{
Assert.Equal("cached-token", result.Token.ConvertToString());
Assert.Equal(expiresOn, result.ExpiresOn);
Assert.Single(GraphSession.Instance.AccessTokenCache);
}
}

[Theory]
[InlineData(false, -1)]
[InlineData(false, 4)]
[InlineData(true, 60)]
public async Task GetAccessTokenRefreshesCacheAsync(bool forceRefresh, int minutesUntilExpiry)
{
GraphSession.Instance.InMemoryTokenCache = new InMemoryTokenCache(Encoding.UTF8.GetBytes(MockConstants.DummyAccessToken));
GraphSession.Instance.AccessTokenCache["User.Read"] = new AccessToken("cached-token", DateTimeOffset.UtcNow.AddMinutes(minutesUntilExpiry));
var authContext = new AuthContext { AuthType = AuthenticationType.UserProvidedAccessToken };

var result = await AuthenticationHelpers.GetAccessTokenAsync(authContext, new[] { "User.Read" }, forceRefresh);

using (result.Token)
{
Assert.Equal(MockConstants.DummyAccessToken, result.Token.ConvertToString());
Assert.Equal(MockConstants.DummyAccessToken, GraphSession.Instance.AccessTokenCache["User.Read"].Token);
Assert.Equal(GraphSession.Instance.AccessTokenCache["User.Read"].ExpiresOn, result.ExpiresOn);
}
}

[Fact]
public async Task GetAccessTokenDoesNotReuseDifferentScopesAsync()
{
GraphSession.Instance.InMemoryTokenCache = new InMemoryTokenCache(Encoding.UTF8.GetBytes(MockConstants.DummyAccessToken));
GraphSession.Instance.AccessTokenCache["Mail.Read"] = new AccessToken("cached-token", DateTimeOffset.UtcNow.AddHours(1));
var authContext = new AuthContext { AuthType = AuthenticationType.UserProvidedAccessToken };

var result = await AuthenticationHelpers.GetAccessTokenAsync(authContext, new[] { "User.Read" });

using (result.Token)
{
Assert.Equal(MockConstants.DummyAccessToken, result.Token.ConvertToString());
Assert.Equal("cached-token", GraphSession.Instance.AccessTokenCache["Mail.Read"].Token);
Assert.Equal(2, GraphSession.Instance.AccessTokenCache.Count);
}
}

[Fact]
public async Task GetAccessTokenRejectsMissingContextAndScopesAsync()
{
await Assert.ThrowsAsync<AuthenticationException>(() => AuthenticationHelpers.GetAccessTokenAsync(null, new[] { "User.Read" }));
await Assert.ThrowsAsync<ArgumentException>(() => AuthenticationHelpers.GetAccessTokenAsync(new AuthContext(), null));
await Assert.ThrowsAsync<ArgumentException>(() => AuthenticationHelpers.GetAccessTokenAsync(new AuthContext(), Array.Empty<string>()));
}

[Fact]
public async Task ShouldUseDelegateAuthProviderWhenUserAccessTokenIsProvidedAsync()
{
Expand Down Expand Up @@ -596,7 +678,6 @@ public async Task SignInAsync_ShouldCallGetTokenAsync_WithCaeEnabledAsync()
authContext, CancellationToken.None, capturingCredential);

// Assert: GetTokenAsync must have been called and provided a context.
Assert.NotNull(capturedContext);
Assert.NotNull(capturedContext.Scopes);

// GetTokenAsync must receive isCaeEnabled: true so that MSAL caches
Expand Down Expand Up @@ -658,10 +739,8 @@ await AuthenticationHelpers.SignInAsync(
new Uri("https://graph.microsoft.com/v1.0/me"));

// the cached token silently during API calls.
Assert.NotNull(signInContext);
Assert.True(signInContext.IsCaeEnabled,
"SignInAsync must pass isCaeEnabled: true to GetTokenAsync.");
Assert.NotNull(providerContext);
Assert.True(providerContext.IsCaeEnabled,
"AzureIdentityAccessTokenProvider must forward isCaeEnabled: true.");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ public async Task GetGraphHttpClientShouldReturnNewHttpClientOnSignOutThenSignIn
}

[Fact]
public async void GetGraphHttpClientShouldBeThreadSafeAsync()
public async Task GetGraphHttpClientShouldBeThreadSafeAsync()
{
GraphSession.Initialize(() => new GraphSession());
GraphSession.Instance.RequestContext = new RequestContext();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System.Collections;
using System.Management.Automation;
using System.Net.Http;

using System.Threading.Tasks;
using Microsoft.Graph.PowerShell.Authentication.Cmdlets;
using Microsoft.Graph.PowerShell.Authentication.Helpers;

Expand Down Expand Up @@ -105,7 +105,7 @@ public void ShouldSerializePSCustomObjectAsJsonObject()
}

[Fact]
public void SetRequestContentShouldSerializeDictionaryWithPSObjectWrappedValues()
public async Task SetRequestContentShouldSerializeDictionaryWithPSObjectWrappedValues()
{
var cmdlet = new InvokeMgGraphRequest();
using (var request = new HttpRequestMessage(HttpMethod.Post,
Expand Down Expand Up @@ -138,7 +138,7 @@ public void SetRequestContentShouldSerializeDictionaryWithPSObjectWrappedValues(
var contentLength = cmdlet.SetRequestContent(request, body);

Assert.True(contentLength > 0);
var json = request.Content.ReadAsStringAsync().GetAwaiter().GetResult();
var json = await request.Content.ReadAsStringAsync();
var parsedBody = JObject.Parse(json);
Assert.Equal("recipient@example.com",
parsedBody.SelectToken("message.toRecipients[0].emailAddress.address").Value<string>());
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net8.0;net472</TargetFrameworks>
<IsPackable>false</IsPackable>
Expand All @@ -13,7 +13,7 @@
tests exercise the real PowerShell runtime. -->
<PackageReference Include="Microsoft.PowerShell.SDK" Version="7.4.17" PrivateAssets="all" Condition="'$(TargetFramework)' == 'net8.0'" />
<PackageReference Include="Moq" Version="4.21.0" />
<PackageReference Include="System.Security.Cryptography.Xml" Version="8.0.4" />
<PackageReference Include="System.Security.Cryptography.Xml" Version="8.0.5" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<PrivateAssets>all</PrivateAssets>
Expand Down
31 changes: 3 additions & 28 deletions src/Authentication/Authentication/Cmdlets/GetMgAccessToken.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------

using Azure.Core;
using Microsoft.Graph.PowerShell.Authentication.Common;
using Microsoft.Graph.PowerShell.Authentication.Core.Extensions;
using Microsoft.Graph.PowerShell.Authentication.Core.Utilities;
using Microsoft.Graph.PowerShell.Authentication.Helpers;
using Microsoft.Graph.PowerShell.Authentication.Interfaces;
Expand All @@ -29,11 +27,6 @@ namespace Microsoft.Graph.PowerShell.Authentication.Cmdlets
[OutputType(typeof(MgAccessTokenInfo))]
public class GetMgAccessToken : PSCmdlet
{
/// <summary>
/// The time window before expiry at which a cached token is considered stale and must be refreshed.
/// </summary>
private static readonly TimeSpan RefreshWindow = TimeSpan.FromMinutes(5);

[Parameter(Mandatory = false, Position = 0, HelpMessage = Constants.HelpMessages.Scopes)]
public string[] Scopes { get; set; }

Expand Down Expand Up @@ -94,38 +87,20 @@ private async Task ProcessRecordAsync()
if (requestedScopes == null || !requestedScopes.Any())
throw new PSInvalidOperationException(Core.ErrorConstants.Message.MissingAuthContext);

string cacheKey = string.Join(" ", requestedScopes.OrderBy(scope => scope, StringComparer.OrdinalIgnoreCase));

AccessToken accessToken;
bool hasCachedToken = GraphSession.Instance.AccessTokenCache.TryGetValue(cacheKey, out accessToken);
bool requiresRefresh = ForceRefresh.IsPresent
|| !hasCachedToken
|| accessToken.ExpiresOn - DateTimeOffset.UtcNow < RefreshWindow;

if (requiresRefresh)
{
var tokenCredential = await AuthenticationHelpers.GetTokenCredentialAsync(authContext).ConfigureAwait(false);
accessToken = await tokenCredential.GetTokenAsync(new TokenRequestContext(requestedScopes), default).ConfigureAwait(false);
GraphSession.Instance.AccessTokenCache[cacheKey] = accessToken;
}

var secureToken = new SecureString();
foreach (char character in accessToken.Token)
secureToken.AppendChar(character);
secureToken.MakeReadOnly();
var accessToken = await AuthenticationHelpers.GetAccessTokenAsync(authContext, requestedScopes, ForceRefresh.IsPresent).ConfigureAwait(false);

if (AsObject.IsPresent)
{
WriteObject(new MgAccessTokenInfo
{
Token = secureToken,
Token = accessToken.Token,
ExpiresOn = accessToken.ExpiresOn,
Scopes = requestedScopes
});
}
else
{
WriteObject(secureToken);
WriteObject(accessToken.Token);
}
}
}
Expand Down