Skip to content

Commit 42d34a6

Browse files
authored
Add StyleCop (#6)
- Add StyleCop to the Nuget project - Add minimalö rule set - Update code to match the rules
1 parent 39e9de8 commit 42d34a6

9 files changed

Lines changed: 161 additions & 43 deletions

KK.AspNetCore.EasyAuthAuthentication.sln

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,20 @@ VisualStudioVersion = 15.0.26124.0
55
MinimumVisualStudioVersion = 15.0.26124.0
66
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{5D09A785-6509-4FA8-8394-DB761ECFC353}"
77
EndProject
8-
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KK.AspNetCore.EasyAuthAuthentication", "src\KK.AspNetCore.EasyAuthAuthentication\KK.AspNetCore.EasyAuthAuthentication.csproj", "{70FFE5C2-8F7C-49E0-9C31-DB713BA66B8B}"
8+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "KK.AspNetCore.EasyAuthAuthentication", "src\KK.AspNetCore.EasyAuthAuthentication\KK.AspNetCore.EasyAuthAuthentication.csproj", "{70FFE5C2-8F7C-49E0-9C31-DB713BA66B8B}"
99
EndProject
10-
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KK.AspNetCore.EasyAuthAuthentication.Sample", "src\KK.AspNetCore.EasyAuthAuthentication.Sample\KK.AspNetCore.EasyAuthAuthentication.Sample.csproj", "{B156B6B8-9427-4A72-8986-9A17F4FBC0EA}"
10+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "KK.AspNetCore.EasyAuthAuthentication.Sample", "src\KK.AspNetCore.EasyAuthAuthentication.Sample\KK.AspNetCore.EasyAuthAuthentication.Sample.csproj", "{B156B6B8-9427-4A72-8986-9A17F4FBC0EA}"
11+
EndProject
12+
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{215B89CF-8087-48EF-ACDE-995AEE744BF2}"
13+
ProjectSection(SolutionItems) = preProject
14+
.editorconfig = .editorconfig
15+
.gitignore = .gitignore
16+
global.json = global.json
17+
LICENSE = LICENSE
18+
README.md = README.md
19+
StyleCop.json = StyleCop.json
20+
StyleCop.ruleset = StyleCop.ruleset
21+
EndProjectSection
1122
EndProject
1223
Global
1324
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -18,9 +29,6 @@ Global
1829
Release|x64 = Release|x64
1930
Release|x86 = Release|x86
2031
EndGlobalSection
21-
GlobalSection(SolutionProperties) = preSolution
22-
HideSolutionNode = FALSE
23-
EndGlobalSection
2432
GlobalSection(ProjectConfigurationPlatforms) = postSolution
2533
{70FFE5C2-8F7C-49E0-9C31-DB713BA66B8B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
2634
{70FFE5C2-8F7C-49E0-9C31-DB713BA66B8B}.Debug|Any CPU.Build.0 = Debug|Any CPU
@@ -47,8 +55,14 @@ Global
4755
{B156B6B8-9427-4A72-8986-9A17F4FBC0EA}.Release|x86.ActiveCfg = Release|Any CPU
4856
{B156B6B8-9427-4A72-8986-9A17F4FBC0EA}.Release|x86.Build.0 = Release|Any CPU
4957
EndGlobalSection
58+
GlobalSection(SolutionProperties) = preSolution
59+
HideSolutionNode = FALSE
60+
EndGlobalSection
5061
GlobalSection(NestedProjects) = preSolution
5162
{70FFE5C2-8F7C-49E0-9C31-DB713BA66B8B} = {5D09A785-6509-4FA8-8394-DB761ECFC353}
5263
{B156B6B8-9427-4A72-8986-9A17F4FBC0EA} = {5D09A785-6509-4FA8-8394-DB761ECFC353}
5364
EndGlobalSection
65+
GlobalSection(ExtensibilityGlobals) = postSolution
66+
SolutionGuid = {44C662E3-C7A8-4358-B63F-59F3BE083C60}
67+
EndGlobalSection
5468
EndGlobal

StyleCop.json

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
{
2+
"$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json",
3+
"settings": {
4+
"indentation": {
5+
"indentationSize": 4,
6+
"useTabs": false
7+
},
8+
"documentationRules": {
9+
"documentPrivateElements": false,
10+
"documentPrivateFields": false
11+
},
12+
"orderingRules": {
13+
"systemUsingDirectivesFirst": false,
14+
"usingDirectivesPlacement": "insideNamespace",
15+
"blankLinesBetweenUsingGroups": "omit"
16+
}
17+
}
18+
}

StyleCop.ruleset

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<RuleSet Name="Rules for StyleCop.Analyzers" Description="Code analysis rules for StyleCop.Analyzers.csproj." ToolsVersion="14.0">
3+
<Rules AnalyzerId="AsyncUsageAnalyzers" RuleNamespace="AsyncUsageAnalyzers">
4+
<Rule Id="UseConfigureAwait" Action="Warning" />
5+
</Rules>
6+
<Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed">
7+
8+
</Rules>
9+
<Rules AnalyzerId="Microsoft.CodeAnalysis.CSharp.Features" RuleNamespace="Microsoft.CodeAnalysis.CSharp.Features">
10+
11+
</Rules>
12+
<Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.Analyzers">
13+
<Rule Id="SA1633" Action="None" /> <!-- File must have file header -->
14+
<Rule Id="SA1413" Action="None" /> <!-- Use trailing comma in multi-line initializers -->
15+
<Rule Id="SA1600" Action="None" /> <!-- Elements should be documented - is already covered by CS1519 - public visible type or member should be documented -->
16+
<Rule Id="SA1210" Action="None" /> <!-- Using directives should be ordered alphabetically by the namespaces -->
17+
<Rule Id="SA1623" Action="None" /> <!-- The property's documentation summary text should begin with : 'Gets or sets' -->
18+
<Rule Id="SA1650" Action="None" /> <!-- The documentation header contains invalidly spelled words. -->
19+
<Rule Id="SA1602" Action="None" /> <!-- Enumeration items should be documented. -->
20+
<Rule Id="SA1128" Action="None" /> <!-- Put constructor initializers on their own line. -->
21+
</Rules>
22+
</RuleSet>
Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,18 @@
11
namespace KK.AspNetCore.EasyAuthAuthentication
22
{
33
/// <summary>
4-
/// Default values related to Azure EasyAuth authentication handler
4+
/// Default values related to Azure EasyAuth authentication handler.
55
/// </summary>
66
public static class EasyAuthAuthenticationDefaults
77
{
8+
/// <summary>
9+
/// Default scheme to identify the EasyAuth authentication.
10+
/// </summary>
811
public const string AuthenticationScheme = "EasyAuth";
12+
13+
/// <summary>
14+
/// Default name to identify the EasyAuth authentication.
15+
/// </summary>
916
public const string DisplayName = "Azure Easy Auth";
1017
}
1118
}
Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,58 @@
1-
namespace KK.AspNetCore.EasyAuthAuthentication
1+
namespace KK.AspNetCore.EasyAuthAuthentication
22
{
33
using System;
44
using Microsoft.AspNetCore.Authentication;
55

6+
/// <summary>
7+
/// Extension methods for <see cref="AuthenticationBuilder"/> to add the <see cref="EasyAuthAuthenticationHandler"/> to the pipeline.
8+
/// </summary>
69
public static class EasyAuthAuthenticationExtensions
710
{
11+
/// <summary>
12+
/// Adds the <see cref="EasyAuthAuthenticationHandler"/> for authentication.
13+
/// </summary>
14+
/// <param name="builder"><inheritdoc/></param>
15+
/// <returns>A reference to this instance after the operation has completed.</returns>
816
public static AuthenticationBuilder AddEasyAuth(this AuthenticationBuilder builder)
917
=> builder.AddEasyAuth(EasyAuthAuthenticationDefaults.AuthenticationScheme);
1018

19+
/// <summary>
20+
/// Adds the <see cref="EasyAuthAuthenticationHandler"/> for authentication.
21+
/// </summary>
22+
/// <param name="builder"><inheritdoc/></param>
23+
/// <param name="authenticationScheme">The schema for the Easy Auth handler.</param>
24+
/// <returns>A reference to this instance after the operation has completed.</returns>
1125
public static AuthenticationBuilder AddEasyAuth(this AuthenticationBuilder builder, string authenticationScheme)
1226
=> builder.AddEasyAuth(authenticationScheme, configureOptions: null);
1327

28+
/// <summary>
29+
/// Adds the <see cref="EasyAuthAuthenticationHandler"/> for authentication.
30+
/// </summary>
31+
/// <param name="builder"><inheritdoc/></param>
32+
/// <param name="configureOptions">A callback to configure <see cref="EasyAuthAuthenticationOptions"/>.</param>
33+
/// <returns>A reference to this instance after the operation has completed.</returns>
1434
public static AuthenticationBuilder AddEasyAuth(this AuthenticationBuilder builder, Action<EasyAuthAuthenticationOptions> configureOptions)
1535
=> builder.AddEasyAuth(EasyAuthAuthenticationDefaults.AuthenticationScheme, configureOptions);
1636

37+
/// <summary>
38+
/// Adds the <see cref="EasyAuthAuthenticationHandler"/> for authentication.
39+
/// </summary>
40+
/// <param name="builder"><inheritdoc/></param>
41+
/// <param name="authenticationScheme">The schema for the Easy Auth handler.</param>
42+
/// <param name="configureOptions">A callback to configure <see cref="EasyAuthAuthenticationOptions"/>.</param>
43+
/// <returns>A reference to this instance after the operation has completed.</returns>
1744
public static AuthenticationBuilder AddEasyAuth(this AuthenticationBuilder builder, string authenticationScheme, Action<EasyAuthAuthenticationOptions> configureOptions)
1845
=> builder.AddEasyAuth(authenticationScheme, displayName: EasyAuthAuthenticationDefaults.DisplayName, configureOptions: configureOptions);
1946

47+
/// <summary>
48+
/// Adds the <see cref="EasyAuthAuthenticationHandler"/> for authentication.
49+
/// </summary>
50+
/// <param name="builder"><inheritdoc/></param>
51+
/// <param name="authenticationScheme">The schema for the Easy Auth handler.</param>
52+
/// <param name="displayName">The display name for the Easy Auth handler.</param>
53+
/// <param name="configureOptions">A callback to configure <see cref="EasyAuthAuthenticationOptions"/>.</param>
54+
/// <returns>A reference to this instance after the operation has completed.</returns>
2055
public static AuthenticationBuilder AddEasyAuth(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action<EasyAuthAuthenticationOptions> configureOptions)
21-
{
22-
return builder.AddScheme<EasyAuthAuthenticationOptions, EasyAuthAuthenticationHandler>(authenticationScheme, displayName, configureOptions);
23-
}
56+
=> builder.AddScheme<EasyAuthAuthenticationOptions, EasyAuthAuthenticationHandler>(authenticationScheme, displayName, configureOptions);
2457
}
2558
}

src/KK.AspNetCore.EasyAuthAuthentication/EasyAuthAuthenticationHandler.cs

Lines changed: 41 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -14,53 +14,63 @@ namespace KK.AspNetCore.EasyAuthAuthentication
1414
using Newtonsoft.Json;
1515
using Newtonsoft.Json.Linq;
1616

17+
/// <summary>
18+
/// Enables the handler in an Easy Auth context.
19+
/// </summary>
1720
public class EasyAuthAuthenticationHandler : AuthenticationHandler<EasyAuthAuthenticationOptions>
1821
{
22+
/// <summary>
23+
/// Initializes a new instance of the <see cref="EasyAuthAuthenticationHandler"/> class.
24+
/// </summary>
25+
/// <param name="options">An instance of <see cref="EasyAuthAuthenticationOptions"/>.</param>
26+
/// <param name="logger">An instance of <see cref="ILoggerFactory"/>.</param>
27+
/// <param name="encoder">An instance of <see cref="UrlEncoder"/>.</param>
28+
/// <param name="clock">An instance of <see cref="ISystemClock"/>.</param>
1929
public EasyAuthAuthenticationHandler(
2030
IOptionsMonitor<EasyAuthAuthenticationOptions> options,
2131
ILoggerFactory logger,
2232
UrlEncoder encoder,
23-
ISystemClock clock
24-
) : base(options, logger, encoder, clock)
33+
ISystemClock clock) : base(options, logger, encoder, clock)
2534
{
26-
2735
}
2836

37+
/// <inheritdoc/>
2938
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
3039
{
31-
Logger.LogInformation("starting authentication handler for app service authentication");
40+
this.Logger.LogInformation("starting authentication handler for app service authentication");
3241

3342
if (
3443
(this.Context.User == null ||
3544
this.Context.User.Identity == null ||
36-
this.Context.User.Identity.IsAuthenticated == false ) && this.Context.Request.Path != "/" + $"{Options.AuthEndpoint}")
45+
this.Context.User.Identity.IsAuthenticated == false)
46+
&& this.Context.Request.Path != "/" + $"{this.Options.AuthEndpoint}")
3747
{
3848
var cookieContainer = new CookieContainer();
39-
HttpClientHandler handler = createHandler(ref cookieContainer);
40-
HttpRequestMessage httpRequest = CreateAuthRequest(ref cookieContainer);
49+
var handler = this.CreateHandler(ref cookieContainer);
50+
var httpRequest = this.CreateAuthRequest(ref cookieContainer);
4151

4252
JArray payload = null;
4353
try
4454
{
45-
payload = await getAuthMe(handler, httpRequest);
55+
payload = await this.GetAuthMe(handler, httpRequest);
4656
}
4757
catch (Exception ex)
4858
{
4959
return AuthenticateResult.Fail(ex.Message);
5060
}
5161

5262
// build up identity from json...
53-
AuthenticationTicket ticket = BuildIdentityFromJsonPayload((JObject)payload[0]);
63+
var ticket = this.BuildIdentityFromJsonPayload((JObject)payload[0]);
5464

55-
Logger.LogInformation("Set identity to user context object.");
65+
this.Logger.LogInformation("Set identity to user context object.");
5666
this.Context.User = ticket.Principal;
5767

58-
Logger.LogInformation("identity build was a success, returning ticket");
68+
this.Logger.LogInformation("identity build was a success, returning ticket");
5969
return AuthenticateResult.Success(ticket);
6070
}
6171
else
6272
{
63-
Logger.LogInformation("identity already set, skipping middleware");
73+
this.Logger.LogInformation("identity already set, skipping middleware");
6474
return AuthenticateResult.NoResult();
6575
}
6676
}
@@ -71,53 +81,52 @@ private AuthenticationTicket BuildIdentityFromJsonPayload(JObject payload)
7181
var idToken = payload["id_token"].Value<string>();
7282
var providerName = payload["provider_name"].Value<string>();
7383

