Skip to content

Commit be2638d

Browse files
committed
Cleanup code for StyleCop
1 parent 669a9c4 commit be2638d

8 files changed

Lines changed: 111 additions & 113 deletions

StyleCop.ruleset

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
<Rule Id="SA1623" Action="None" /> <!-- The property's documentation summary text should begin with : 'Gets or sets' -->
1818
<Rule Id="SA1650" Action="None" /> <!-- The documentation header contains invalidly spelled words. -->
1919
<Rule Id="SA1602" Action="None" /> <!-- Enumeration items should be documented. -->
20+
<Rule Id="SA1009" Action="None" /> <!-- Closing parenthesis should not be preceded by a space. -->
21+
<Rule Id="SA1111" Action="None" /> <!-- Closing Parenthesis Must Be On Line Of Last Parameter. -->
2022
<Rule Id="SA1128" Action="None" /> <!-- Put constructor initializers on their own line. -->
2123
</Rules>
2224
</RuleSet>

src/KK.AspNetCore.EasyAuthAuthentication/AuthTokenHeaderNames.cs

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,36 +2,34 @@ namespace KK.AspNetCore.EasyAuthAuthentication
22
{
33
/// <summary>
44
/// This class contains all header names that are possible to make an authentication.
5-
/// The source of the list can find here: https://docs.microsoft.com/en-us/azure/app-service/app-service-authentication-how-to#retrieve-tokens-in-app-code
5+
/// The source of the list can find here: https://docs.microsoft.com/en-us/azure/app-service/app-service-authentication-how-to#retrieve-tokens-in-app-code .
66
/// </summary>
7-
public static class AuthTokenHeaderNames
7+
internal static class AuthTokenHeaderNames
88
{
9-
#region AzureAd
9+
// AzureAd
1010
public const string AADIdToken = "X-MS-TOKEN-AAD-ID-TOKEN";
1111
public const string AADAccessToken = "X-MS-TOKEN-AAD-ACCESS-TOKEN";
1212
public const string AADExpiresOn = "X-MS-TOKEN-AAD-EXPIRES-ON";
1313
public const string AADRefreshToken = "X-MS-TOKEN-AAD-REFRESH-TOKEN";
14-
#endregion
15-
#region Facebook
14+
15+
// Facebook
1616
public const string FacebookAccessToken = "X-MS-TOKEN-FACEBOOK-ACCESS-TOKEN";
1717
public const string FacebookExpiresOn = "X-MS-TOKEN-FACEBOOK-EXPIRES-ON";
18-
#endregion
19-
#region Google
18+
19+
// Google
2020
public const string GoogleIdToken = "X-MS-TOKEN-GOOGLE-ID-TOKEN";
2121
public const string GoogleAccessToken = "X-MS-TOKEN-GOOGLE-ACCESS-TOKEN";
2222
public const string GoogleExpiresOn = "X-MS-TOKEN-GOOGLE-EXPIRES-ON";
2323
public const string GoogleRefreshToken = "X-MS-TOKEN-GOOGLE-REFRESH-TOKEN";
2424

25-
#endregion
26-
#region Microsoft Account
25+
// Microsoft Account
2726
public const string MicrosoftAccessToken = "X-MS-TOKEN-MICROSOFTACCOUNT-ACCESS-TOKEN";
2827
public const string MicrosoftExpiresOn = "X-MS-TOKEN-MICROSOFTACCOUNT-EXPIRES-ON";
2928
public const string MicrosoftAuthenticationToken = "X-MS-TOKEN-MICROSOFTACCOUNT-AUTHENTICATION-TOKEN";
3029
public const string MicrosoftRefreshToken = "X-MS-TOKEN-MICROSOFTACCOUNT-REFRESH-TOKEN";
31-
#endregion
32-
#region Twitter
30+
31+
// Twitter
3332
public const string TwitterAccessToken = "X-MS-TOKEN-TWITTER-ACCESS-TOKEN";
3433
public const string TwitterAccessTokenSecret = "X-MS-TOKEN-TWITTER-ACCESS-TOKEN-SECRET";
35-
#endregion
3634
}
3735
}

