Skip to content

Commit b49fa91

Browse files
committed
nullable enabled and fixed styling inline with latest language version
1 parent 09aa6a3 commit b49fa91

23 files changed

+78
-99
lines changed

src/AspNetCore.Authentication.Basic/AspNetCore.Authentication.Basic.csproj

+3-1
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,10 @@
1717
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
1818
<Title>$(AssemblyName)</Title>
1919
<RepositoryType>git</RepositoryType>
20-
<PackageIconUrl />
2120
<NeutralLanguage />
21+
<LangVersion>latest</LangVersion>
22+
<Nullable>enable</Nullable>
23+
<!--<ImplicitUsings>enable</ImplicitUsings>-->
2224
<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>
2325
<PackageLicenseFile>LICENSE.txt</PackageLicenseFile>
2426
<PackageReadmeFile>README.md</PackageReadmeFile>

src/AspNetCore.Authentication.Basic/BasicExtensions.cs

+6-6
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ public static AuthenticationBuilder AddBasic(this AuthenticationBuilder builder,
4040
/// <param name="builder"></param>
4141
/// <param name="configureOptions">The configure options.</param>
4242
/// <returns>The instance of <see cref="AuthenticationBuilder"/></returns>
43-
public static AuthenticationBuilder AddBasic(this AuthenticationBuilder builder, Action<BasicOptions> configureOptions)
43+
public static AuthenticationBuilder AddBasic(this AuthenticationBuilder builder, Action<BasicOptions>? configureOptions)
4444
=> builder.AddBasic(BasicDefaults.AuthenticationScheme, configureOptions);
4545

4646
/// <summary>
@@ -51,7 +51,7 @@ public static AuthenticationBuilder AddBasic(this AuthenticationBuilder builder,
5151
/// <param name="authenticationScheme">The authentication scheme.</param>
5252
/// <param name="configureOptions">The configure options.</param>
5353
/// <returns>The instance of <see cref="AuthenticationBuilder"/></returns>
54-
public static AuthenticationBuilder AddBasic(this AuthenticationBuilder builder, string authenticationScheme, Action<BasicOptions> configureOptions)
54+
public static AuthenticationBuilder AddBasic(this AuthenticationBuilder builder, string authenticationScheme, Action<BasicOptions>? configureOptions)
5555
=> builder.AddBasic(authenticationScheme, displayName: null, configureOptions: configureOptions);
5656

5757
/// <summary>
@@ -63,7 +63,7 @@ public static AuthenticationBuilder AddBasic(this AuthenticationBuilder builder,
6363
/// <param name="displayName">The display name.</param>
6464
/// <param name="configureOptions">The configure options.</param>
6565
/// <returns>The instance of <see cref="AuthenticationBuilder"/></returns>
66-
public static AuthenticationBuilder AddBasic(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action<BasicOptions> configureOptions)
66+
public static AuthenticationBuilder AddBasic(this AuthenticationBuilder builder, string authenticationScheme, string? displayName, Action<BasicOptions>? configureOptions)
6767
{
6868
// Adds post configure options to the pipeline.
6969
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IPostConfigureOptions<BasicOptions>, BasicPostConfigureOptions>());
@@ -107,7 +107,7 @@ public static AuthenticationBuilder AddBasic<TBasicUserValidationService>(this A
107107
/// <param name="builder"></param>
108108
/// <param name="configureOptions">The <see cref="BasicOptions"/>.</param>
109109
/// <returns>The instance of <see cref="AuthenticationBuilder"/></returns>
110-
public static AuthenticationBuilder AddBasic<TBasicUserValidationService>(this AuthenticationBuilder builder, Action<BasicOptions> configureOptions) where TBasicUserValidationService : class, IBasicUserValidationService
110+
public static AuthenticationBuilder AddBasic<TBasicUserValidationService>(this AuthenticationBuilder builder, Action<BasicOptions>? configureOptions) where TBasicUserValidationService : class, IBasicUserValidationService
111111
=> builder.AddBasic<TBasicUserValidationService>(BasicDefaults.AuthenticationScheme, configureOptions);
112112

113113
/// <summary>
@@ -119,7 +119,7 @@ public static AuthenticationBuilder AddBasic<TBasicUserValidationService>(this A
119119
/// <param name="authenticationScheme">The authentication scheme.</param>
120120
/// <param name="configureOptions">The <see cref="BasicOptions"/>.</param>
121121
/// <returns>The instance of <see cref="AuthenticationBuilder"/></returns>
122-
public static AuthenticationBuilder AddBasic<TBasicUserValidationService>(this AuthenticationBuilder builder, string authenticationScheme, Action<BasicOptions> configureOptions) where TBasicUserValidationService : class, IBasicUserValidationService
122+
public static AuthenticationBuilder AddBasic<TBasicUserValidationService>(this AuthenticationBuilder builder, string authenticationScheme, Action<BasicOptions>? configureOptions) where TBasicUserValidationService : class, IBasicUserValidationService
123123
=> builder.AddBasic<TBasicUserValidationService>(authenticationScheme, displayName: null, configureOptions: configureOptions);
124124

125125
/// <summary>
@@ -132,7 +132,7 @@ public static AuthenticationBuilder AddBasic<TBasicUserValidationService>(this A
132132
/// <param name="displayName">The display name.</param>
133133
/// <param name="configureOptions">The <see cref="BasicOptions"/>.</param>
134134
/// <returns>The instance of <see cref="AuthenticationBuilder"/></returns>
135-
public static AuthenticationBuilder AddBasic<TBasicUserValidationService>(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action<BasicOptions> configureOptions)
135+
public static AuthenticationBuilder AddBasic<TBasicUserValidationService>(this AuthenticationBuilder builder, string authenticationScheme, string? displayName, Action<BasicOptions>? configureOptions)
136136
where TBasicUserValidationService : class, IBasicUserValidationService
137137
{
138138
// Adds implementation of IBasicUserValidationService to the dependency container.

src/AspNetCore.Authentication.Basic/BasicHandler.cs

+15-9
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ public BasicHandler(IOptionsMonitor<BasicOptions> options, ILoggerFactory logger
5353
/// <summary>
5454
/// Get or set <see cref="BasicEvents"/>.
5555
/// </summary>
56-
protected new BasicEvents Events { get => (BasicEvents)base.Events; set => base.Events = value; }
56+
protected new BasicEvents Events { get => (BasicEvents)base.Events!; set => base.Events = value; }
5757

5858
/// <summary>
5959
/// Create an instance of <see cref="BasicEvents"/>.
@@ -91,6 +91,12 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
9191
return AuthenticateResult.NoResult();
9292
}
9393

94+
if (string.IsNullOrWhiteSpace(headerValue.Parameter))
95+
{
96+
Logger.LogInformation($"'Authorization' header found but the scheme value/credentials is not present.");
97+
return AuthenticateResult.NoResult();
98+
}
99+
94100
BasicCredentials credentials;
95101
try
96102
{
@@ -172,7 +178,7 @@ protected override async Task HandleChallengeAsync(AuthenticationProperties prop
172178
await base.HandleChallengeAsync(properties);
173179
}
174180

175-
private async Task<AuthenticateResult> RaiseAndHandleEventValidateCredentialsAsync(BasicCredentials credentials)
181+
private async Task<AuthenticateResult?> RaiseAndHandleEventValidateCredentialsAsync(BasicCredentials credentials)
176182
{
177183
var validateCredentialsContext = new BasicValidateCredentialsContext(Context, Scheme, Options, credentials.Username, credentials.Password);
178184
await Events.ValidateCredentialsAsync(validateCredentialsContext).ConfigureAwait(false);
@@ -210,7 +216,10 @@ private async Task<AuthenticateResult> RaiseAndHandleAuthenticationSucceededAsyn
210216
{
211217
// If claims principal is set and is authenticated then build a ticket by calling and return success.
212218
authenticationSucceededContext.Success();
213-
return authenticationSucceededContext.Result;
219+
if (authenticationSucceededContext.Result != null)
220+
{
221+
return authenticationSucceededContext.Result;
222+
}
214223
}
215224

216225
Logger.LogError("No authenticated prinicipal set.");
@@ -229,7 +238,7 @@ private bool IgnoreAuthenticationIfAllowAnonymous()
229238

230239
private async Task<bool> ValidateUsingBasicUserValidationServiceAsync(string username, string password)
231240
{
232-
IBasicUserValidationService basicUserValidationService = null;
241+
IBasicUserValidationService? basicUserValidationService = null;
233242
if (Options.BasicUserValidationServiceType != null)
234243
{
235244
basicUserValidationService = ActivatorUtilities.GetServiceOrCreateInstance(Context.RequestServices, Options.BasicUserValidationServiceType) as IBasicUserValidationService;
@@ -279,18 +288,15 @@ private static BasicCredentials DecodeBasicCredentials(string credentials)
279288
throw new Exception("Username cannot be empty.");
280289
}
281290

282-
if (password == null)
283-
{
284-
password = string.Empty;
285-
}
291+
password ??= string.Empty;
286292

287293
return new BasicCredentials(username, password);
288294
}
289295

290296
private readonly struct BasicCredentials
291297
{
292298
public BasicCredentials(string username, string password)
293-
{
299+
{
294300
Username = username;
295301
Password = password;
296302
}

src/AspNetCore.Authentication.Basic/BasicOptions.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public BasicOptions()
2424
/// Required to be set if SuppressWWWAuthenticateHeader is not set to true.
2525
/// <see href="https://tools.ietf.org/html/rfc7235#section-2.2"/>
2626
/// </summary>
27-
public string Realm { get; set; }
27+
public string? Realm { get; set; }
2828

2929
/// <summary>
3030
/// Default value is false.
@@ -42,7 +42,7 @@ public BasicOptions()
4242
/// </summary>
4343
public new BasicEvents Events
4444
{
45-
get => (BasicEvents)base.Events;
45+
get => (BasicEvents)base.Events!;
4646
set => base.Events = value;
4747
}
4848

@@ -54,6 +54,6 @@ public BasicOptions()
5454
public bool IgnoreAuthenticationIfAllowAnonymous { get; set; }
5555
#endif
5656

57-
internal Type BasicUserValidationServiceType { get; set; } = null;
57+
internal Type? BasicUserValidationServiceType { get; set; } = null;
5858
}
5959
}

src/AspNetCore.Authentication.Basic/BasicPostConfigureOptions.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ namespace AspNetCore.Authentication.Basic
1111
/// </summary>
1212
internal class BasicPostConfigureOptions : IPostConfigureOptions<BasicOptions>
1313
{
14-
public void PostConfigure(string name, BasicOptions options)
14+
public void PostConfigure(string? name, BasicOptions options)
1515
{
1616
if (!options.SuppressWWWAuthenticateHeader && string.IsNullOrWhiteSpace(options.Realm))
1717
{

src/AspNetCore.Authentication.Basic/BasicUtils.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ internal static class BasicUtils
2323
/// <param name="claimsIssuer">The claims issuer.</param>
2424
/// <param name="claims">The list of claims.</param>
2525
/// <returns></returns>
26-
internal static ClaimsPrincipal BuildClaimsPrincipal(string username, string schemeName, string claimsIssuer, IEnumerable<Claim> claims = null)
26+
internal static ClaimsPrincipal BuildClaimsPrincipal(string? username, string schemeName, string? claimsIssuer, IEnumerable<Claim>? claims = null)
2727
{
2828
if (string.IsNullOrWhiteSpace(schemeName)) throw new ArgumentNullException(nameof(schemeName));
2929

src/AspNetCore.Authentication.Basic/Events/BasicAuthenticationSucceededContext.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public BasicAuthenticationSucceededContext(HttpContext context, AuthenticationSc
3030
/// <summary>
3131
/// Get the <see cref="ClaimsPrincipal"/> containing the user claims.
3232
/// </summary>
33-
public new ClaimsPrincipal Principal => base.Principal;
33+
public new ClaimsPrincipal Principal => base.Principal!;
3434

3535
/// <summary>
3636
/// Called to replace the claims principal. The supplied principal will replace the value of the
@@ -57,7 +57,7 @@ public void ReplacePrincipal(ClaimsPrincipal principal)
5757
public void AddClaim(Claim claim)
5858
{
5959
if (claim == null) throw new ArgumentNullException(nameof(claim));
60-
(Principal?.Identity as ClaimsIdentity).AddClaim(claim);
60+
(Principal.Identity as ClaimsIdentity)?.AddClaim(claim);
6161
}
6262

6363
/// <summary>
@@ -68,7 +68,7 @@ public void AddClaim(Claim claim)
6868
public void AddClaims(IEnumerable<Claim> claims)
6969
{
7070
if (claims == null) throw new ArgumentNullException(nameof(claims));
71-
(Principal?.Identity as ClaimsIdentity).AddClaims(claims);
71+
(Principal.Identity as ClaimsIdentity)?.AddClaims(claims);
7272
}
7373
}
7474
}

src/AspNetCore.Authentication.Basic/Events/BasicEvents.cs

+5-5
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ public class BasicEvents
2020
/// or construct an authentication principal from the user details &amp; attach it to the context.Principal property and finally call context.Success() method.
2121
/// If only context.Principal property set without calling context.Success() method then, Success() method is automaticalled called.
2222
/// </remarks>
23-
public Func<BasicValidateCredentialsContext, Task> OnValidateCredentials { get; set; }
23+
public Func<BasicValidateCredentialsContext, Task>? OnValidateCredentials { get; set; }
2424

2525
/// <summary>
2626
/// A delegate assigned to this property will be invoked when the authentication succeeds. It will not be called if OnValidateCredentials delegate is assigned.
@@ -29,12 +29,12 @@ public class BasicEvents
2929
/// <remarks>
3030
/// Only use this if you know what you are doing.
3131
/// </remarks>
32-
public Func<BasicAuthenticationSucceededContext, Task> OnAuthenticationSucceeded { get; set; }
32+
public Func<BasicAuthenticationSucceededContext, Task>? OnAuthenticationSucceeded { get; set; }
3333

3434
/// <summary>
3535
/// A delegate assigned to this property will be invoked when the authentication fails.
3636
/// </summary>
37-
public Func<BasicAuthenticationFailedContext, Task> OnAuthenticationFailed { get; set; }
37+
public Func<BasicAuthenticationFailedContext, Task>? OnAuthenticationFailed { get; set; }
3838

3939
/// <summary>
4040
/// A delegate assigned to this property will be invoked before a challenge is sent back to the caller when handling unauthorized response.
@@ -46,7 +46,7 @@ public class BasicEvents
4646
/// changing the 401 result to 302 of a login page or external sign-in location.)
4747
/// Call context.Handled() at the end so that any default logic for this challenge will be skipped.
4848
/// </remarks>
49-
public Func<BasicHandleChallengeContext, Task> OnHandleChallenge { get; set; }
49+
public Func<BasicHandleChallengeContext, Task>? OnHandleChallenge { get; set; }
5050

5151
/// <summary>
5252
/// A delegate assigned to this property will be invoked if Authorization fails and results in a Forbidden response.
@@ -56,7 +56,7 @@ public class BasicEvents
5656
/// Set the delegate to handle Forbid.
5757
/// Call context.Handled() at the end so that any default logic will be skipped.
5858
/// </remarks>
59-
public Func<BasicHandleForbiddenContext, Task> OnHandleForbidden { get; set; }
59+
public Func<BasicHandleForbiddenContext, Task>? OnHandleForbidden { get; set; }
6060

6161

6262

src/AspNetCore.Authentication.Basic/Events/BasicValidateCredentialsContext.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ public BasicValidateCredentialsContext(HttpContext context, AuthenticationScheme
4545
/// and <see cref="ResultContext{TOptions}.Success"/> method will also be called.
4646
/// </summary>
4747
/// <param name="claims">Claims to be added to the identity.</param>
48-
public void ValidationSucceeded(IEnumerable<Claim> claims = null)
48+
public void ValidationSucceeded(IEnumerable<Claim>? claims = null)
4949
{
5050
Principal = BasicUtils.BuildClaimsPrincipal(Username, Scheme.Name, Options.ClaimsIssuer, claims);
5151
Success();
@@ -56,7 +56,7 @@ public void ValidationSucceeded(IEnumerable<Claim> claims = null)
5656
/// otherwise, <see cref="ResultContext{TOptions}.Fail(string)"/> method will be called.
5757
/// </summary>
5858
/// <param name="failureMessage">(Optional) The failure message.</param>
59-
public void ValidationFailed(string failureMessage = null)
59+
public void ValidationFailed(string? failureMessage = null)
6060
{
6161
if (string.IsNullOrWhiteSpace(failureMessage))
6262
{
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// This file is used by Code Analysis to maintain SuppressMessage
2+
// attributes that are applied to this project.
3+
// Project-level suppressions either have no target or are given
4+
// a specific target and scoped to a namespace, type, member, etc.
5+
6+
using System.Diagnostics.CodeAnalysis;
7+
8+
[assembly: SuppressMessage("Style", "IDE0130:Namespace does not match folder structure", Justification = "Does not need to match, folder used for structural purpose only.", Scope = "namespace", Target = "~N:AspNetCore.Authentication.Basic")]
9+
[assembly: SuppressMessage("Style", "IDE0290:Use primary constructor", Justification = "Not a fan of this.")]
10+
[assembly: SuppressMessage("Maintainability", "CA1510:Use ArgumentNullException throw helper", Justification = "Not supported by older frameworks.")]

test/AspNetCore.Authentication.Basic.Tests/BasicExtensionsTests.cs

-3
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,6 @@
33

44
using Microsoft.AspNetCore.Authentication;
55
using Microsoft.Extensions.DependencyInjection;
6-
using System;
7-
using System.Linq;
8-
using System.Threading.Tasks;
96
using Xunit;
107

118
namespace AspNetCore.Authentication.Basic.Tests

test/AspNetCore.Authentication.Basic.Tests/BasicHandlerTests.cs

+1-5
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,11 @@
77
using Microsoft.AspNetCore.TestHost;
88
using Microsoft.Extensions.DependencyInjection;
99
using Microsoft.Extensions.Options;
10-
using System;
11-
using System.Collections.Generic;
12-
using System.Linq;
1310
using System.Net;
1411
using System.Net.Http;
1512
using System.Net.Http.Headers;
1613
using System.Security.Claims;
1714
using System.Text.Json;
18-
using System.Threading.Tasks;
1915
using Xunit;
2016

2117
namespace AspNetCore.Authentication.Basic.Tests
@@ -591,7 +587,7 @@ public async Task MultiScheme()
591587

592588
#endregion // Multi-Scheme
593589

594-
private async Task<ClaimsPrincipalDto> DeserializeClaimsPrincipalAsync(HttpResponseMessage response)
590+
private static async Task<ClaimsPrincipalDto> DeserializeClaimsPrincipalAsync(HttpResponseMessage response)
595591
{
596592
return JsonSerializer.Deserialize<ClaimsPrincipalDto>(await response.Content.ReadAsStringAsync());
597593
}

test/AspNetCore.Authentication.Basic.Tests/BasicOptionsTests.cs

-3
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,7 @@
44
using AspNetCore.Authentication.Basic.Tests.Infrastructure;
55
using Microsoft.Extensions.DependencyInjection;
66
using Microsoft.Extensions.Options;
7-
using System;
87
using System.Net;
9-
using System.Net.Http;
10-
using System.Threading.Tasks;
118
using Xunit;
129

1310
namespace AspNetCore.Authentication.Basic.Tests

test/AspNetCore.Authentication.Basic.Tests/BasicPostConfigureOptionsTests.cs

+4-6
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,12 @@
22
// Licensed under the MIT License. See License.txt in the project root for license information.
33

44
using AspNetCore.Authentication.Basic.Tests.Infrastructure;
5-
using System;
6-
using System.Threading.Tasks;
75
using Xunit;
86

97
namespace AspNetCore.Authentication.Basic.Tests
108
{
11-
public class BasicPostConfigureOptionsTests
12-
{
9+
public class BasicPostConfigureOptionsTests
10+
{
1311
[Fact]
1412
public async Task PostConfigure_no_option_set_throws_exception()
1513
{
@@ -77,13 +75,13 @@ await RunAuthInitWithServiceAsync(options =>
7775
}
7876

7977

80-
private async Task RunAuthInitAsync(Action<BasicOptions> configureOptions)
78+
private static async Task RunAuthInitAsync(Action<BasicOptions> configureOptions)
8179
{
8280
var server = TestServerBuilder.BuildTestServer(configureOptions);
8381
await server.CreateClient().GetAsync(TestServerBuilder.BaseUrl);
8482
}
8583

86-
private async Task RunAuthInitWithServiceAsync(Action<BasicOptions> configureOptions)
84+
private static async Task RunAuthInitWithServiceAsync(Action<BasicOptions> configureOptions)
8785
{
8886
var server = TestServerBuilder.BuildTestServerWithService(configureOptions);
8987
await server.CreateClient().GetAsync(TestServerBuilder.BaseUrl);

0 commit comments

Comments
 (0)