74-
Logger.LogDebug("payload was fetched from endpoint. id: {0}", id);
84+
this.Logger.LogDebug("payload was fetched from endpoint. id: {0}", id);
7585

7686
var identity = new GenericIdentity(id);
7787

78-
Logger.LogInformation("building claims from payload...");
88+
this.Logger.LogInformation("building claims from payload...");
7989

80-
List<Claim> claims = new List<Claim>();
90+
var claims = new List<Claim>();
8191
foreach (var claim in payload["user_claims"])
8292
{
8393
claims.Add(new Claim(claim["typ"].ToString(), claim["val"].ToString()));
8494
}
8595

86-
Logger.LogInformation("Add claims to new identity");
96+
this.Logger.LogInformation("Add claims to new identity");
8797

8898
identity.AddClaims(claims);
8999
identity.AddClaim(new Claim("id_token", idToken));
90100
identity.AddClaim(new Claim("provider_name", providerName));
91101
var p = new GenericPrincipal(identity, null);
92102
return new AuthenticationTicket(
93103
p,
94-
EasyAuthAuthenticationDefaults.AuthenticationScheme
95-
);
104+
EasyAuthAuthenticationDefaults.AuthenticationScheme);
96105
}
97106

98107
private HttpRequestMessage CreateAuthRequest(ref CookieContainer cookieContainer)
99108
{
100-
Logger.LogInformation($"identity not found, attempting to fetch from auth endpoint '/{Options.AuthEndpoint}'");
109+
this.Logger.LogInformation($"identity not found, attempting to fetch from auth endpoint '/{this.Options.AuthEndpoint}'");
101110

102-
var uriString = $"{Context.Request.Scheme}://{Context.Request.Host}";
111+
var uriString = $"{this.Context.Request.Scheme}://{this.Context.Request.Host}";
103112

104-
Logger.LogDebug("host uri: {0}", uriString);
113+
this.Logger.LogDebug("host uri: {0}", uriString);
105114

106-
foreach (var c in Context.Request.Cookies)
115+
foreach (var c in this.Context.Request.Cookies)
107116
{
108117
cookieContainer.Add(new Uri(uriString), new Cookie(c.Key, c.Value));
109118
}
110119

111-
Logger.LogDebug("found {0} cookies in request", cookieContainer.Count);
120+
this.Logger.LogDebug("found {0} cookies in request", cookieContainer.Count);
112121

113-
foreach (var cookie in Context.Request.Cookies)
122+
foreach (var cookie in this.Context.Request.Cookies)
114123
{
115-
Logger.LogDebug(cookie.Key);
124+
this.Logger.LogDebug(cookie.Key);
116125
}
117126

118127
// fetch value from endpoint
119-
var request = new HttpRequestMessage(HttpMethod.Get, $"{uriString}/{Options.AuthEndpoint}");
120-
foreach (var header in Context.Request.Headers)
128+
var request = new HttpRequestMessage(HttpMethod.Get, $"{uriString}/{this.Options.AuthEndpoint}");
129+
foreach (var header in this.Context.Request.Headers)
121130
{
122131
if (header.Key.StartsWith("X-ZUMO-"))
123132
{
@@ -128,7 +137,7 @@ private HttpRequestMessage CreateAuthRequest(ref CookieContainer cookieContainer
128137
return request;
129138
}
130139

131-
private static HttpClientHandler createHandler(ref CookieContainer container)
140+
private HttpClientHandler CreateHandler(ref CookieContainer container)
132141
{
133142
var handler = new HttpClientHandler()
134143
{
@@ -137,15 +146,15 @@ private static HttpClientHandler createHandler(ref CookieContainer container)
137146
return handler;
138147
}
139148

140-
private async Task<JArray> getAuthMe(HttpClientHandler handler, HttpRequestMessage httpRequest)
149+
private async Task<JArray> GetAuthMe(HttpClientHandler handler, HttpRequestMessage httpRequest)
141150
{
142151
JArray payload = null;
143-
using (HttpClient client = new HttpClient(handler))
152+
using (var client = new HttpClient(handler))
144153
{
145154
var response = await client.SendAsync(httpRequest);
146155
if (!response.IsSuccessStatusCode)
147156
{
148-
Logger.LogDebug("auth endpoint was not sucessful. Status code: {0}, reason {1}", response.StatusCode, response.ReasonPhrase);
157+
this.Logger.LogDebug("auth endpoint was not sucessful. Status code: {0}, reason {1}", response.StatusCode, response.ReasonPhrase);
149158
throw new WebException("Unable to fetch user information from auth endpoint.");
150159
}
151160

@@ -163,4 +172,4 @@ private async Task<JArray> getAuthMe(HttpClientHandler handler, HttpRequestMessa
163172
return payload;
164173
}
165174
}
166-
}
175+
}

src/KK.AspNetCore.EasyAuthAuthentication/EasyAuthAuthenticationOptions.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,15 @@
33
using System;
44
using Microsoft.AspNetCore.Authentication;
55

6+
/// <summary>
7+
/// Options for the <see cref="EasyAuthAuthenticationHandler"/>.
8+
/// </summary>
69
public class EasyAuthAuthenticationOptions : AuthenticationSchemeOptions
710
{
11+
/// <summary>
12+
/// The endpoint where to look for the <c>JSON</c> with the authentification information.
13+
/// </summary>
14+
/// <value>A relative path to the <c>wwwroot</c> folder.</value>
815
public string AuthEndpoint { get; set; } = ".auth/me";
916
}
1017
}

src/KK.AspNetCore.EasyAuthAuthentication/GitVersion.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@ major-version-bump-message: '\+version:\s?(breaking|major)'
44
minor-version-bump-message: '\+version:\s?(feature|minor)'
55
patch-version-bump-message: '\+version:\s?(fix|patch)'
66
ignore:
7-
sha: []
7+
sha: []

src/KK.AspNetCore.EasyAuthAuthentication/KK.AspNetCore.EasyAuthAuthentication.csproj

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,12 @@
1919
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
2020
</ItemGroup>
2121

22+
<!-- StyleCop Settings -->
23+
<PropertyGroup>
24+
<GenerateDocumentationFile>true</GenerateDocumentationFile>
25+
<CodeAnalysisRuleSet>..\..\StyleCop.ruleset</CodeAnalysisRuleSet>
26+
</PropertyGroup>
27+
<ItemGroup>
28+
<PackageReference Include="StyleCop.Analyzers" Version="1.1.0-beta009" privateassets="all" />
29+
</ItemGroup>
2230
</Project>

0 commit comments

Comments
 (0)