Skip to content

Commit a24aed7

Browse files
Use newer method overloads in auth handlers (#30715)
* Use new CancellationToken overloads Use new overloads of methods added in .NET 5.0 that accept a CancellationToken. * Use StringBuilder.Append(char) Use StringBuilder.Append(char) instead of StringBuilder.Append(string) when there is only a single character. * Use WriteAsync(Span<byte>, CancellationToken) Use WriteAsync() overload that accepts a span and a CancellationToken, instead of an array and indexes to write all bytes. * Make methods static Make methods that do not access instance data static. * Remove unused code Remove an unused method and an unused parameter. * Use compound assignment Use the compound assignment operator. * Fix test names Fix copy-paste from Facebook tests. * Remove CancellationToken Remove the CancellationToken from the WriteAsync() call to address review feedback.
1 parent e61245a commit a24aed7

File tree

10 files changed

+33
-63
lines changed

10 files changed

+33
-63
lines changed

src/Security/Authentication/Core/src/AuthenticationHandler.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ protected virtual async Task InitializeEventsAsync()
153153
{
154154
Events = Context.RequestServices.GetRequiredService(Options.EventsType);
155155
}
156-
Events = Events ?? await CreateEventsAsync();
156+
Events ??= await CreateEventsAsync();
157157
}
158158

159159
/// <summary>

src/Security/Authentication/Facebook/src/FacebookHandler.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ protected override async Task<AuthenticationTicket> CreateTicketAsync(ClaimsIden
4949
throw new HttpRequestException($"An error occurred when retrieving Facebook user information ({response.StatusCode}). Please check if the authentication information is correct and the corresponding Facebook Graph API is enabled.");
5050
}
5151

