-
Notifications
You must be signed in to change notification settings - Fork 328
/
ClientCredentialRequest.cs
235 lines (201 loc) · 11 KB
/
ClientCredentialRequest.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Identity.Client.ApiConfig.Parameters;
using Microsoft.Identity.Client.Cache.Items;
using Microsoft.Identity.Client.Core;
using Microsoft.Identity.Client.Extensibility;
using Microsoft.Identity.Client.Instance;
using Microsoft.Identity.Client.OAuth2;
using Microsoft.Identity.Client.Utils;
namespace Microsoft.Identity.Client.Internal.Requests
{
internal class ClientCredentialRequest : RequestBase
{
private readonly AcquireTokenForClientParameters _clientParameters;
private static readonly SemaphoreSlim s_semaphoreSlim = new SemaphoreSlim(1, 1);
public ClientCredentialRequest(
IServiceBundle serviceBundle,
AuthenticationRequestParameters authenticationRequestParameters,
AcquireTokenForClientParameters clientParameters)
: base(serviceBundle, authenticationRequestParameters, clientParameters)
{
_clientParameters = clientParameters;
}
protected override async Task<AuthenticationResult> ExecuteAsync(CancellationToken cancellationToken)
{
if (AuthenticationRequestParameters.Scope == null || AuthenticationRequestParameters.Scope.Count == 0)
{
throw new MsalClientException(
MsalError.ScopesRequired,
MsalErrorMessage.ScopesRequired);
}
ILoggerAdapter logger = AuthenticationRequestParameters.RequestContext.Logger;
if (AuthenticationRequestParameters.Authority is AadAuthority aadAuthority &&
aadAuthority.IsCommonOrOrganizationsTenant())
{
logger.Error(MsalErrorMessage.ClientCredentialWrongAuthority);
}
AuthenticationResult authResult = null;
//skip checking cache for force refresh or when claims are present
if (_clientParameters.ForceRefresh || !string.IsNullOrEmpty(AuthenticationRequestParameters.Claims))
{
AuthenticationRequestParameters.RequestContext.ApiEvent.CacheInfo = CacheRefreshReason.ForceRefreshOrClaims;
logger.Info("[ClientCredentialRequest] Skipped looking for an Access Token in the cache because ForceRefresh was set.");
authResult = await GetAccessTokenAsync(cancellationToken, logger).ConfigureAwait(false);
return authResult;
}
//check cache for AT
MsalAccessTokenCacheItem cachedAccessTokenItem = await GetCachedAccessTokenAsync().ConfigureAwait(false);
if (cachedAccessTokenItem != null)
{
//return the token in the cache and check if it needs to be proactively refreshed
authResult = CreateAuthenticationResultFromCache(cachedAccessTokenItem);
try
{
var proactivelyRefresh = SilentRequestHelper.NeedsRefresh(cachedAccessTokenItem);
// may fire a request to get a new token in the background when AT needs to be refreshed
if (proactivelyRefresh)
{
AuthenticationRequestParameters.RequestContext.ApiEvent.CacheInfo = CacheRefreshReason.ProactivelyRefreshed;
SilentRequestHelper.ProcessFetchInBackground(
cachedAccessTokenItem,
() => GetAccessTokenAsync(cancellationToken, logger), logger);
}
}
catch (MsalServiceException e)
{
return await HandleTokenRefreshErrorAsync(e, cachedAccessTokenItem).ConfigureAwait(false);
}
}
else
{
// No AT in the cache
if (AuthenticationRequestParameters.RequestContext.ApiEvent.CacheInfo != CacheRefreshReason.Expired)
{
AuthenticationRequestParameters.RequestContext.ApiEvent.CacheInfo = CacheRefreshReason.NoCachedAccessToken;
}
authResult = await GetAccessTokenAsync(cancellationToken, logger).ConfigureAwait(false);
}
return authResult;
}
private async Task<AuthenticationResult> GetAccessTokenAsync(
CancellationToken cancellationToken,
ILoggerAdapter logger)
{
await ResolveAuthorityAsync().ConfigureAwait(false);
//calls sent to AAD
if (ServiceBundle.Config.AppTokenProvider == null)
{
MsalTokenResponse msalTokenResponse = await SendTokenRequestAsync(GetBodyParameters(), cancellationToken).ConfigureAwait(false);
return await CacheTokenResponseAndCreateAuthenticationResultAsync(msalTokenResponse).ConfigureAwait(false);
}
//calls sent to app token provider
AuthenticationResult authResult;
MsalAccessTokenCacheItem cachedAccessTokenItem = null;
try
{
//allow only one call to the provider
logger.Verbose(() => "[ClientCredentialRequest] Entering token acquire for client credential request semaphore.");
await s_semaphoreSlim.WaitAsync(cancellationToken).ConfigureAwait(false);
logger.Verbose(() => "[ClientCredentialRequest] Entered token acquire for client credential request semaphore.");
// Bypass cache and send request to token endpoint, when
// 1. Force refresh is requested, or
// 2. Claims are passed, or
// 3. If the AT needs to be refreshed pro-actively
if (_clientParameters.ForceRefresh ||
AuthenticationRequestParameters.RequestContext.ApiEvent.CacheInfo == CacheRefreshReason.ProactivelyRefreshed ||
!string.IsNullOrEmpty(AuthenticationRequestParameters.Claims))
{
authResult = await SendTokenRequestToAppTokenProviderAsync(logger, cancellationToken).ConfigureAwait(false);
}
else
{
cachedAccessTokenItem = await GetCachedAccessTokenAsync().ConfigureAwait(false);
if (cachedAccessTokenItem == null)
{
authResult = await SendTokenRequestToAppTokenProviderAsync(logger, cancellationToken).ConfigureAwait(false);
}
else
{
logger.Verbose(() => "[ClientCredentialRequest] Getting Access token from cache ...");
authResult = CreateAuthenticationResultFromCache(cachedAccessTokenItem);
}
}
return authResult;
}
finally
{
s_semaphoreSlim.Release();
logger.Verbose(() => "[ClientCredentialRequest] Released token acquire for client credential request semaphore.");
}
}
private async Task<AuthenticationResult> SendTokenRequestToAppTokenProviderAsync(ILoggerAdapter logger,
CancellationToken cancellationToken)
{
logger.Info("[ClientCredentialRequest] Sending Token response to client credential request endpoint ...");
AppTokenProviderParameters appTokenProviderParameters = new AppTokenProviderParameters
{
Scopes = GetOverriddenScopes(AuthenticationRequestParameters.Scope),
CorrelationId = AuthenticationRequestParameters.RequestContext.CorrelationId.ToString(),
Claims = AuthenticationRequestParameters.Claims,
TenantId = AuthenticationRequestParameters.Authority.TenantId,
CancellationToken = cancellationToken,
};
AppTokenProviderResult externalToken = await ServiceBundle.Config.AppTokenProvider(appTokenProviderParameters).ConfigureAwait(false);
var tokenResponse = MsalTokenResponse.CreateFromAppProviderResponse(externalToken);
tokenResponse.Scope = appTokenProviderParameters.Scopes.AsSingleString();
tokenResponse.CorrelationId = appTokenProviderParameters.CorrelationId;
AuthenticationResult authResult = await CacheTokenResponseAndCreateAuthenticationResultAsync(tokenResponse)
.ConfigureAwait(false);
return authResult;
}
private async Task<MsalAccessTokenCacheItem> GetCachedAccessTokenAsync()
{
MsalAccessTokenCacheItem cachedAccessTokenItem = await CacheManager.FindAccessTokenAsync().ConfigureAwait(false);
if (cachedAccessTokenItem != null && !_clientParameters.ForceRefresh)
{
AuthenticationRequestParameters.RequestContext.ApiEvent.IsAccessTokenCacheHit = true;
Metrics.IncrementTotalAccessTokensFromCache();
return cachedAccessTokenItem;
}
return null;
}
private AuthenticationResult CreateAuthenticationResultFromCache(MsalAccessTokenCacheItem cachedAccessTokenItem)
{
AuthenticationResult authResult = new AuthenticationResult(
cachedAccessTokenItem,
null,
AuthenticationRequestParameters.AuthenticationScheme,
AuthenticationRequestParameters.RequestContext.CorrelationId,
TokenSource.Cache,
AuthenticationRequestParameters.RequestContext.ApiEvent,
account: null,
spaAuthCode: null,
additionalResponseParameters: null);
return authResult;
}
protected override SortedSet<string> GetOverriddenScopes(ISet<string> inputScopes)
{
// Client credentials should not add the reserved scopes
// "openid", "profile" and "offline_access"
// because AT is on behalf of an app (no profile, no IDToken, no RT)
return new SortedSet<string>(inputScopes);
}
private Dictionary<string, string> GetBodyParameters()
{
var dict = new Dictionary<string, string>
{
[OAuth2Parameter.GrantType] = OAuth2GrantType.ClientCredentials,
[OAuth2Parameter.Scope] = AuthenticationRequestParameters.Scope.AsSingleString()
};
return dict;
}
protected override KeyValuePair<string, string>? GetCcsHeader(IDictionary<string, string> additionalBodyParameters)
{
return null;
}
}
}