Skip to content
This repository was archived by the owner on Dec 13, 2018. It is now read-only.

Commit 30d350d

Browse files
committed
Move logger to base handler and moar var
1 parent 6072e3b commit 30d350d

27 files changed

+169
-227
lines changed

src/Microsoft.AspNet.Authentication.Cookies/CookieAuthenticationHandler.cs

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -22,18 +22,11 @@ internal class CookieAuthenticationHandler : AuthenticationHandler<CookieAuthent
2222
private const string HeaderValueMinusOne = "-1";
2323
private const string SessionIdClaim = "Microsoft.AspNet.Authentication.Cookies-SessionId";
2424

25-
private readonly ILogger _logger;
26-
2725
private bool _shouldRenew;
2826
private DateTimeOffset _renewIssuedUtc;
2927
private DateTimeOffset _renewExpiresUtc;
3028
private string _sessionKey;
3129

32-
public CookieAuthenticationHandler([NotNull] ILogger logger)
33-
{
34-
_logger = logger;
35-
}
36-
3730
protected override AuthenticationTicket AuthenticateCore()
3831
{
3932
return AuthenticateCoreAsync().GetAwaiter().GetResult();
@@ -54,7 +47,7 @@ protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
5447

5548
if (ticket == null)
5649
{
57-
_logger.LogWarning(@"Unprotect ticket failed");
50+
Logger.LogWarning(@"Unprotect ticket failed");
5851
return null;
5952
}
6053

@@ -63,14 +56,14 @@ protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
6356
Claim claim = ticket.Principal.Claims.FirstOrDefault(c => c.Type.Equals(SessionIdClaim));
6457
if (claim == null)
6558
{
66-
_logger.LogWarning(@"SessionId missing");
59+
Logger.LogWarning(@"SessionId missing");
6760
return null;
6861
}
6962
_sessionKey = claim.Value;
7063
ticket = await Options.SessionStore.RetrieveAsync(_sessionKey);
7164
if (ticket == null)
7265
{
73-
_logger.LogWarning(@"Identity missing in session store");
66+
Logger.LogWarning(@"Identity missing in session store");
7467
return null;
7568
}
7669
}