52-
using (var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync()))
52+
using (var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync(Context.RequestAborted)))
5353
{
5454
var context = new OAuthCreatingTicketContext(new ClaimsPrincipal(identity), properties, Context, Scheme, Options, Backchannel, tokens, payload.RootElement);
5555
context.RunClaimActions();

src/Security/Authentication/Google/src/GoogleHandler.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ protected override async Task<AuthenticationTicket> CreateTicketAsync(
4646
throw new HttpRequestException($"An error occurred when retrieving Google user information ({response.StatusCode}). Please check if the authentication information is correct.");
4747
}
4848

49-
using (var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync()))
49+
using (var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync(Context.RequestAborted)))
5050
{
5151
var context = new OAuthCreatingTicketContext(new ClaimsPrincipal(identity), properties, Context, Scheme, Options, Backchannel, tokens, payload.RootElement);
5252
context.RunClaimActions();
@@ -80,7 +80,7 @@ protected override string BuildChallengeUrl(AuthenticationProperties properties,
8080
return authorizationEndpoint;
8181
}
8282

83-
private void AddQueryString<T>(
83+
private static void AddQueryString<T>(
8484
IDictionary<string, string> queryStrings,
8585
AuthenticationProperties properties,
8686
string name,
@@ -107,7 +107,7 @@ private void AddQueryString<T>(
107107
}
108108
}
109109

110-
private void AddQueryString(
110+
private static void AddQueryString(
111111
IDictionary<string, string> queryStrings,
112112
AuthenticationProperties properties,
113113
string name,

src/Security/Authentication/JwtBearer/src/JwtBearerHandler.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -243,13 +243,13 @@ protected override async Task HandleChallengeAsync(AuthenticationProperties prop
243243
{
244244
builder.Append(" error=\"");
245245
builder.Append(eventContext.Error);
246-
builder.Append("\"");
246+
builder.Append('\"');
247247
}
248248
if (!string.IsNullOrEmpty(eventContext.ErrorDescription))
249249
{
250250
if (!string.IsNullOrEmpty(eventContext.Error))
251251
{
252-
builder.Append(",");
252+
builder.Append(',');
253253
}
254254

255255
builder.Append(" error_description=\"");
@@ -261,7 +261,7 @@ protected override async Task HandleChallengeAsync(AuthenticationProperties prop
261261
if (!string.IsNullOrEmpty(eventContext.Error) ||
262262
!string.IsNullOrEmpty(eventContext.ErrorDescription))
263263
{
264-
builder.Append(",");
264+
builder.Append(',');
265265
}
266266

267267
builder.Append(" error_uri=\"");

src/Security/Authentication/MicrosoftAccount/src/MicrosoftAccountHandler.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ protected override async Task<AuthenticationTicket> CreateTicketAsync(ClaimsIden
4343
throw new HttpRequestException($"An error occurred when retrieving Microsoft user information ({response.StatusCode}). Please check if the authentication information is correct and the corresponding Microsoft Account API is enabled.");
4444
}
4545

46-
using (var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync()))
46+
using (var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync(Context.RequestAborted)))
4747
{
4848
var context = new OAuthCreatingTicketContext(new ClaimsPrincipal(identity), properties, Context, Scheme, Options, Backchannel, tokens, payload.RootElement);
4949
context.RunClaimActions();
@@ -92,7 +92,7 @@ protected override string BuildChallengeUrl(AuthenticationProperties properties,
9292
return QueryHelpers.AddQueryString(Options.AuthorizationEndpoint, queryStrings!);
9393
}
9494

95-
private void AddQueryString<T>(
95+
private static void AddQueryString<T>(
9696
Dictionary<string, string> queryStrings,
9797
AuthenticationProperties properties,
9898
string name,
@@ -119,7 +119,7 @@ private void AddQueryString<T>(
119119
}
120120
}
121121

122-
private void AddQueryString(
122+
private static void AddQueryString(
123123
Dictionary<string, string> queryStrings,
124124
AuthenticationProperties properties,
125125
string name,

src/Security/Authentication/OAuth/src/OAuthHandler.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ protected virtual async Task<OAuthTokenResponse> ExchangeCodeAsync(OAuthCodeExch
217217
var response = await Backchannel.SendAsync(requestMessage, Context.RequestAborted);
218218
if (response.IsSuccessStatusCode)
219219
{
220-
var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
220+
var payload = JsonDocument.Parse(await response.Content.ReadAsStringAsync(Context.RequestAborted));
221221
return OAuthTokenResponse.Success(payload);
222222
}
223223
else

src/Security/Authentication/OpenIdConnect/src/OpenIdConnectHandler.cs

Lines changed: 9 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ protected virtual async Task<bool> HandleRemoteSignOutAsync()
105105
&& Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)
106106
&& Request.Body.CanRead)
107107
{
108-
var form = await Request.ReadFormAsync();
108+
var form = await Request.ReadFormAsync(Context.RequestAborted);
109109
message = new OpenIdConnectMessage(form.Select(pair => new KeyValuePair<string, string[]>(pair.Key, pair.Value)));
110110
}
111111

@@ -195,7 +195,7 @@ public async virtual Task SignOutAsync(AuthenticationProperties properties)
195195
return;
196196
}
197197

198-
properties = properties ?? new AuthenticationProperties();
198+
properties ??= new AuthenticationProperties();
199199

200200
Logger.EnteringOpenIdAuthenticationHandlerHandleSignOutAsync(GetType().FullName);
201201

@@ -276,7 +276,7 @@ public async virtual Task SignOutAsync(AuthenticationProperties properties)
276276
Response.Headers[HeaderNames.Pragma] = "no-cache";
277277
Response.Headers[HeaderNames.Expires] = HeaderValueEpocDate;
278278

279-
await Response.Body.WriteAsync(buffer, 0, buffer.Length);
279+
await Response.Body.WriteAsync(buffer);
280280
}
281281
else
282282
{
@@ -479,7 +479,7 @@ private async Task HandleChallengeAsyncInternal(AuthenticationProperties propert
479479
Response.Headers[HeaderNames.Pragma] = "no-cache";
480480
Response.Headers[HeaderNames.Expires] = HeaderValueEpocDate;
481481

482-
await Response.Body.WriteAsync(buffer, 0, buffer.Length);
482+
await Response.Body.WriteAsync(buffer);
483483
return;
484484
}
485485

@@ -521,7 +521,7 @@ protected override async Task<HandleRequestResult> HandleRemoteAuthenticateAsync
521521
&& Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)
522522
&& Request.Body.CanRead)
523523
{
524-
var form = await Request.ReadFormAsync();
524+
var form = await Request.ReadFormAsync(Context.RequestAborted);
525525
authorizationResponse = new OpenIdConnectMessage(form.Select(pair => new KeyValuePair<string, string[]>(pair.Key, pair.Value)));
526526
}
527527

@@ -823,7 +823,7 @@ protected virtual async Task<OpenIdConnectMessage> RedeemAuthorizationCodeAsync(
823823
var requestMessage = new HttpRequestMessage(HttpMethod.Post, tokenEndpointRequest.TokenEndpoint ?? _configuration.TokenEndpoint);
824824
requestMessage.Content = new FormUrlEncodedContent(tokenEndpointRequest.Parameters);
825825
requestMessage.Version = Backchannel.DefaultRequestVersion;
826-
var responseMessage = await Backchannel.SendAsync(requestMessage);
826+
var responseMessage = await Backchannel.SendAsync(requestMessage, Context.RequestAborted);
827827

828828
var contentMediaType = responseMessage.Content.Headers.ContentType?.MediaType;
829829
if (string.IsNullOrEmpty(contentMediaType))
@@ -842,7 +842,7 @@ protected virtual async Task<OpenIdConnectMessage> RedeemAuthorizationCodeAsync(
842842
OpenIdConnectMessage message;
843843
try
844844
{
845-
var responseContent = await responseMessage.Content.ReadAsStringAsync();
845+
var responseContent = await responseMessage.Content.ReadAsStringAsync(Context.RequestAborted);
846846
message = new OpenIdConnectMessage(responseContent);
847847
}
848848
catch (Exception ex)
@@ -886,9 +886,9 @@ protected virtual async Task<HandleRequestResult> GetUserInformationAsync(
886886
var requestMessage = new HttpRequestMessage(HttpMethod.Get, userInfoEndpoint);
887887
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", message.AccessToken);
888888
requestMessage.Version = Backchannel.DefaultRequestVersion;
889-
var responseMessage = await Backchannel.SendAsync(requestMessage);
889+
var responseMessage = await Backchannel.SendAsync(requestMessage, Context.RequestAborted);
890890
responseMessage.EnsureSuccessStatusCode();
891-
var userInfoResponse = await responseMessage.Content.ReadAsStringAsync();
891+
var userInfoResponse = await responseMessage.Content.ReadAsStringAsync(Context.RequestAborted);
892892

893893
JsonDocument user;
894894
var contentType = responseMessage.Content.Headers.ContentType;
@@ -1037,36 +1037,6 @@ private string ReadNonceCookie(string nonce)
10371037
return null;
10381038
}
10391039

1040-
private AuthenticationProperties GetPropertiesFromState(string state)
1041-
{
1042-
// assume a well formed query string: <a=b&>OpenIdConnectAuthenticationDefaults.AuthenticationPropertiesKey=kasjd;fljasldkjflksdj<&c=d>
1043-
var startIndex = 0;
1044-
if (string.IsNullOrEmpty(state) || (startIndex = state.IndexOf(OpenIdConnectDefaults.AuthenticationPropertiesKey, StringComparison.Ordinal)) == -1)
1045-
{
1046-
return null;
1047-
}
1048-
1049-
var authenticationIndex = startIndex + OpenIdConnectDefaults.AuthenticationPropertiesKey.Length;
1050-
if (authenticationIndex == -1 || authenticationIndex == state.Length || state[authenticationIndex] != '=')
1051-
{
1052-
return null;
1053-
}
1054-
1055-
// scan rest of string looking for '&'
1056-
authenticationIndex++;
1057-
var endIndex = state.Substring(authenticationIndex, state.Length - authenticationIndex).IndexOf("&", StringComparison.Ordinal);
1058-
1059-
// -1 => no other parameters are after the AuthenticationPropertiesKey
1060-
if (endIndex == -1)
1061-
{
1062-
return Options.StateDataFormat.Unprotect(Uri.UnescapeDataString(state.Substring(authenticationIndex).Replace('+', ' ')));
1063-
}
1064-
else
1065-
{
1066-
return Options.StateDataFormat.Unprotect(Uri.UnescapeDataString(state.Substring(authenticationIndex, endIndex).Replace('+', ' ')));
1067-
}
1068-
}
1069-
10701040
private async Task<MessageReceivedContext> RunMessageReceivedEventAsync(OpenIdConnectMessage message, AuthenticationProperties properties)
10711041
{
10721042
Logger.MessageReceived(message.BuildRedirectUrl());

src/Security/Authentication/Twitter/src/TwitterHandler.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ protected override async Task<HandleRequestResult> HandleRemoteAuthenticateAsync
117117
JsonDocument user;
118118
if (Options.RetrieveUserDetails)
119119
{
120-
user = await RetrieveUserDetailsAsync(accessToken, identity);
120+
user = await RetrieveUserDetailsAsync(accessToken);
121121
}
122122
else
123123
{
@@ -223,9 +223,9 @@ private async Task<HttpResponseMessage> ExecuteRequestAsync(string url, HttpMeth
223223

224224
var canonicalizedRequestBuilder = new StringBuilder();
225225
canonicalizedRequestBuilder.Append(httpMethod.Method);
226-
canonicalizedRequestBuilder.Append("&");
226+
canonicalizedRequestBuilder.Append('&');
227227
canonicalizedRequestBuilder.Append(Uri.EscapeDataString(url));
228-
canonicalizedRequestBuilder.Append("&");
228+
canonicalizedRequestBuilder.Append('&');
229229
canonicalizedRequestBuilder.Append(Uri.EscapeDataString(parameterString));
230230

231231
var signature = ComputeSignature(Options.ConsumerSecret, accessToken?.TokenSecret, canonicalizedRequestBuilder.ToString());
@@ -271,7 +271,7 @@ private async Task<RequestToken> ObtainRequestTokenAsync(string callBackUri, Aut
271271

272272
var response = await ExecuteRequestAsync(TwitterDefaults.RequestTokenEndpoint, HttpMethod.Post, extraOAuthPairs: new Dictionary<string, string>() { { "oauth_callback", callBackUri } });
273273
await EnsureTwitterRequestSuccess(response);
274-
var responseText = await response.Content.ReadAsStringAsync();
274+
var responseText = await response.Content.ReadAsStringAsync(Context.RequestAborted);
275275

276276
var responseParameters = new FormCollection(new FormReader(responseText).ReadForm());
277277
if (!string.Equals(responseParameters["oauth_callback_confirmed"], "true", StringComparison.Ordinal))
@@ -297,7 +297,7 @@ private async Task<AccessToken> ObtainAccessTokenAsync(RequestToken token, strin
297297
await EnsureTwitterRequestSuccess(response); // throw
298298
}
299299

300-
var responseText = await response.Content.ReadAsStringAsync();
300+
var responseText = await response.Content.ReadAsStringAsync(Context.RequestAborted);
301301
var responseParameters = new FormCollection(new FormReader(responseText).ReadForm());
302302

303303
return new AccessToken
@@ -310,7 +310,7 @@ private async Task<AccessToken> ObtainAccessTokenAsync(RequestToken token, strin
310310
}
311311

312312
// https://dev.twitter.com/rest/reference/get/account/verify_credentials
313-
private async Task<JsonDocument> RetrieveUserDetailsAsync(AccessToken accessToken, ClaimsIdentity identity)
313+
private async Task<JsonDocument> RetrieveUserDetailsAsync(AccessToken accessToken)
314314
{
315315
Logger.RetrieveUserDetails();
316316

@@ -321,7 +321,7 @@ private async Task<JsonDocument> RetrieveUserDetailsAsync(AccessToken accessToke
321321
Logger.LogError("Email request failed with a status code of " + response.StatusCode);
322322
await EnsureTwitterRequestSuccess(response); // throw
323323
}
324-
var responseText = await response.Content.ReadAsStringAsync();
324+
var responseText = await response.Content.ReadAsStringAsync(Context.RequestAborted);
325325

326326
var result = JsonDocument.Parse(responseText);
327327

@@ -334,7 +334,7 @@ private string GenerateTimeStamp()
334334
return Convert.ToInt64(secondsSinceUnixEpocStart.TotalSeconds).ToString(CultureInfo.InvariantCulture);
335335
}
336336

337-
private string ComputeSignature(string consumerSecret, string tokenSecret, string signatureData)
337+
private static string ComputeSignature(string consumerSecret, string tokenSecret, string signatureData)
338338
{
339339
using (var algorithm = new HMACSHA1())
340340
{
@@ -363,7 +363,7 @@ private async Task EnsureTwitterRequestSuccess(HttpResponseMessage response)
363363
try
364364
{
365365
// Failure, attempt to parse Twitters error message
366-
var errorContentStream = await response.Content.ReadAsStreamAsync();
366+
var errorContentStream = await response.Content.ReadAsStreamAsync(Context.RequestAborted);
367367
errorResponse = await JsonSerializer.DeserializeAsync<TwitterErrorResponse>(errorContentStream, ErrorSerializerOptions);
368368
}
369369
catch

src/Security/Authentication/WsFederation/src/WsFederationHandler.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ protected override async Task<HandleRequestResult> HandleRemoteAuthenticateAsync
148148
&& Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)
149149
&& Request.Body.CanRead)
150150
{
151-
var form = await Request.ReadFormAsync();
151+
var form = await Request.ReadFormAsync(Context.RequestAborted);
152152

153153
wsFederationMessage = new WsFederationMessage(form.Select(pair => new KeyValuePair<string, string[]>(pair.Key, pair.Value)));
154154
}

src/Security/Authentication/test/GoogleTests.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -941,7 +941,7 @@ public async Task AuthenticateGoogleWhenAlreadySignedInSucceeds()
941941
}
942942

943943
[Fact]
944-
public async Task AuthenticateFacebookWhenAlreadySignedWithGoogleReturnsNull()
944+
public async Task AuthenticateGoogleWhenAlreadySignedWithGoogleReturnsNull()
945945
{
946946
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider(NullLoggerFactory.Instance).CreateProtector("GoogleTest"));
947947
using var host = await CreateHost(o =>
@@ -978,7 +978,7 @@ public async Task AuthenticateFacebookWhenAlreadySignedWithGoogleReturnsNull()
978978
}
979979

980980
[Fact]
981-
public async Task ChallengeFacebookWhenAlreadySignedWithGoogleSucceeds()
981+
public async Task ChallengeGoogleWhenAlreadySignedWithGoogleSucceeds()
982982
{
983983
var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider(NullLoggerFactory.Instance).CreateProtector("GoogleTest"));
984984
using var host = await CreateHost(o =>

0 commit comments

Comments
 (0)