src/KK.AspNetCore.EasyAuthAuthentication/AuthenticationTicketBuilder.cs

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,35 @@
1-
using System.Collections.Generic;
2-
using System.Linq;
3-
using System.Security.Claims;
4-
using System.Security.Principal;
5-
using Microsoft.AspNetCore.Authentication;
6-
using Newtonsoft.Json.Linq;
7-
81
namespace KK.AspNetCore.EasyAuthAuthentication
92
{
10-
public static class AuthenticationTicketBuilder
3+
using System.Collections.Generic;
4+
using System.Linq;
5+
using System.Security.Claims;
6+
using Microsoft.AspNetCore.Authentication;
7+
using Newtonsoft.Json.Linq;
8+
9+
internal static class AuthenticationTicketBuilder
1110
{
1211
/// <summary>
13-
/// Build a `AuthenticationTicket` from the given payload, the principal name and the provider name
12+
/// Build a `AuthenticationTicket` from the given payload, the principal name and the provider name.
1413
/// </summary>
15-
/// <param name="claimsPayload">A array of JObjects that have a `type` and a `val` property</param>
14+
/// <param name="claimsPayload">A array of JObjects that have a `type` and a `val` property.</param>
1615
/// <param name="providerName">The provider name of the current auth provider.</param>
17-
/// <returns>A `AuthenticationTicket`</returns>
16+
/// <returns>A `AuthenticationTicket`.</returns>
1817
public static AuthenticationTicket Build(IEnumerable<JObject> claimsPayload, string providerName)
1918
{
19+
// setting ClaimsIdentity.AuthenticationType to value that Azure AD non-EasyAuth setups use
2020
var identity = new ClaimsIdentity(
21-
createClaims(claimsPayload),
22-
// setting ClaimsIdentity.AuthenticationType to value that Azure AD non-EasyAuth setups use
21+
CreateClaims(claimsPayload),
2322
AuthenticationTypesNames.Federation
2423
);
2524

26-
addScopeClaim(identity);
27-
addProviderNameClaim(identity, providerName);
25+
AddScopeClaim(identity);
26+
AddProviderNameClaim(identity, providerName);
2827
var genericPrincipal = new ClaimsPrincipal(identity);
2928

3029
return new AuthenticationTicket(genericPrincipal, EasyAuthAuthenticationDefaults.AuthenticationScheme);
3130
}
3231

33-
private static IEnumerable<Claim> createClaims(IEnumerable<JObject> claimsAsJson)
32+
private static IEnumerable<Claim> CreateClaims(IEnumerable<JObject> claimsAsJson)
3433
{
3534
foreach (var claim in claimsAsJson)
3635
{
@@ -42,12 +41,14 @@ private static IEnumerable<Claim> createClaims(IEnumerable<JObject> claimsAsJson
4241
{
4342
yield return new Claim(ClaimTypes.Authentication, item);
4443
}
44+
4545
break;
4646
case "roles":
4747
foreach (var item in claim["val"].ToString().Split(','))
4848
{
4949
yield return new Claim(ClaimTypes.Role, item);
5050
}
51+
5152
break;
5253
default:
5354
yield return new Claim(claimType, claim["val"].ToString());
@@ -56,7 +57,7 @@ private static IEnumerable<Claim> createClaims(IEnumerable<JObject> claimsAsJson
5657
}
5758
}
5859

59-
private static void addScopeClaim(ClaimsIdentity identity)
60+
private static void AddScopeClaim(ClaimsIdentity identity)
6061
{
6162
if (!identity.Claims.Any(claim => claim.Type == "scp"))
6263
{
@@ -66,7 +67,7 @@ private static void addScopeClaim(ClaimsIdentity identity)
6667
}
6768
}
6869

69-
private static void addProviderNameClaim(ClaimsIdentity identity, string providerName)
70+
private static void AddProviderNameClaim(ClaimsIdentity identity, string providerName)
7071
{
7172
if (!identity.Claims.Any(claim => claim.Type == "provider_name"))
7273
{

src/KK.AspNetCore.EasyAuthAuthentication/AuthenticationTypesNames.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ namespace KK.AspNetCore.EasyAuthAuthentication
22
{
33
/// <summary>
44
/// This class contains all Authentication type names.
5-
/// Source of this is: https://docs.microsoft.com/en-us/dotnet/api/system.security.claims.authenticationtypes?view=netframework-4.7.2
5+
/// Source of this is: https://docs.microsoft.com/en-us/dotnet/api/system.security.claims.authenticationtypes?view=netframework-4.7.2 .
66
/// </summary>
7-
public class AuthenticationTypesNames
7+
internal class AuthenticationTypesNames
88
{
99
public const string Basic = "AuthenticationTypes.Basic";
1010
public const string Federation = "AuthenticationTypes.Federation";

src/KK.AspNetCore.EasyAuthAuthentication/EasyAuthAuthenticationHandler.cs

Lines changed: 20 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,36 @@
11
namespace KK.AspNetCore.EasyAuthAuthentication
22
{
33
using System;
4-
using System.Collections.Generic;
5-
using System.IdentityModel.Tokens.Jwt;
6-
using System.Linq; // required by Children<JObject>.FirstOrDefault requires using System.Linq;
7-
using System.Net;
8-
using System.Net.Http;
94
using System.Security.Claims;
10-
using System.Security.Principal;
11-
using System.Text;
125
using System.Text.Encodings.Web;
136
using System.Threading.Tasks;
147
using KK.AspNetCore.EasyAuthAuthentication.Services;
158
using Microsoft.AspNetCore.Authentication;
169
using Microsoft.AspNetCore.Http;
1710
using Microsoft.Extensions.Logging;
1811
using Microsoft.Extensions.Options;
19-
using Newtonsoft.Json;
20-
using Newtonsoft.Json.Linq;
2112

2213
/// <summary>
2314
/// Enables the handler in an Easy Auth context.
2415
/// </summary>
2516
public class EasyAuthAuthenticationHandler : AuthenticationHandler<EasyAuthAuthenticationOptions>
2617
{
18+
private static readonly Func<ClaimsPrincipal, bool> IsContextUserNotAuthenticated =
19+
user => user == null || user.Identity == null || user.Identity.IsAuthenticated == false;
20+
21+
private static readonly Func<IHeaderDictionary, string, bool> IsHeaderSet =
22+
(headers, headerName) => !string.IsNullOrEmpty(headers[headerName].ToString());
23+
24+
private static readonly Func<IHeaderDictionary, ClaimsPrincipal, HttpRequest, string, bool> CanUseEasyAuthJson =
25+
(headers, user, request, authEndpoint) =>
26+
IsContextUserNotAuthenticated(user)
27+
&& !IsHeaderSet(headers, AuthTokenHeaderNames.AADIdToken)
28+
&& request.Path != "/" + $"{authEndpoint}";
29+
30+
private readonly Func<IHeaderDictionary, ClaimsPrincipal, bool> canUseHeaderAuth =
31+
(headers, user) => IsContextUserNotAuthenticated(user) &&
32+
IsHeaderSet(headers, AuthTokenHeaderNames.AADIdToken);
33+
2734
/// <summary>
2835
/// Initializes a new instance of the <see cref="EasyAuthAuthenticationHandler"/> class.
2936
/// </summary>
@@ -39,42 +46,30 @@ public EasyAuthAuthenticationHandler(
3946
{
4047
}
4148

42-
private static Func<ClaimsPrincipal, bool> isContextUserNotAuthenticated =
43-
user => (user == null || user.Identity == null || user.Identity.IsAuthenticated == false);
44-
private static Func<IHeaderDictionary, string, bool> isHeaderSet =
45-
(headers, headerName) => !string.IsNullOrEmpty(headers[headerName].ToString());
46-
private Func<IHeaderDictionary, ClaimsPrincipal, bool> canUseHeaderAuth =
47-
(headers, user) => isContextUserNotAuthenticated(user) &&
48-
isHeaderSet(headers, AuthTokenHeaderNames.AADIdToken);
49-
private static Func<IHeaderDictionary, ClaimsPrincipal, HttpRequest, string, bool> canUseEasyAuthJson =
50-
(headers, user, request, authEndpoint) =>
51-
isContextUserNotAuthenticated(user)
52-
&& !isHeaderSet(headers, AuthTokenHeaderNames.AADIdToken)
53-
&& request.Path != "/" + $"{authEndpoint}";
54-
5549
/// <inheritdoc/>
5650
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
5751
{
5852
this.Logger.LogInformation("starting authentication handler for app service authentication");
5953

60-
if (canUseHeaderAuth(this.Context.Request.Headers, this.Context.User))
54+
if (this.canUseHeaderAuth(this.Context.Request.Headers, this.Context.User))
6155
{
6256
return EasyAuthWithHeaderService.AuthUser(this.Logger, this.Context);
6357
}
64-
else if (canUseEasyAuthJson(this.Context.Request.Headers, this.Context.User, this.Context.Request, this.Options.AuthEndpoint))
58+
else if (CanUseEasyAuthJson(this.Context.Request.Headers, this.Context.User, this.Context.Request, this.Options.AuthEndpoint))
6559
{
6660
return await EasyAuthWithAuthMeService.AuthUser(this.Logger, this.Context, this.Options.AuthEndpoint);
6761
}
6862
else
6963
{
70-
if (isContextUserNotAuthenticated(this.Context.User))
64+
if (IsContextUserNotAuthenticated(this.Context.User))
7165
{
7266
this.Logger.LogInformation("The identity isn't set by easy auth.");
7367
}
7468
else
7569
{
7670
this.Logger.LogInformation("identity already set, skipping middleware");
7771
}
72+
7873
return AuthenticateResult.NoResult();
7974
}
8075
}

src/KK.AspNetCore.EasyAuthAuthentication/Schemas.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
namespace KK.AspNetCore.EasyAuthAuthentication
22
{
3-
public class Schemas
3+
internal class Schemas
44
{
55
public const string AuthMethod = "http://schemas.microsoft.com/claims/authnmethodsreferences";
66
}

src/KK.AspNetCore.EasyAuthAuthentication/Services/EasyAuthWithAuthMeService.cs

Lines changed: 38 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,18 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using System.Linq;
4-
using System.Net;
5-
using System.Net.Http;
6-
using System.Security.Claims;
7-
using System.Security.Principal;
8-
using System.Threading.Tasks;
9-
using Microsoft.AspNetCore.Authentication;
10-
using Microsoft.AspNetCore.Http;
11-
using Microsoft.Extensions.Logging;
12-
using Newtonsoft.Json;
13-
using Newtonsoft.Json.Linq;
14-
151
namespace KK.AspNetCore.EasyAuthAuthentication.Services
162
{
17-
public class EasyAuthWithAuthMeService
3+
using System;
4+
using System.Net;
5+
using System.Net.Http;
6+
using System.Security.Principal;
7+
using System.Threading.Tasks;
8+
using Microsoft.AspNetCore.Authentication;
9+
using Microsoft.AspNetCore.Http;
10+
using Microsoft.Extensions.Logging;
11+
using Newtonsoft.Json;
12+
using Newtonsoft.Json.Linq;
13+
14+
internal class EasyAuthWithAuthMeService
1815
{
19-
private string Host { get; }
20-
private IRequestCookieCollection Cookies { get; }
21-
private IHeaderDictionary Headers { get; }
22-
private string AuthEndPoint { get; }
23-
private ILogger Logger { get; }
24-
private string HttpSchema { get; }
2516
private EasyAuthWithAuthMeService(
2617
ILogger logger,
2718
string httpSchema,
@@ -32,20 +23,32 @@ private EasyAuthWithAuthMeService(
3223
{
3324
this.HttpSchema = httpSchema;
3425
this.Host = host;
35-
Cookies = cookies;
36-
Headers = headers;
37-
AuthEndPoint = authEndPoint;
26+
this.Cookies = cookies;
27+
this.Headers = headers;
28+
this.AuthEndPoint = authEndPoint;
3829
this.Logger = logger;
3930
}
4031

32+
private string Host { get; }
33+
34+
private IRequestCookieCollection Cookies { get; }
35+
36+
private IHeaderDictionary Headers { get; }
37+
38+
private string AuthEndPoint { get; }
39+
40+
private ILogger Logger { get; }
41+
42+
private string HttpSchema { get; }
43+
4144
/// <summary>
4245
/// Use this method to authenticate a user with easy auth.
4346
/// This will set the `context.User` of your HttpContext.
4447
/// </summary>
45-
/// <param name="logger"></param>
48+
/// <param name="logger">An instance of <see cref="ILogger"/>.</param>
4649
/// <param name="context">The http context with the missing user claim.</param>
47-
/// <param name="authEndpoint">The auth endpoint where we find the easy auth json</param>
48-
/// <returns></returns>
50+
/// <param name="authEndpoint">The auth endpoint where we find the easy auth json.</param>
51+
/// <returns>An <see cref="AuthenticateResult" />.</returns>
4952
public static async Task<AuthenticateResult> AuthUser(ILogger logger, HttpContext context, string authEndpoint)
5053
{
5154
try
@@ -146,8 +149,14 @@ private HttpRequestMessage CreateAuthRequest(ref CookieContainer cookieContainer
146149

147150
// fetch value from endpoint
148151
var authMeEndpoint = string.Empty;
149-
if (this.AuthEndPoint.StartsWith("http")) authMeEndpoint = this.AuthEndPoint; // enable pulling from places like storage account private blob container
150-
else authMeEndpoint = $"{uriString}/{this.AuthEndPoint}"; // localhost relative path, e.g. wwwroot/.auth/me.json
152+
if (this.AuthEndPoint.StartsWith("http"))
153+
{
154+
authMeEndpoint = this.AuthEndPoint; // enable pulling from places like storage account private blob container
155+
}
156+
else
157+
{
158+
authMeEndpoint = $"{uriString}/{this.AuthEndPoint}"; // localhost relative path, e.g. wwwroot/.auth/me.json
159+
}
151160

152161
var request = new HttpRequestMessage(HttpMethod.Get, authMeEndpoint);
153162
foreach (var header in this.Headers)

0 commit comments

Comments
 (0)