src/Microsoft.AspNet.Authentication.Cookies/CookieAuthenticationMiddleware.cs

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,14 @@ namespace Microsoft.AspNet.Authentication.Cookies
1515
{
1616
public class CookieAuthenticationMiddleware : AuthenticationMiddleware<CookieAuthenticationOptions>
1717
{
18-
private readonly ILogger _logger;
19-
2018
public CookieAuthenticationMiddleware(
2119
[NotNull] RequestDelegate next,
2220
[NotNull] IDataProtectionProvider dataProtectionProvider,
2321
[NotNull] ILoggerFactory loggerFactory,
2422
[NotNull] IUrlEncoder urlEncoder,
2523
[NotNull] IOptions<CookieAuthenticationOptions> options,
2624
ConfigureOptions<CookieAuthenticationOptions> configureOptions)
27-
: base(next, options, configureOptions)
25+
: base(next, options, loggerFactory, configureOptions)
2826
{
2927
if (Options.Notifications == null)
3028
{
@@ -36,21 +34,19 @@ public CookieAuthenticationMiddleware(
3634
}
3735
if (Options.TicketDataFormat == null)
3836
{
39-
IDataProtector dataProtector = dataProtectionProvider.CreateProtector(
37+
var dataProtector = dataProtectionProvider.CreateProtector(
4038
typeof(CookieAuthenticationMiddleware).FullName, Options.AuthenticationScheme, "v2");
4139
Options.TicketDataFormat = new TicketDataFormat(dataProtector);
4240
}
4341
if (Options.CookieManager == null)
4442
{
4543
Options.CookieManager = new ChunkingCookieManager(urlEncoder);
4644
}
47-
48-
_logger = loggerFactory.CreateLogger(typeof(CookieAuthenticationMiddleware).FullName);
4945
}
5046

5147
protected override AuthenticationHandler<CookieAuthenticationOptions> CreateHandler()
5248
{
53-
return new CookieAuthenticationHandler(_logger);
49+
return new CookieAuthenticationHandler();
5450
}
5551
}
5652
}

src/Microsoft.AspNet.Authentication.Facebook/FacebookAuthenticationHandler.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@ namespace Microsoft.AspNet.Authentication.Facebook
2121
{
2222
internal class FacebookAuthenticationHandler : OAuthAuthenticationHandler<FacebookAuthenticationOptions, IFacebookAuthenticationNotifications>
2323
{
24-
public FacebookAuthenticationHandler(HttpClient httpClient, ILogger logger)
25-
: base(httpClient, logger)
24+
public FacebookAuthenticationHandler(HttpClient httpClient)
25+
: base(httpClient)
2626
{
2727
}
2828

@@ -39,9 +39,9 @@ protected override async Task<TokenResponse> ExchangeCodeAsync(string code, stri
3939

4040
var tokenResponse = await Backchannel.GetAsync(Options.TokenEndpoint + queryBuilder.ToString(), Context.RequestAborted);
4141
tokenResponse.EnsureSuccessStatusCode();
42-
string oauthTokenResponse = await tokenResponse.Content.ReadAsStringAsync();
42+
var oauthTokenResponse = await tokenResponse.Content.ReadAsStringAsync();
4343

44-
IFormCollection form = new FormCollection(FormReader.ReadForm(oauthTokenResponse));
44+
var form = new FormCollection(FormReader.ReadForm(oauthTokenResponse));
4545
var response = new JObject();
4646
foreach (string key in form.Keys)
4747
{
@@ -53,16 +53,16 @@ protected override async Task<TokenResponse> ExchangeCodeAsync(string code, stri
5353

5454
protected override async Task<AuthenticationTicket> GetUserInformationAsync(AuthenticationProperties properties, TokenResponse tokens)
5555
{
56-
string graphAddress = Options.UserInformationEndpoint + "?access_token=" + Uri.EscapeDataString(tokens.AccessToken);
56+
var graphAddress = Options.UserInformationEndpoint + "?access_token=" + Uri.EscapeDataString(tokens.AccessToken);
5757
if (Options.SendAppSecretProof)
5858
{
5959
graphAddress += "&appsecret_proof=" + GenerateAppSecretProof(tokens.AccessToken);
6060
}
6161

6262
var graphResponse = await Backchannel.GetAsync(graphAddress, Context.RequestAborted);
6363
graphResponse.EnsureSuccessStatusCode();
64-
string text = await graphResponse.Content.ReadAsStringAsync();
65-
JObject user = JObject.Parse(text);
64+
var text = await graphResponse.Content.ReadAsStringAsync();
65+
var user = JObject.Parse(text);
6666

6767
var context = new FacebookAuthenticatedContext(Context, Options, user, tokens);
6868
var identity = new ClaimsIdentity(
@@ -107,8 +107,8 @@ private string GenerateAppSecretProof(string accessToken)
107107
{
108108
using (HMACSHA256 algorithm = new HMACSHA256(Encoding.ASCII.GetBytes(Options.AppSecret)))
109109
{
110-
byte[] hash = algorithm.ComputeHash(Encoding.ASCII.GetBytes(accessToken));
111-
StringBuilder builder = new StringBuilder();
110+
var hash = algorithm.ComputeHash(Encoding.ASCII.GetBytes(accessToken));
111+
var builder = new StringBuilder();
112112
for (int i = 0; i < hash.Length; i++)
113113
{
114114
builder.Append(hash[i].ToString("x2", CultureInfo.InvariantCulture));

src/Microsoft.AspNet.Authentication.Facebook/FacebookAuthenticationMiddleware.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ public FacebookAuthenticationMiddleware(
5454
/// <returns>An <see cref="AuthenticationHandler"/> configured with the <see cref="FacebookAuthenticationOptions"/> supplied to the constructor.</returns>
5555
protected override AuthenticationHandler<FacebookAuthenticationOptions> CreateHandler()
5656
{
57-
return new FacebookAuthenticationHandler(Backchannel, Logger);
57+
return new FacebookAuthenticationHandler(Backchannel);
5858
}
5959
}
60-
}
60+
}

src/Microsoft.AspNet.Authentication.Facebook/FacebookServiceCollectionExtensions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,4 @@ public static IServiceCollection ConfigureFacebookAuthentication([NotNull] this
3333
return services.Configure<FacebookAuthenticationOptions>(config, optionsName);
3434
}
3535
}
36-
}
36+
}

src/Microsoft.AspNet.Authentication.Google/GoogleAuthenticationHandler.cs

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,27 +10,26 @@
1010
using Microsoft.AspNet.Http.Authentication;
1111
using Microsoft.AspNet.Authentication.OAuth;
1212
using Microsoft.AspNet.WebUtilities;
13-
using Microsoft.Framework.Logging;
1413
using Newtonsoft.Json.Linq;
1514

1615
namespace Microsoft.AspNet.Authentication.Google
1716
{
1817
internal class GoogleAuthenticationHandler : OAuthAuthenticationHandler<GoogleAuthenticationOptions, IGoogleAuthenticationNotifications>
1918
{
20-
public GoogleAuthenticationHandler(HttpClient httpClient, ILogger logger)
21-
: base(httpClient, logger)
19+
public GoogleAuthenticationHandler(HttpClient httpClient)
20+
: base(httpClient)
2221
{
2322
}
2423

2524
protected override async Task<AuthenticationTicket> GetUserInformationAsync(AuthenticationProperties properties, TokenResponse tokens)
2625
{
2726
// Get the Google user
28-
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, Options.UserInformationEndpoint);
27+
var request = new HttpRequestMessage(HttpMethod.Get, Options.UserInformationEndpoint);
2928
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken);
30-
HttpResponseMessage graphResponse = await Backchannel.SendAsync(request, Context.RequestAborted);
29+
var graphResponse = await Backchannel.SendAsync(request, Context.RequestAborted);
3130
graphResponse.EnsureSuccessStatusCode();
3231
var text = await graphResponse.Content.ReadAsStringAsync();
33-
JObject user = JObject.Parse(text);
32+
var user = JObject.Parse(text);
3433

3534
var context = new GoogleAuthenticatedContext(Context, Options, user, tokens);
3635
var identity = new ClaimsIdentity(
@@ -79,7 +78,7 @@ protected override async Task<AuthenticationTicket> GetUserInformationAsync(Auth
7978
// TODO: Abstract this properties override pattern into the base class?
8079
protected override string BuildChallengeUrl(AuthenticationProperties properties, string redirectUri)
8180
{
82-
string scope = FormatScope();
81+
var scope = FormatScope();
8382

8483
var queryStrings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
8584
queryStrings.Add("response_type", "code");
@@ -92,10 +91,10 @@ protected override string BuildChallengeUrl(AuthenticationProperties properties,
9291
AddQueryString(queryStrings, properties, "approval_prompt");
9392
AddQueryString(queryStrings, properties, "login_hint");
9493

95-
string state = Options.StateDataFormat.Protect(properties);
94+
var state = Options.StateDataFormat.Protect(properties);
9695
queryStrings.Add("state", state);
9796

98-
string authorizationEndpoint = QueryHelpers.AddQueryString(Options.AuthorizationEndpoint, queryStrings);
97+
var authorizationEndpoint = QueryHelpers.AddQueryString(Options.AuthorizationEndpoint, queryStrings);
9998
return authorizationEndpoint;
10099
}
101100

src/Microsoft.AspNet.Authentication.Google/GoogleAuthenticationMiddleware.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ public GoogleAuthenticationMiddleware(
5656
/// <returns>An <see cref="AuthenticationHandler"/> configured with the <see cref="GoogleAuthenticationOptions"/> supplied to the constructor.</returns>
5757
protected override AuthenticationHandler<GoogleAuthenticationOptions> CreateHandler()
5858
{
59-
return new GoogleAuthenticationHandler(Backchannel, Logger);
59+
return new GoogleAuthenticationHandler(Backchannel);
6060
}
6161
}
62-
}
62+
}

src/Microsoft.AspNet.Authentication.Google/GoogleAuthenticationOptions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,4 @@ public GoogleAuthenticationOptions()
3333
/// </summary>
3434
public string AccessType { get; set; }
3535
}
36-
}
36+
}

src/Microsoft.AspNet.Authentication.MicrosoftAccount/MicrosoftAccountAuthenticationHandler.cs

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,31 @@
11
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
22
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
33

4-
using System;
5-
using System.Collections.Generic;
64
using System.Net.Http;
75
using System.Net.Http.Headers;
86
using System.Security.Claims;
97
using System.Threading.Tasks;
10-
using Microsoft.AspNet.Http;
11-
using Microsoft.AspNet.Http.Authentication;
128
using Microsoft.AspNet.Authentication.OAuth;
13-
using Microsoft.Framework.Logging;
9+
using Microsoft.AspNet.Http.Authentication;
1410
using Newtonsoft.Json.Linq;
1511

1612
namespace Microsoft.AspNet.Authentication.MicrosoftAccount
1713
{
1814
internal class MicrosoftAccountAuthenticationHandler : OAuthAuthenticationHandler<MicrosoftAccountAuthenticationOptions, IMicrosoftAccountAuthenticationNotifications>
1915
{
20-
public MicrosoftAccountAuthenticationHandler(HttpClient httpClient, ILogger logger)
21-
: base(httpClient, logger)
16+
public MicrosoftAccountAuthenticationHandler(HttpClient httpClient)
17+
: base(httpClient)
2218
{
2319
}
2420

2521
protected override async Task<AuthenticationTicket> GetUserInformationAsync(AuthenticationProperties properties, TokenResponse tokens)
2622
{
27-
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, Options.UserInformationEndpoint);
23+
var request = new HttpRequestMessage(HttpMethod.Get, Options.UserInformationEndpoint);
2824
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken);
29-
HttpResponseMessage graphResponse = await Backchannel.SendAsync(request, Context.RequestAborted);
25+
var graphResponse = await Backchannel.SendAsync(request, Context.RequestAborted);
3026
graphResponse.EnsureSuccessStatusCode();
31-
string accountString = await graphResponse.Content.ReadAsStringAsync();
32-
JObject accountInformation = JObject.Parse(accountString);
27+
var accountString = await graphResponse.Content.ReadAsStringAsync();
28+
var accountInformation = JObject.Parse(accountString);
3329

3430
var context = new MicrosoftAccountAuthenticatedContext(Context, Options, accountInformation, tokens);
3531
context.Properties = properties;

src/Microsoft.AspNet.Authentication.MicrosoftAccount/MicrosoftAccountAuthenticationMiddleware.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
22
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
33

4-
using System;
54
using Microsoft.AspNet.Authentication.OAuth;
65
using Microsoft.AspNet.Builder;
76
using Microsoft.AspNet.DataProtection;
@@ -50,7 +49,7 @@ public MicrosoftAccountAuthenticationMiddleware(
5049
/// <returns>An <see cref="AuthenticationHandler"/> configured with the <see cref="MicrosoftAccountAuthenticationOptions"/> supplied to the constructor.</returns>
5150
protected override AuthenticationHandler<MicrosoftAccountAuthenticationOptions> CreateHandler()
5251
{
53-
return new MicrosoftAccountAuthenticationHandler(Backchannel, Logger);
52+
return new MicrosoftAccountAuthenticationHandler(Backchannel);
5453
}
5554
}
5655
}

src/Microsoft.AspNet.Authentication.OAuth/OAuthAuthenticationHandler.cs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,13 @@ public class OAuthAuthenticationHandler<TOptions, TNotifications> : Authenticati
1919
where TOptions : OAuthAuthenticationOptions<TNotifications>
2020
where TNotifications : IOAuthAuthenticationNotifications
2121
{
22-
public OAuthAuthenticationHandler(HttpClient backchannel, ILogger logger)
22+
public OAuthAuthenticationHandler(HttpClient backchannel)
2323
{
2424
Backchannel = backchannel;
25-
Logger = logger;
2625
}
2726

2827
protected HttpClient Backchannel { get; private set; }
2928

30-
protected ILogger Logger { get; private set; }
31-
3229
public override async Task<bool> InvokeAsync()
3330
{
3431
if (Options.CallbackPath.HasValue && Options.CallbackPath == Request.Path)
@@ -107,7 +104,7 @@ protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
107104
}
108105

109106
// OAuth2 10.12 CSRF
110-
if (!ValidateCorrelationId(properties, Logger))
107+
if (!ValidateCorrelationId(properties))
111108
{
112109
return new AuthenticationTicket(properties, Options.AuthenticationScheme);
113110
}

src/Microsoft.AspNet.Authentication.OAuth/OAuthAuthenticationMiddleware.cs

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ public OAuthAuthenticationMiddleware(
3636
[NotNull] IOptions<ExternalAuthenticationOptions> externalOptions,
3737
[NotNull] IOptions<TOptions> options,
3838
ConfigureOptions<TOptions> configureOptions = null)
39-
: base(next, options, configureOptions)
39+
: base(next, options, loggerFactory, configureOptions)
4040
{
4141
// todo: review error handling
4242
if (string.IsNullOrWhiteSpace(Options.AuthenticationScheme))
@@ -64,11 +64,9 @@ public OAuthAuthenticationMiddleware(
6464
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, "TokenEndpoint"));
6565
}
6666

67-
Logger = loggerFactory.CreateLogger(this.GetType().FullName);
68-
6967
if (Options.StateDataFormat == null)
7068
{
71-
IDataProtector dataProtector = dataProtectionProvider.CreateProtector(
69+
var dataProtector = dataProtectionProvider.CreateProtector(
7270
this.GetType().FullName, Options.AuthenticationScheme, "v1");
7371
Options.StateDataFormat = new PropertiesDataFormat(dataProtector);
7472
}
@@ -90,15 +88,13 @@ public OAuthAuthenticationMiddleware(
9088

9189
protected HttpClient Backchannel { get; private set; }
9290

93-
protected ILogger Logger { get; private set; }
94-
9591
/// <summary>
9692
/// Provides the <see cref="AuthenticationHandler"/> object for processing authentication-related requests.
9793
/// </summary>
9894
/// <returns>An <see cref="AuthenticationHandler"/> configured with the <see cref="OAuthAuthenticationOptions"/> supplied to the constructor.</returns>
9995
protected override AuthenticationHandler<TOptions> CreateHandler()
10096
{
101-
return new OAuthAuthenticationHandler<TOptions, TNotifications>(Backchannel, Logger);
97+
return new OAuthAuthenticationHandler<TOptions, TNotifications>(Backchannel);
10298
}
10399

104100
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Managed by caller")]

src/Microsoft.AspNet.Authentication.OAuthBearer/OAuthBearerAuthenticationHandler.cs

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,8 @@ namespace Microsoft.AspNet.Authentication.OAuthBearer
1717
{
1818
public class OAuthBearerAuthenticationHandler : AuthenticationHandler<OAuthBearerAuthenticationOptions>
1919
{
20-
private readonly ILogger _logger;
2120
private OpenIdConnectConfiguration _configuration;
2221

23-
public OAuthBearerAuthenticationHandler(ILogger logger)
24-
{
25-
_logger = logger;
26-
}
27-
2822
protected override AuthenticationTicket AuthenticateCore()
2923
{
3024
return AuthenticateCoreAsync().GetAwaiter().GetResult();
@@ -63,7 +57,7 @@ protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
6357

6458
if (string.IsNullOrEmpty(token))
6559
{
66-
string authorization = Request.Headers.Get("Authorization");
60+
var authorization = Request.Headers.Get("Authorization");
6761

6862
// If no authorization header found, nothing to process further
6963
if (string.IsNullOrEmpty(authorization))
@@ -155,7 +149,7 @@ protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
155149
}
156150
catch (Exception ex)
157151
{
158-
_logger.LogError("Exception occurred while processing message", ex);
152+
Logger.LogError("Exception occurred while processing message", ex);
159153

160154
// Refresh the configuration for exceptions that may be caused by key rollovers. The user can also request a refresh in the notification.
161155
if (Options.RefreshOnIssuerKeyNotFound && ex.GetType().Equals(typeof(SecurityTokenSignatureKeyNotFoundException)))

0 commit comments

Comments
 (0)