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

Cache tokens for service principal #20193

Merged
merged 1 commit into from
Nov 22, 2022
Merged
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
1 change: 1 addition & 0 deletions src/Accounts/Accounts/ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
-->

## Upcoming Release
* Enabled caching tokens when logging in with a service principal. This could reduce network traffic and improve performance.

## Version 2.10.3
* Updated `Get-AzSubscription` to retrieve subscription by Id rather than listed all the subscriptions from server if subscription Id is provided. [#19115]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public async Task ServicePrincipalSecretAuthenticationTest()
//Setup
var mockAzureCredentialFactory = new Mock<AzureCredentialFactory>();
mockAzureCredentialFactory.Setup(f => f.CreateClientSecretCredential(
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<SecureString>(), It.IsAny<ClientCertificateCredentialOptions>())).Returns(() => new TokenCredentialMock());
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<SecureString>(), It.IsAny<ClientSecretCredentialOptions>())).Returns(() => new TokenCredentialMock());

AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => mockAzureCredentialFactory.Object, true);
InMemoryTokenCacheProvider cacheProvider = new InMemoryTokenCacheProvider();
Expand Down Expand Up @@ -101,7 +101,7 @@ public async Task ServicePrincipalSecretAuthenticationTest()
var token = await authenticator.Authenticate(parameter);

//Verify
mockAzureCredentialFactory.Verify(f => f.CreateClientSecretCredential(TestTenantId, accountId, securePassword, It.IsAny<ClientCertificateCredentialOptions>()), Times.Once());
mockAzureCredentialFactory.Verify(f => f.CreateClientSecretCredential(TestTenantId, accountId, securePassword, It.IsAny<ClientSecretCredentialOptions>()), Times.Once());
Assert.Equal(fakeToken, token.AccessToken);
Assert.Equal(TestTenantId, token.TenantId);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public virtual TokenCredential CreateManagedIdentityCredential(string clientId)
return new ManagedIdentityCredential(clientId);
}

public virtual TokenCredential CreateClientSecretCredential(string tenantId, string clientId, SecureString secret, ClientCertificateCredentialOptions options)
public virtual TokenCredential CreateClientSecretCredential(string tenantId, string clientId, SecureString secret, ClientSecretCredentialOptions options)
{
return new ClientSecretCredential(tenantId, clientId, secret.ConvertToString(), options);
}
Expand Down
16 changes: 12 additions & 4 deletions src/Accounts/Authenticators/ServicePrincipalAuthenticator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public class ServicePrincipalAuthenticator : DelegatingAuthenticator
{
private const string AuthenticationFailedMessage = "No certificate thumbprint or secret provided for the given service principal '{0}'.";

//MSAL doesn't cache Service Principal into msal.cache
// MSAL doesn't cache the secret of Service Principal, but it caches access tokens
public override Task<IAccessToken> Authenticate(AuthenticationParameters parameters, CancellationToken cancellationToken)
{
var spParameters = parameters as ServicePrincipalParameters;
Expand All @@ -43,10 +43,12 @@ public override Task<IAccessToken> Authenticate(AuthenticationParameters paramet
var authority = spParameters.Environment.ActiveDirectoryAuthority;

var requestContext = new TokenRequestContext(scopes);
var tokenCachePersistenceOptions = spParameters.TokenCacheProvider.GetTokenCachePersistenceOptions();
AzureSession.Instance.TryGetComponent(nameof(AzureCredentialFactory), out AzureCredentialFactory azureCredentialFactory);

var options = new ClientCertificateCredentialOptions()
{
TokenCachePersistenceOptions = tokenCachePersistenceOptions, // allows MSAL to cache access tokens
AuthorityHost = new Uri(authority),
SendCertificateChain = spParameters.SendCertificateChain ?? default(bool)
};
Expand All @@ -63,10 +65,15 @@ public override Task<IAccessToken> Authenticate(AuthenticationParameters paramet
else if (spParameters.Secret != null)
{
//Service principal with secret
tokenCredential = azureCredentialFactory.CreateClientSecretCredential(tenantId, spParameters.ApplicationId, spParameters.Secret, options);
parametersLog = $"- ApplicationId:'{spParameters.ApplicationId}', TenantId:'{tenantId}', Scopes:'{string.Join(",", scopes)}', AuthorityHost:'{options.AuthorityHost}'";
var csOptions = new ClientSecretCredentialOptions()
{
TokenCachePersistenceOptions = tokenCachePersistenceOptions, // allows MSAL to cache access tokens
AuthorityHost = new Uri(authority)
};
tokenCredential = azureCredentialFactory.CreateClientSecretCredential(tenantId, spParameters.ApplicationId, spParameters.Secret, csOptions);
parametersLog = $"- ApplicationId:'{spParameters.ApplicationId}', TenantId:'{tenantId}', Scopes:'{string.Join(",", scopes)}', AuthorityHost:'{csOptions.AuthorityHost}'";
}
else if(!string.IsNullOrEmpty(spParameters.CertificatePath))
else if (!string.IsNullOrEmpty(spParameters.CertificatePath))
{
if (spParameters.CertificateSecret != null)
{
Expand All @@ -86,6 +93,7 @@ public override Task<IAccessToken> Authenticate(AuthenticationParameters paramet
{
throw new MsalException(MsalError.AuthenticationFailed, string.Format(AuthenticationFailedMessage, clientId));
}

return MsalAccessToken.GetAccessTokenAsync(
nameof(ServicePrincipalAuthenticator),
parametersLog,
Expand Down