diff --git a/src/Http/Authentication.Abstractions/src/AuthenticateResult.cs b/src/Http/Authentication.Abstractions/src/AuthenticateResult.cs index f801ce530851..f10b5b93922d 100644 --- a/src/Http/Authentication.Abstractions/src/AuthenticateResult.cs +++ b/src/Http/Authentication.Abstractions/src/AuthenticateResult.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Diagnostics.CodeAnalysis; using System.Security.Claims; namespace Microsoft.AspNetCore.Authentication @@ -19,6 +20,7 @@ protected AuthenticateResult() { } /// /// If a ticket was produced, authenticate was successful. /// + [MemberNotNullWhen(true, nameof(Ticket))] public bool Succeeded => Ticket != null; /// diff --git a/src/Http/Authentication.Abstractions/src/AuthenticationHttpContextExtensions.cs b/src/Http/Authentication.Abstractions/src/AuthenticationHttpContextExtensions.cs index 539f1c74f3c9..e6d56aa4fa60 100644 --- a/src/Http/Authentication.Abstractions/src/AuthenticationHttpContextExtensions.cs +++ b/src/Http/Authentication.Abstractions/src/AuthenticationHttpContextExtensions.cs @@ -36,7 +36,7 @@ public static Task AuthenticateAsync(this HttpContext contex /// The context. /// The name of the authentication scheme. /// The result. - public static Task ChallengeAsync(this HttpContext context, string scheme) => + public static Task ChallengeAsync(this HttpContext context, string? scheme) => context.ChallengeAsync(scheme, properties: null); /// @@ -72,7 +72,7 @@ public static Task ChallengeAsync(this HttpContext context, string? scheme, Auth /// The context. /// The name of the authentication scheme. /// The task. - public static Task ForbidAsync(this HttpContext context, string scheme) => + public static Task ForbidAsync(this HttpContext context, string? scheme) => context.ForbidAsync(scheme, properties: null); /// @@ -109,7 +109,7 @@ public static Task ForbidAsync(this HttpContext context, string? scheme, Authent /// The name of the authentication scheme. /// The user. /// The task. - public static Task SignInAsync(this HttpContext context, string scheme, ClaimsPrincipal principal) => + public static Task SignInAsync(this HttpContext context, string? scheme, ClaimsPrincipal principal) => context.SignInAsync(scheme, principal, properties: null); /// diff --git a/src/Http/Authentication.Abstractions/src/AuthenticationTicket.cs b/src/Http/Authentication.Abstractions/src/AuthenticationTicket.cs index 49600607873f..e75656685597 100644 --- a/src/Http/Authentication.Abstractions/src/AuthenticationTicket.cs +++ b/src/Http/Authentication.Abstractions/src/AuthenticationTicket.cs @@ -17,7 +17,7 @@ public class AuthenticationTicket /// the that represents the authenticated user. /// additional properties that can be consumed by the user or runtime. /// the authentication middleware that was responsible for this ticket. - public AuthenticationTicket(ClaimsPrincipal principal, AuthenticationProperties? properties, string? authenticationScheme) + public AuthenticationTicket(ClaimsPrincipal principal, AuthenticationProperties? properties, string authenticationScheme) { if (principal == null) { @@ -41,17 +41,17 @@ public AuthenticationTicket(ClaimsPrincipal principal, string authenticationSche /// /// Gets the authentication type. /// - public string? AuthenticationScheme { get; private set; } + public string AuthenticationScheme { get; } /// /// Gets the claims-principal with authenticated user identities. /// - public ClaimsPrincipal Principal { get; private set; } + public ClaimsPrincipal Principal { get; } /// /// Additional state values for the authentication session. /// - public AuthenticationProperties Properties { get; private set; } + public AuthenticationProperties Properties { get; } /// /// Returns a copy of the ticket. diff --git a/src/Http/Http.Abstractions/src/PathString.cs b/src/Http/Http.Abstractions/src/PathString.cs index 79f82ddd1a4e..48eb14c01571 100644 --- a/src/Http/Http.Abstractions/src/PathString.cs +++ b/src/Http/Http.Abstractions/src/PathString.cs @@ -424,7 +424,7 @@ public override int GetHashCode() /// The left parameter /// The right parameter /// The ToString combination of both values - public static string operator +(PathString left, string right) + public static string operator +(PathString left, string? right) { // This overload exists to prevent the implicit string<->PathString converter from // trying to call the PathString+PathString operator for things that are not path strings. diff --git a/src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs b/src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs index 7ca93485954f..f10e6114cdbd 100644 --- a/src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs +++ b/src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Diagnostics; using System.Linq; using System.Security.Claims; using System.Text.Encodings.Web; @@ -27,9 +28,9 @@ public class CookieAuthenticationHandler : SignInAuthenticationHandler _readCookieTask; - private AuthenticationTicket _refreshTicket; + private string? _sessionKey; + private Task? _readCookieTask; + private AuthenticationTicket? _refreshTicket; public CookieAuthenticationHandler(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) @@ -41,7 +42,7 @@ public CookieAuthenticationHandler(IOptionsMonitor /// protected new CookieAuthenticationEvents Events { - get { return (CookieAuthenticationEvents)base.Events; } + get { return (CookieAuthenticationEvents)base.Events!; } set { base.Events = value; } } @@ -86,7 +87,7 @@ private void CheckForRefresh(AuthenticationTicket ticket) } } - private void RequestRefresh(AuthenticationTicket ticket, ClaimsPrincipal replacedPrincipal = null) + private void RequestRefresh(AuthenticationTicket ticket, ClaimsPrincipal? replacedPrincipal = null) { var issuedUtc = ticket.Properties.IssuedUtc; var expiresUtc = ticket.Properties.ExpiresUtc; @@ -102,7 +103,7 @@ private void RequestRefresh(AuthenticationTicket ticket, ClaimsPrincipal replace } } - private AuthenticationTicket CloneTicket(AuthenticationTicket ticket, ClaimsPrincipal replacedPrincipal) + private AuthenticationTicket CloneTicket(AuthenticationTicket ticket, ClaimsPrincipal? replacedPrincipal) { var principal = replacedPrincipal ?? ticket.Principal; var newPrincipal = new ClaimsPrincipal(); @@ -122,7 +123,7 @@ private AuthenticationTicket CloneTicket(AuthenticationTicket ticket, ClaimsPrin private async Task ReadCookieTicket() { - var cookie = Options.CookieManager.GetRequestCookie(Context, Options.Cookie.Name); + var cookie = Options.CookieManager.GetRequestCookie(Context, Options.Cookie.Name!); if (string.IsNullOrEmpty(cookie)) { return AuthenticateResult.NoResult(); @@ -157,7 +158,7 @@ private async Task ReadCookieTicket() { if (Options.SessionStore != null) { - await Options.SessionStore.RemoveAsync(_sessionKey); + await Options.SessionStore.RemoveAsync(_sessionKey!); } return AuthenticateResult.Fail("Ticket expired"); } @@ -176,6 +177,7 @@ protected override async Task HandleAuthenticateAsync() return result; } + Debug.Assert(result.Ticket != null); var context = new CookieValidatePrincipalContext(Context, Scheme, Options, result.Ticket); await Events.ValidatePrincipal(context); @@ -244,7 +246,7 @@ protected virtual async Task FinishResponseAsync() Options.CookieManager.AppendResponseCookie( Context, - Options.Cookie.Name, + Options.Cookie.Name!, cookieValue, cookieOptions); @@ -252,7 +254,7 @@ protected virtual async Task FinishResponseAsync() } } - protected async override Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties properties) + protected async override Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties? properties) { if (user == null) { @@ -299,7 +301,7 @@ protected async override Task HandleSignInAsync(ClaimsPrincipal user, Authentica signInContext.CookieOptions.Expires = expiresUtc.ToUniversalTime(); } - var ticket = new AuthenticationTicket(signInContext.Principal, signInContext.Properties, signInContext.Scheme.Name); + var ticket = new AuthenticationTicket(signInContext.Principal!, signInContext.Properties, signInContext.Scheme.Name); if (Options.SessionStore != null) { @@ -324,14 +326,14 @@ protected async override Task HandleSignInAsync(ClaimsPrincipal user, Authentica Options.CookieManager.AppendResponseCookie( Context, - Options.Cookie.Name, + Options.Cookie.Name!, cookieValue, signInContext.CookieOptions); var signedInContext = new CookieSignedInContext( Context, Scheme, - signInContext.Principal, + signInContext.Principal!, signInContext.Properties, Options); @@ -344,7 +346,7 @@ protected async override Task HandleSignInAsync(ClaimsPrincipal user, Authentica Logger.AuthenticationSchemeSignedIn(Scheme.Name); } - protected async override Task HandleSignOutAsync(AuthenticationProperties properties) + protected async override Task HandleSignOutAsync(AuthenticationProperties? properties) { properties = properties ?? new AuthenticationProperties(); @@ -369,7 +371,7 @@ protected async override Task HandleSignOutAsync(AuthenticationProperties proper Options.CookieManager.DeleteCookie( Context, - Options.Cookie.Name, + Options.Cookie.Name!, context.CookieOptions); // Only redirect on the logout path @@ -449,7 +451,7 @@ protected override async Task HandleChallengeAsync(AuthenticationProperties prop await Events.RedirectToLogin(redirectContext); } - private string GetTlsTokenBinding() + private string? GetTlsTokenBinding() { var binding = Context.Features.Get()?.GetProvidedTokenBindingId(); return binding == null ? null : Convert.ToBase64String(binding); diff --git a/src/Security/Authentication/Cookies/src/CookieAuthenticationOptions.cs b/src/Security/Authentication/Cookies/src/CookieAuthenticationOptions.cs index 0248669979dc..49e7092b767a 100644 --- a/src/Security/Authentication/Cookies/src/CookieAuthenticationOptions.cs +++ b/src/Security/Authentication/Cookies/src/CookieAuthenticationOptions.cs @@ -71,7 +71,7 @@ public CookieBuilder Cookie /// /// If set this will be used by the CookieAuthenticationHandler for data protection. /// - public IDataProtectionProvider DataProtectionProvider { get; set; } + public IDataProtectionProvider? DataProtectionProvider { get; set; } /// /// The SlidingExpiration is set to true to instruct the handler to re-issue a new cookie with a new @@ -111,7 +111,7 @@ public CookieBuilder Cookie /// public new CookieAuthenticationEvents Events { - get => (CookieAuthenticationEvents)base.Events; + get => (CookieAuthenticationEvents)base.Events!; set => base.Events = value; } @@ -119,20 +119,20 @@ public CookieBuilder Cookie /// The TicketDataFormat is used to protect and unprotect the identity and other properties which are stored in the /// cookie value. If not provided one will be created using . /// - public ISecureDataFormat TicketDataFormat { get; set; } + public ISecureDataFormat TicketDataFormat { get; set; } = default!; /// /// The component used to get cookies from the request or set them on the response. /// /// ChunkingCookieManager will be used by default. /// - public ICookieManager CookieManager { get; set; } + public ICookieManager CookieManager { get; set; } = default!; /// /// An optional container in which to store the identity across requests. When used, only a session identifier is sent /// to the client. This can be used to mitigate potential problems with very large identities. /// - public ITicketStore SessionStore { get; set; } + public ITicketStore? SessionStore { get; set; } /// /// diff --git a/src/Security/Authentication/Cookies/src/CookieExtensions.cs b/src/Security/Authentication/Cookies/src/CookieExtensions.cs index 7763e6a62496..7787ad80944a 100644 --- a/src/Security/Authentication/Cookies/src/CookieExtensions.cs +++ b/src/Security/Authentication/Cookies/src/CookieExtensions.cs @@ -17,13 +17,13 @@ public static AuthenticationBuilder AddCookie(this AuthenticationBuilder builder public static AuthenticationBuilder AddCookie(this AuthenticationBuilder builder, string authenticationScheme) => builder.AddCookie(authenticationScheme, configureOptions: null); - public static AuthenticationBuilder AddCookie(this AuthenticationBuilder builder, Action configureOptions) + public static AuthenticationBuilder AddCookie(this AuthenticationBuilder builder, Action? configureOptions) => builder.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, configureOptions); - public static AuthenticationBuilder AddCookie(this AuthenticationBuilder builder, string authenticationScheme, Action configureOptions) + public static AuthenticationBuilder AddCookie(this AuthenticationBuilder builder, string authenticationScheme, Action? configureOptions) => builder.AddCookie(authenticationScheme, displayName: null, configureOptions: configureOptions); - public static AuthenticationBuilder AddCookie(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action configureOptions) + public static AuthenticationBuilder AddCookie(this AuthenticationBuilder builder, string authenticationScheme, string? displayName, Action? configureOptions) { builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton, PostConfigureCookieAuthenticationOptions>()); builder.Services.AddOptions(authenticationScheme).Validate(o => o.Cookie.Expiration == null, "Cookie.Expiration is ignored, use ExpireTimeSpan instead."); diff --git a/src/Security/Authentication/Cookies/src/CookieSignedInContext.cs b/src/Security/Authentication/Cookies/src/CookieSignedInContext.cs index 98c31dd1906a..d0d1dde8b78b 100644 --- a/src/Security/Authentication/Cookies/src/CookieSignedInContext.cs +++ b/src/Security/Authentication/Cookies/src/CookieSignedInContext.cs @@ -23,7 +23,7 @@ public CookieSignedInContext( HttpContext context, AuthenticationScheme scheme, ClaimsPrincipal principal, - AuthenticationProperties properties, + AuthenticationProperties? properties, CookieAuthenticationOptions options) : base(context, scheme, options, properties) { diff --git a/src/Security/Authentication/Cookies/src/CookieSigningInContext.cs b/src/Security/Authentication/Cookies/src/CookieSigningInContext.cs index 41d7b4f6aeb0..b85429f0cf59 100644 --- a/src/Security/Authentication/Cookies/src/CookieSigningInContext.cs +++ b/src/Security/Authentication/Cookies/src/CookieSigningInContext.cs @@ -25,7 +25,7 @@ public CookieSigningInContext( AuthenticationScheme scheme, CookieAuthenticationOptions options, ClaimsPrincipal principal, - AuthenticationProperties properties, + AuthenticationProperties? properties, CookieOptions cookieOptions) : base(context, scheme, options, properties) { diff --git a/src/Security/Authentication/Cookies/src/CookieSigningOutContext.cs b/src/Security/Authentication/Cookies/src/CookieSigningOutContext.cs index 34f6e49ab66d..fd0e9712b1ed 100644 --- a/src/Security/Authentication/Cookies/src/CookieSigningOutContext.cs +++ b/src/Security/Authentication/Cookies/src/CookieSigningOutContext.cs @@ -22,7 +22,7 @@ public CookieSigningOutContext( HttpContext context, AuthenticationScheme scheme, CookieAuthenticationOptions options, - AuthenticationProperties properties, + AuthenticationProperties? properties, CookieOptions cookieOptions) : base(context, scheme, options, properties) => CookieOptions = cookieOptions; diff --git a/src/Security/Authentication/Cookies/src/ICookieManager.cs b/src/Security/Authentication/Cookies/src/ICookieManager.cs index 4514fefa973a..5db41d72230c 100644 --- a/src/Security/Authentication/Cookies/src/ICookieManager.cs +++ b/src/Security/Authentication/Cookies/src/ICookieManager.cs @@ -17,7 +17,7 @@ public interface ICookieManager /// /// /// - string GetRequestCookie(HttpContext context, string key); + string? GetRequestCookie(HttpContext context, string key); /// /// Append the given cookie to the response. @@ -26,7 +26,7 @@ public interface ICookieManager /// /// /// - void AppendResponseCookie(HttpContext context, string key, string value, CookieOptions options); + void AppendResponseCookie(HttpContext context, string key, string? value, CookieOptions options); /// /// Append a delete cookie to the response. diff --git a/src/Security/Authentication/Cookies/src/LoggingExtensions.cs b/src/Security/Authentication/Cookies/src/LoggingExtensions.cs index a8a59f29ddd5..340fb04a2958 100644 --- a/src/Security/Authentication/Cookies/src/LoggingExtensions.cs +++ b/src/Security/Authentication/Cookies/src/LoggingExtensions.cs @@ -7,8 +7,8 @@ namespace Microsoft.Extensions.Logging { internal static class LoggingExtensions { - private static Action _authenticationSchemeSignedIn; - private static Action _authenticationSchemeSignedOut; + private static Action _authenticationSchemeSignedIn; + private static Action _authenticationSchemeSignedOut; static LoggingExtensions() { diff --git a/src/Security/Authentication/Cookies/src/Microsoft.AspNetCore.Authentication.Cookies.csproj b/src/Security/Authentication/Cookies/src/Microsoft.AspNetCore.Authentication.Cookies.csproj index 803c58f40877..af13015b04f1 100644 --- a/src/Security/Authentication/Cookies/src/Microsoft.AspNetCore.Authentication.Cookies.csproj +++ b/src/Security/Authentication/Cookies/src/Microsoft.AspNetCore.Authentication.Cookies.csproj @@ -1,4 +1,4 @@ - + ASP.NET Core middleware that enables an application to use cookie based authentication. @@ -9,6 +9,7 @@ true aspnetcore;authentication;security false + enable diff --git a/src/Security/Authentication/Cookies/src/PostConfigureCookieAuthenticationOptions.cs b/src/Security/Authentication/Cookies/src/PostConfigureCookieAuthenticationOptions.cs index 48895072e931..588109880005 100644 --- a/src/Security/Authentication/Cookies/src/PostConfigureCookieAuthenticationOptions.cs +++ b/src/Security/Authentication/Cookies/src/PostConfigureCookieAuthenticationOptions.cs @@ -26,7 +26,7 @@ public PostConfigureCookieAuthenticationOptions(IDataProtectionProvider dataProt /// The options instance to configure. public void PostConfigure(string name, CookieAuthenticationOptions options) { - options.DataProtectionProvider = options.DataProtectionProvider ?? _dp; + options.DataProtectionProvider ??= _dp; if (string.IsNullOrEmpty(options.Cookie.Name)) { diff --git a/src/Security/Authentication/Core/src/AuthenticationBuilder.cs b/src/Security/Authentication/Core/src/AuthenticationBuilder.cs index d4efd0c847f0..c89c15300321 100644 --- a/src/Security/Authentication/Core/src/AuthenticationBuilder.cs +++ b/src/Security/Authentication/Core/src/AuthenticationBuilder.cs @@ -25,7 +25,7 @@ public AuthenticationBuilder(IServiceCollection services) /// public virtual IServiceCollection Services { get; } - private AuthenticationBuilder AddSchemeHelper(string authenticationScheme, string displayName, Action configureOptions) + private AuthenticationBuilder AddSchemeHelper(string authenticationScheme, string? displayName, Action? configureOptions) where TOptions : AuthenticationSchemeOptions, new() where THandler : class, IAuthenticationHandler { @@ -57,7 +57,7 @@ private AuthenticationBuilder AddSchemeHelper(string authent /// The display name of this scheme. /// Used to configure the scheme options. /// The builder. - public virtual AuthenticationBuilder AddScheme(string authenticationScheme, string displayName, Action configureOptions) + public virtual AuthenticationBuilder AddScheme(string authenticationScheme, string? displayName, Action? configureOptions) where TOptions : AuthenticationSchemeOptions, new() where THandler : AuthenticationHandler => AddSchemeHelper(authenticationScheme, displayName, configureOptions); @@ -70,7 +70,7 @@ public virtual AuthenticationBuilder AddScheme(string authen /// The name of this scheme. /// Used to configure the scheme options. /// The builder. - public virtual AuthenticationBuilder AddScheme(string authenticationScheme, Action configureOptions) + public virtual AuthenticationBuilder AddScheme(string authenticationScheme, Action? configureOptions) where TOptions : AuthenticationSchemeOptions, new() where THandler : AuthenticationHandler => AddScheme(authenticationScheme, displayName: null, configureOptions: configureOptions); @@ -85,7 +85,7 @@ public virtual AuthenticationBuilder AddScheme(string authen /// The display name of this scheme. /// Used to configure the scheme options. /// The builder. - public virtual AuthenticationBuilder AddRemoteScheme(string authenticationScheme, string displayName, Action configureOptions) + public virtual AuthenticationBuilder AddRemoteScheme(string authenticationScheme, string? displayName, Action? configureOptions) where TOptions : RemoteAuthenticationOptions, new() where THandler : RemoteAuthenticationHandler { @@ -101,7 +101,7 @@ public virtual AuthenticationBuilder AddRemoteScheme(string /// The display name of this scheme. /// Used to configure the scheme options. /// The builder. - public virtual AuthenticationBuilder AddPolicyScheme(string authenticationScheme, string displayName, Action configureOptions) + public virtual AuthenticationBuilder AddPolicyScheme(string authenticationScheme, string? displayName, Action configureOptions) => AddSchemeHelper(authenticationScheme, displayName, configureOptions); // Used to ensure that there's always a default sign in scheme that's not itself @@ -116,7 +116,7 @@ public EnsureSignInScheme(IOptions authOptions) public void PostConfigure(string name, TOptions options) { - options.SignInScheme = options.SignInScheme ?? _authOptions.DefaultSignInScheme ?? _authOptions.DefaultScheme; + options.SignInScheme ??= _authOptions.DefaultSignInScheme ?? _authOptions.DefaultScheme; } } } diff --git a/src/Security/Authentication/Core/src/AuthenticationHandler.cs b/src/Security/Authentication/Core/src/AuthenticationHandler.cs index 5f8a8d588f14..d19286d03077 100644 --- a/src/Security/Authentication/Core/src/AuthenticationHandler.cs +++ b/src/Security/Authentication/Core/src/AuthenticationHandler.cs @@ -13,11 +13,11 @@ namespace Microsoft.AspNetCore.Authentication { public abstract class AuthenticationHandler : IAuthenticationHandler where TOptions : AuthenticationSchemeOptions, new() { - private Task _authenticateTask; + private Task? _authenticateTask; - public AuthenticationScheme Scheme { get; private set; } - public TOptions Options { get; private set; } - protected HttpContext Context { get; private set; } + public AuthenticationScheme Scheme { get; private set; } = default!; + public TOptions Options { get; private set; } = default!; + protected HttpContext Context { get; private set; } = default!; protected HttpRequest Request { @@ -45,7 +45,7 @@ protected HttpResponse Response /// The handler calls methods on the events which give the application control at certain points where processing is occurring. /// If it is not provided a default instance is supplied which does nothing when the methods are called. /// - protected virtual object Events { get; set; } + protected virtual object? Events { get; set; } protected virtual string ClaimsIssuer => Options.ClaimsIssuer ?? Scheme.Name; @@ -116,7 +116,7 @@ protected virtual async Task InitializeEventsAsync() protected string BuildRedirectUri(string targetPath) => Request.Scheme + "://" + Request.Host + OriginalPathBase + targetPath; - protected virtual string ResolveTarget(string scheme) + protected virtual string? ResolveTarget(string? scheme) { var target = scheme ?? Options.ForwardDefaultSelector?.Invoke(Context) ?? Options.ForwardDefault; @@ -135,10 +135,10 @@ public async Task AuthenticateAsync() } // Calling Authenticate more than once should always return the original value. - var result = await HandleAuthenticateOnceAsync(); - if (result?.Failure == null) + var result = await HandleAuthenticateOnceAsync() ?? AuthenticateResult.NoResult(); + if (result.Failure == null) { - var ticket = result?.Ticket; + var ticket = result.Ticket; if (ticket?.Principal != null) { Logger.AuthenticationSchemeAuthenticated(Scheme.Name); @@ -212,7 +212,7 @@ protected virtual Task HandleChallengeAsync(AuthenticationProperties properties) return Task.CompletedTask; } - public async Task ChallengeAsync(AuthenticationProperties properties) + public async Task ChallengeAsync(AuthenticationProperties? properties) { var target = ResolveTarget(Options.ForwardChallenge); if (target != null) @@ -221,12 +221,12 @@ public async Task ChallengeAsync(AuthenticationProperties properties) return; } - properties = properties ?? new AuthenticationProperties(); + properties ??= new AuthenticationProperties(); await HandleChallengeAsync(properties); Logger.AuthenticationSchemeChallenged(Scheme.Name); } - public async Task ForbidAsync(AuthenticationProperties properties) + public async Task ForbidAsync(AuthenticationProperties? properties) { var target = ResolveTarget(Options.ForwardForbid); if (target != null) @@ -235,7 +235,7 @@ public async Task ForbidAsync(AuthenticationProperties properties) return; } - properties = properties ?? new AuthenticationProperties(); + properties ??= new AuthenticationProperties(); await HandleForbiddenAsync(properties); Logger.AuthenticationSchemeForbidden(Scheme.Name); } diff --git a/src/Security/Authentication/Core/src/AuthenticationSchemeOptions.cs b/src/Security/Authentication/Core/src/AuthenticationSchemeOptions.cs index 0f1e1b98146d..1cfe428cf528 100644 --- a/src/Security/Authentication/Core/src/AuthenticationSchemeOptions.cs +++ b/src/Security/Authentication/Core/src/AuthenticationSchemeOptions.cs @@ -26,17 +26,17 @@ public virtual void Validate(string scheme) /// /// Gets or sets the issuer that should be used for any claims that are created /// - public string ClaimsIssuer { get; set; } + public string? ClaimsIssuer { get; set; } /// /// Instance used for events /// - public object Events { get; set; } + public object? Events { get; set; } /// /// If set, will be used as the service type to get the Events instance instead of the property. /// - public Type EventsType { get; set; } + public Type? EventsType { get; set; } /// /// If set, this specifies a default scheme that authentication handlers should forward all authentication operations to @@ -44,42 +44,42 @@ public virtual void Validate(string scheme) /// setting first, followed by checking the ForwardDefaultSelector, followed by ForwardDefault. The first non null result /// will be used as the target scheme to forward to. /// - public string ForwardDefault { get; set; } + public string? ForwardDefault { get; set; } /// /// If set, this specifies the target scheme that this scheme should forward AuthenticateAsync calls to. /// For example Context.AuthenticateAsync("ThisScheme") => Context.AuthenticateAsync("ForwardAuthenticateValue"); /// Set the target to the current scheme to disable forwarding and allow normal processing. /// - public string ForwardAuthenticate { get; set; } + public string? ForwardAuthenticate { get; set; } /// /// If set, this specifies the target scheme that this scheme should forward ChallengeAsync calls to. /// For example Context.ChallengeAsync("ThisScheme") => Context.ChallengeAsync("ForwardChallengeValue"); /// Set the target to the current scheme to disable forwarding and allow normal processing. /// - public string ForwardChallenge { get; set; } + public string? ForwardChallenge { get; set; } /// /// If set, this specifies the target scheme that this scheme should forward ForbidAsync calls to. /// For example Context.ForbidAsync("ThisScheme") => Context.ForbidAsync("ForwardForbidValue"); /// Set the target to the current scheme to disable forwarding and allow normal processing. /// - public string ForwardForbid { get; set; } + public string? ForwardForbid { get; set; } /// /// If set, this specifies the target scheme that this scheme should forward SignInAsync calls to. /// For example Context.SignInAsync("ThisScheme") => Context.SignInAsync("ForwardSignInValue"); /// Set the target to the current scheme to disable forwarding and allow normal processing. /// - public string ForwardSignIn { get; set; } + public string? ForwardSignIn { get; set; } /// /// If set, this specifies the target scheme that this scheme should forward SignOutAsync calls to. /// For example Context.SignOutAsync("ThisScheme") => Context.SignOutAsync("ForwardSignOutValue"); /// Set the target to the current scheme to disable forwarding and allow normal processing. /// - public string ForwardSignOut { get; set; } + public string? ForwardSignOut { get; set; } /// /// Used to select a default scheme for the current request that authentication handlers should forward all authentication operations to @@ -87,7 +87,7 @@ public virtual void Validate(string scheme) /// setting first, followed by checking the ForwardDefaultSelector, followed by ForwardDefault. The first non null result /// will be used as the target scheme to forward to. /// - public Func ForwardDefaultSelector { get; set; } + public Func? ForwardDefaultSelector { get; set; } } } diff --git a/src/Security/Authentication/Core/src/AuthenticationServiceCollectionExtensions.cs b/src/Security/Authentication/Core/src/AuthenticationServiceCollectionExtensions.cs index 6c381b84ab0d..70e707f34da2 100644 --- a/src/Security/Authentication/Core/src/AuthenticationServiceCollectionExtensions.cs +++ b/src/Security/Authentication/Core/src/AuthenticationServiceCollectionExtensions.cs @@ -58,7 +58,7 @@ public EnsureSignInScheme(IOptions authOptions) public void PostConfigure(string name, TOptions options) { - options.SignInScheme = options.SignInScheme ?? _authOptions.DefaultSignInScheme; + options.SignInScheme ??= _authOptions.DefaultSignInScheme; } } diff --git a/src/Security/Authentication/Core/src/Events/AccessDeniedContext.cs b/src/Security/Authentication/Core/src/Events/AccessDeniedContext.cs index f01d69453bb7..30cfee4e693c 100644 --- a/src/Security/Authentication/Core/src/Events/AccessDeniedContext.cs +++ b/src/Security/Authentication/Core/src/Events/AccessDeniedContext.cs @@ -27,18 +27,18 @@ public AccessDeniedContext( /// /// Additional state values for the authentication session. /// - public AuthenticationProperties Properties { get; set; } + public AuthenticationProperties? Properties { get; set; } /// /// Gets or sets the return URL that will be flowed up to the access denied page. /// If is not set, this property is not used. /// - public string ReturnUrl { get; set; } + public string? ReturnUrl { get; set; } /// /// Gets or sets the parameter name that will be used to flow the return URL. /// By default, this property is set to . /// - public string ReturnUrlParameter { get; set; } + public string ReturnUrlParameter { get; set; } = default!; } } diff --git a/src/Security/Authentication/Core/src/Events/HandleRequestContext.cs b/src/Security/Authentication/Core/src/Events/HandleRequestContext.cs index 52dd9ce12fdc..d31cc921e29f 100644 --- a/src/Security/Authentication/Core/src/Events/HandleRequestContext.cs +++ b/src/Security/Authentication/Core/src/Events/HandleRequestContext.cs @@ -16,7 +16,7 @@ protected HandleRequestContext( /// /// The which is used by the handler. /// - public HandleRequestResult Result { get; protected set; } + public HandleRequestResult Result { get; protected set; } = default!; /// /// Discontinue all processing for this request and return to the client. @@ -29,4 +29,4 @@ protected HandleRequestContext( /// public void SkipHandler() => Result = HandleRequestResult.SkipHandler(); } -} \ No newline at end of file +} diff --git a/src/Security/Authentication/Core/src/Events/PrincipalContext.cs b/src/Security/Authentication/Core/src/Events/PrincipalContext.cs index 8bf40760a18e..f2585fdfbc77 100644 --- a/src/Security/Authentication/Core/src/Events/PrincipalContext.cs +++ b/src/Security/Authentication/Core/src/Events/PrincipalContext.cs @@ -19,12 +19,12 @@ public abstract class PrincipalContext : PropertiesContext w /// The authentication scheme. /// The authentication options associated with the scheme. /// The authentication properties. - protected PrincipalContext(HttpContext context, AuthenticationScheme scheme, TOptions options, AuthenticationProperties properties) + protected PrincipalContext(HttpContext context, AuthenticationScheme scheme, TOptions options, AuthenticationProperties? properties) : base(context, scheme, options, properties) { } /// /// Gets the containing the user claims. /// - public virtual ClaimsPrincipal Principal { get; set; } + public virtual ClaimsPrincipal? Principal { get; set; } } } diff --git a/src/Security/Authentication/Core/src/Events/PropertiesContext.cs b/src/Security/Authentication/Core/src/Events/PropertiesContext.cs index f1730d0d7f7f..f803d248b5c3 100644 --- a/src/Security/Authentication/Core/src/Events/PropertiesContext.cs +++ b/src/Security/Authentication/Core/src/Events/PropertiesContext.cs @@ -17,7 +17,7 @@ public abstract class PropertiesContext : BaseContext where /// The authentication scheme. /// The authentication options associated with the scheme. /// The authentication properties. - protected PropertiesContext(HttpContext context, AuthenticationScheme scheme, TOptions options, AuthenticationProperties properties) + protected PropertiesContext(HttpContext context, AuthenticationScheme scheme, TOptions options, AuthenticationProperties? properties) : base(context, scheme, options) { Properties = properties ?? new AuthenticationProperties(); diff --git a/src/Security/Authentication/Core/src/Events/RemoteAuthenticationContext.cs b/src/Security/Authentication/Core/src/Events/RemoteAuthenticationContext.cs index b7a0168798c4..76b42239bc87 100644 --- a/src/Security/Authentication/Core/src/Events/RemoteAuthenticationContext.cs +++ b/src/Security/Authentication/Core/src/Events/RemoteAuthenticationContext.cs @@ -23,14 +23,14 @@ protected RemoteAuthenticationContext( HttpContext context, AuthenticationScheme scheme, TOptions options, - AuthenticationProperties properties) + AuthenticationProperties? properties) : base(context, scheme, options) => Properties = properties ?? new AuthenticationProperties(); /// /// Gets the containing the user claims. /// - public ClaimsPrincipal Principal { get; set; } + public ClaimsPrincipal? Principal { get; set; } /// /// Gets or sets the . @@ -40,10 +40,10 @@ protected RemoteAuthenticationContext( /// /// Calls success creating a ticket with the and . /// - public void Success() => Result = HandleRequestResult.Success(new AuthenticationTicket(Principal, Properties, Scheme.Name)); + public void Success() => Result = HandleRequestResult.Success(new AuthenticationTicket(Principal!, Properties, Scheme.Name)); public void Fail(Exception failure) => Result = HandleRequestResult.Fail(failure); public void Fail(string failureMessage) => Result = HandleRequestResult.Fail(failureMessage); } -} \ No newline at end of file +} diff --git a/src/Security/Authentication/Core/src/Events/RemoteFailureContext.cs b/src/Security/Authentication/Core/src/Events/RemoteFailureContext.cs index 6b3598f40a5d..c39956aa3f30 100644 --- a/src/Security/Authentication/Core/src/Events/RemoteFailureContext.cs +++ b/src/Security/Authentication/Core/src/Events/RemoteFailureContext.cs @@ -24,11 +24,11 @@ public RemoteFailureContext( /// /// User friendly error message for the error. /// - public Exception Failure { get; set; } + public Exception? Failure { get; set; } /// /// Additional state values for the authentication session. /// - public AuthenticationProperties Properties { get; set; } + public AuthenticationProperties? Properties { get; set; } } } diff --git a/src/Security/Authentication/Core/src/Events/ResultContext.cs b/src/Security/Authentication/Core/src/Events/ResultContext.cs index 12b21f4bf68f..b8ca95b43e8f 100644 --- a/src/Security/Authentication/Core/src/Events/ResultContext.cs +++ b/src/Security/Authentication/Core/src/Events/ResultContext.cs @@ -12,6 +12,8 @@ namespace Microsoft.AspNetCore.Authentication /// public abstract class ResultContext : BaseContext where TOptions : AuthenticationSchemeOptions { + private AuthenticationProperties? _properties; + /// /// Constructor. /// @@ -24,26 +26,30 @@ protected ResultContext(HttpContext context, AuthenticationScheme scheme, TOptio /// /// Gets or sets the containing the user claims. /// - public ClaimsPrincipal Principal { get; set; } + public ClaimsPrincipal? Principal { get; set; } - private AuthenticationProperties _properties; /// /// Gets or sets the . /// - public AuthenticationProperties Properties { - get => _properties ?? (_properties = new AuthenticationProperties()); + public AuthenticationProperties Properties + { + get + { + _properties ??= new AuthenticationProperties(); + return _properties; + } set => _properties = value; } /// /// Gets the result. /// - public AuthenticateResult Result { get; private set; } + public AuthenticateResult Result { get; private set; } = default!; /// /// Calls success creating a ticket with the and . /// - public void Success() => Result = HandleRequestResult.Success(new AuthenticationTicket(Principal, Properties, Scheme.Name)); + public void Success() => Result = HandleRequestResult.Success(new AuthenticationTicket(Principal!, Properties, Scheme.Name)); /// /// Indicates that there was no information returned for this authentication scheme. diff --git a/src/Security/Authentication/Core/src/Events/TicketReceivedContext.cs b/src/Security/Authentication/Core/src/Events/TicketReceivedContext.cs index 51b77a37fa6b..665cb2769a70 100644 --- a/src/Security/Authentication/Core/src/Events/TicketReceivedContext.cs +++ b/src/Security/Authentication/Core/src/Events/TicketReceivedContext.cs @@ -19,6 +19,6 @@ public TicketReceivedContext( : base(context, scheme, options, ticket?.Properties) => Principal = ticket?.Principal; - public string ReturnUri { get; set; } + public string? ReturnUri { get; set; } } } diff --git a/src/Security/Authentication/Core/src/IDataSerializer.cs b/src/Security/Authentication/Core/src/IDataSerializer.cs index ad9c523005c0..be1367600cc6 100644 --- a/src/Security/Authentication/Core/src/IDataSerializer.cs +++ b/src/Security/Authentication/Core/src/IDataSerializer.cs @@ -1,11 +1,15 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System.Diagnostics.CodeAnalysis; + namespace Microsoft.AspNetCore.Authentication { public interface IDataSerializer { byte[] Serialize(TModel model); + + [return: MaybeNull] TModel Deserialize(byte[] data); } } diff --git a/src/Security/Authentication/Core/src/ISecureDataFormat.cs b/src/Security/Authentication/Core/src/ISecureDataFormat.cs index 73b1b882b59b..56b815440b74 100644 --- a/src/Security/Authentication/Core/src/ISecureDataFormat.cs +++ b/src/Security/Authentication/Core/src/ISecureDataFormat.cs @@ -1,13 +1,20 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System.Diagnostics.CodeAnalysis; + namespace Microsoft.AspNetCore.Authentication { public interface ISecureDataFormat { string Protect(TData data); - string Protect(TData data, string purpose); + + string Protect(TData data, string? purpose); + + [return: MaybeNull] TData Unprotect(string protectedText); - TData Unprotect(string protectedText, string purpose); + + [return: MaybeNull] + TData Unprotect(string protectedText, string? purpose); } } diff --git a/src/Security/Authentication/Core/src/JsonDocumentAuthExtensions.cs b/src/Security/Authentication/Core/src/JsonDocumentAuthExtensions.cs index 83784ddfd3b4..eaa3ea5c30e6 100644 --- a/src/Security/Authentication/Core/src/JsonDocumentAuthExtensions.cs +++ b/src/Security/Authentication/Core/src/JsonDocumentAuthExtensions.cs @@ -7,7 +7,7 @@ namespace Microsoft.AspNetCore.Authentication { public static class JsonDocumentAuthExtensions { - public static string GetString(this JsonElement element, string key) + public static string? GetString(this JsonElement element, string key) { if (element.TryGetProperty(key, out var property) && property.ValueKind != JsonValueKind.Null) { diff --git a/src/Security/Authentication/Core/src/LoggingExtensions.cs b/src/Security/Authentication/Core/src/LoggingExtensions.cs index 75a1e3e6e342..d8a9d3ef64b9 100644 --- a/src/Security/Authentication/Core/src/LoggingExtensions.cs +++ b/src/Security/Authentication/Core/src/LoggingExtensions.cs @@ -7,20 +7,20 @@ namespace Microsoft.Extensions.Logging { internal static class LoggingExtensions { - private static readonly Action _authenticationSchemeAuthenticated; - private static readonly Action _authenticationSchemeNotAuthenticated; - private static readonly Action _authenticationSchemeNotAuthenticatedWithFailure; - private static readonly Action _authenticationSchemeChallenged; - private static readonly Action _authenticationSchemeForbidden; - private static readonly Action _remoteAuthenticationError; - private static readonly Action _signInHandled; - private static readonly Action _signInSkipped; - private static readonly Action _correlationPropertyNotFound; - private static readonly Action _correlationCookieNotFound; - private static readonly Action _unexpectedCorrelationCookieValue; - private static readonly Action _accessDeniedError; - private static readonly Action _accessDeniedContextHandled; - private static readonly Action _accessDeniedContextSkipped; + private static readonly Action _authenticationSchemeAuthenticated; + private static readonly Action _authenticationSchemeNotAuthenticated; + private static readonly Action _authenticationSchemeNotAuthenticatedWithFailure; + private static readonly Action _authenticationSchemeChallenged; + private static readonly Action _authenticationSchemeForbidden; + private static readonly Action _remoteAuthenticationError; + private static readonly Action _signInHandled; + private static readonly Action _signInSkipped; + private static readonly Action _correlationPropertyNotFound; + private static readonly Action _correlationCookieNotFound; + private static readonly Action _unexpectedCorrelationCookieValue; + private static readonly Action _accessDeniedError; + private static readonly Action _accessDeniedContextHandled; + private static readonly Action _accessDeniedContextSkipped; static LoggingExtensions() { diff --git a/src/Security/Authentication/Core/src/Microsoft.AspNetCore.Authentication.csproj b/src/Security/Authentication/Core/src/Microsoft.AspNetCore.Authentication.csproj index e81a55f314c3..5d8135751dbf 100644 --- a/src/Security/Authentication/Core/src/Microsoft.AspNetCore.Authentication.csproj +++ b/src/Security/Authentication/Core/src/Microsoft.AspNetCore.Authentication.csproj @@ -1,4 +1,4 @@ - + ASP.NET Core common types used by the various authentication middleware components. @@ -8,6 +8,7 @@ true aspnetcore;authentication;security false + enable diff --git a/src/Security/Authentication/Core/src/PolicySchemeHandler.cs b/src/Security/Authentication/Core/src/PolicySchemeHandler.cs index 4dbbb7de2d9f..3a171f1cf29c 100644 --- a/src/Security/Authentication/Core/src/PolicySchemeHandler.cs +++ b/src/Security/Authentication/Core/src/PolicySchemeHandler.cs @@ -18,19 +18,19 @@ public class PolicySchemeHandler : SignInAuthenticationHandler options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { } - protected override Task HandleChallengeAsync(AuthenticationProperties properties) + protected override Task HandleChallengeAsync(AuthenticationProperties? properties) => throw new NotImplementedException(); - protected override Task HandleForbiddenAsync(AuthenticationProperties properties) + protected override Task HandleForbiddenAsync(AuthenticationProperties? properties) => throw new NotImplementedException(); - protected override Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties properties) + protected override Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties? properties) => throw new NotImplementedException(); - protected override Task HandleSignOutAsync(AuthenticationProperties properties) + protected override Task HandleSignOutAsync(AuthenticationProperties? properties) => throw new NotImplementedException(); protected override Task HandleAuthenticateAsync() => throw new NotImplementedException(); } -} \ No newline at end of file +} diff --git a/src/Security/Authentication/Core/src/PropertiesSerializer.cs b/src/Security/Authentication/Core/src/PropertiesSerializer.cs index c213bc4f6056..0789d1e1a169 100644 --- a/src/Security/Authentication/Core/src/PropertiesSerializer.cs +++ b/src/Security/Authentication/Core/src/PropertiesSerializer.cs @@ -26,7 +26,7 @@ public virtual byte[] Serialize(AuthenticationProperties model) } } - public virtual AuthenticationProperties Deserialize(byte[] data) + public virtual AuthenticationProperties? Deserialize(byte[] data) { using (var memory = new MemoryStream(data)) { @@ -59,7 +59,7 @@ public virtual void Write(BinaryWriter writer, AuthenticationProperties properti } } - public virtual AuthenticationProperties Read(BinaryReader reader) + public virtual AuthenticationProperties? Read(BinaryReader reader) { if (reader == null) { @@ -72,12 +72,12 @@ public virtual AuthenticationProperties Read(BinaryReader reader) } var count = reader.ReadInt32(); - var extra = new Dictionary(count); + var extra = new Dictionary(count); for (var index = 0; index != count; ++index) { - string key = reader.ReadString(); - string value = reader.ReadString(); + var key = reader.ReadString(); + var value = reader.ReadString(); extra.Add(key, value); } return new AuthenticationProperties(extra); diff --git a/src/Security/Authentication/Core/src/RemoteAuthenticationHandler.cs b/src/Security/Authentication/Core/src/RemoteAuthenticationHandler.cs index 2f650f097127..ed5e379d6617 100644 --- a/src/Security/Authentication/Core/src/RemoteAuthenticationHandler.cs +++ b/src/Security/Authentication/Core/src/RemoteAuthenticationHandler.cs @@ -2,6 +2,7 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Diagnostics; using System.Security.Cryptography; using System.Text.Encodings.Web; using System.Threading.Tasks; @@ -18,7 +19,7 @@ public abstract class RemoteAuthenticationHandler : AuthenticationHand private const string CorrelationMarker = "N"; private const string AuthSchemeKey = ".AuthScheme"; - protected string SignInScheme => Options.SignInScheme; + protected string? SignInScheme => Options.SignInScheme; /// /// The handler calls methods on the events which give the application control at certain points where processing is occurring. @@ -26,7 +27,7 @@ public abstract class RemoteAuthenticationHandler : AuthenticationHand /// protected new RemoteAuthenticationEvents Events { - get { return (RemoteAuthenticationEvents)base.Events; } + get { return (RemoteAuthenticationEvents)base.Events!; } set { base.Events = value; } } @@ -46,9 +47,9 @@ public virtual async Task HandleRequestAsync() return false; } - AuthenticationTicket ticket = null; - Exception exception = null; - AuthenticationProperties properties = null; + AuthenticationTicket? ticket = null; + Exception? exception = null; + AuthenticationProperties? properties = null; try { var authResult = await HandleRemoteAuthenticateAsync(); @@ -109,6 +110,7 @@ public virtual async Task HandleRequestAsync() } // We have a ticket if we get here + Debug.Assert(ticket != null); var ticketContext = new TicketReceivedContext(Context, Scheme, Options, ticket) { ReturnUri = ticket.Properties.RedirectUri @@ -135,7 +137,7 @@ public virtual async Task HandleRequestAsync() } } - await Context.SignInAsync(SignInScheme, ticketContext.Principal, ticketContext.Properties); + await Context.SignInAsync(SignInScheme, ticketContext.Principal!, ticketContext.Properties); // Default redirect path is the base path if (string.IsNullOrEmpty(ticketContext.ReturnUri)) @@ -165,10 +167,9 @@ protected override async Task HandleAuthenticateAsync() } // The SignInScheme may be shared with multiple providers, make sure this provider issued the identity. - string authenticatedScheme; var ticket = result.Ticket; if (ticket != null && ticket.Principal != null && ticket.Properties != null - && ticket.Properties.Items.TryGetValue(AuthSchemeKey, out authenticatedScheme) + && ticket.Properties.Items.TryGetValue(AuthSchemeKey, out var authenticatedScheme) && string.Equals(Scheme.Name, authenticatedScheme, StringComparison.Ordinal)) { return AuthenticateResult.Success(new AuthenticationTicket(ticket.Principal, @@ -211,9 +212,9 @@ protected virtual bool ValidateCorrelationId(AuthenticationProperties properties throw new ArgumentNullException(nameof(properties)); } - if (!properties.Items.TryGetValue(CorrelationProperty, out string correlationId)) + if (!properties.Items.TryGetValue(CorrelationProperty, out var correlationId)) { - Logger.CorrelationPropertyNotFound(Options.CorrelationCookie.Name); + Logger.CorrelationPropertyNotFound(Options.CorrelationCookie.Name!); return false; } diff --git a/src/Security/Authentication/Core/src/RemoteAuthenticationOptions.cs b/src/Security/Authentication/Core/src/RemoteAuthenticationOptions.cs index 4dd39ca16e3c..933d6e000dc0 100644 --- a/src/Security/Authentication/Core/src/RemoteAuthenticationOptions.cs +++ b/src/Security/Authentication/Core/src/RemoteAuthenticationOptions.cs @@ -70,17 +70,17 @@ public override void Validate() /// This cannot be set at the same time as BackchannelCertificateValidator unless the value /// can be downcast to a WebRequestHandler. /// - public HttpMessageHandler BackchannelHttpHandler { get; set; } + public HttpMessageHandler? BackchannelHttpHandler { get; set; } /// /// Used to communicate with the remote identity provider. /// - public HttpClient Backchannel { get; set; } + public HttpClient Backchannel { get; set; } = default!; /// /// Gets or sets the type used to secure data. /// - public IDataProtectionProvider DataProtectionProvider { get; set; } + public IDataProtectionProvider? DataProtectionProvider { get; set; } /// /// The request path within the application's base path where the user-agent will be returned. @@ -110,7 +110,7 @@ public override void Validate() /// This value typically corresponds to a cookie middleware registered in the Startup class. /// When omitted, is used as a fallback value. /// - public string SignInScheme { get; set; } + public string? SignInScheme { get; set; } /// /// Gets or sets the time limit for completing the authentication flow (15 minutes by default). @@ -119,7 +119,7 @@ public override void Validate() public new RemoteAuthenticationEvents Events { - get => (RemoteAuthenticationEvents)base.Events; + get => (RemoteAuthenticationEvents)base.Events!; set => base.Events = value; } diff --git a/src/Security/Authentication/Core/src/RequestPathBaseCookieBuilder.cs b/src/Security/Authentication/Core/src/RequestPathBaseCookieBuilder.cs index 2efc05c155d2..d4f81c85ca2f 100644 --- a/src/Security/Authentication/Core/src/RequestPathBaseCookieBuilder.cs +++ b/src/Security/Authentication/Core/src/RequestPathBaseCookieBuilder.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -14,7 +14,7 @@ public class RequestPathBaseCookieBuilder : CookieBuilder /// /// Gets an optional value that is appended to the request path base. /// - protected virtual string AdditionalPath { get; } + protected virtual string? AdditionalPath { get; } public override CookieOptions Build(HttpContext context, DateTimeOffset expiresFrom) { diff --git a/src/Security/Authentication/Core/src/SecureDataFormat.cs b/src/Security/Authentication/Core/src/SecureDataFormat.cs index f35025d8bb5f..e53a51e71a5e 100644 --- a/src/Security/Authentication/Core/src/SecureDataFormat.cs +++ b/src/Security/Authentication/Core/src/SecureDataFormat.cs @@ -1,6 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System.Diagnostics.CodeAnalysis; using Microsoft.AspNetCore.DataProtection; namespace Microsoft.AspNetCore.Authentication @@ -21,7 +22,7 @@ public string Protect(TData data) return Protect(data, purpose: null); } - public string Protect(TData data, string purpose) + public string Protect(TData data, string? purpose) { var userData = _serializer.Serialize(data); @@ -35,12 +36,14 @@ public string Protect(TData data, string purpose) return Base64UrlTextEncoder.Encode(protectedData); } + [return: MaybeNull] public TData Unprotect(string protectedText) { return Unprotect(protectedText, purpose: null); } - public TData Unprotect(string protectedText, string purpose) + [return: MaybeNull] + public TData Unprotect(string protectedText, string? purpose) { try { @@ -76,4 +79,4 @@ public TData Unprotect(string protectedText, string purpose) } } } -} \ No newline at end of file +} diff --git a/src/Security/Authentication/Core/src/SignInAuthenticationHandler.cs b/src/Security/Authentication/Core/src/SignInAuthenticationHandler.cs index dbd612dc1010..064ea47ae0ed 100644 --- a/src/Security/Authentication/Core/src/SignInAuthenticationHandler.cs +++ b/src/Security/Authentication/Core/src/SignInAuthenticationHandler.cs @@ -19,7 +19,7 @@ public abstract class SignInAuthenticationHandler : SignOutAuthenticat public SignInAuthenticationHandler(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { } - public virtual Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties properties) + public virtual Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties? properties) { var target = ResolveTarget(Options.ForwardSignIn); return (target != null) @@ -33,7 +33,7 @@ public virtual Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties p /// /// /// A Task. - protected abstract Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties properties); + protected abstract Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties? properties); } -} \ No newline at end of file +} diff --git a/src/Security/Authentication/Core/src/SignOutAuthenticationHandler.cs b/src/Security/Authentication/Core/src/SignOutAuthenticationHandler.cs index 015cb39e05f0..12b2027fc40e 100644 --- a/src/Security/Authentication/Core/src/SignOutAuthenticationHandler.cs +++ b/src/Security/Authentication/Core/src/SignOutAuthenticationHandler.cs @@ -18,7 +18,7 @@ public abstract class SignOutAuthenticationHandler : AuthenticationHan public SignOutAuthenticationHandler(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { } - public virtual Task SignOutAsync(AuthenticationProperties properties) + public virtual Task SignOutAsync(AuthenticationProperties? properties) { var target = ResolveTarget(Options.ForwardSignOut); return (target != null) @@ -31,6 +31,6 @@ public virtual Task SignOutAsync(AuthenticationProperties properties) /// /// /// A Task. - protected abstract Task HandleSignOutAsync(AuthenticationProperties properties); + protected abstract Task HandleSignOutAsync(AuthenticationProperties? properties); } -} \ No newline at end of file +} diff --git a/src/Security/Authentication/Core/src/TicketSerializer.cs b/src/Security/Authentication/Core/src/TicketSerializer.cs index e33ec71725fb..0ef66646753a 100644 --- a/src/Security/Authentication/Core/src/TicketSerializer.cs +++ b/src/Security/Authentication/Core/src/TicketSerializer.cs @@ -28,7 +28,7 @@ public virtual byte[] Serialize(AuthenticationTicket ticket) } } - public virtual AuthenticationTicket Deserialize(byte[] data) + public virtual AuthenticationTicket? Deserialize(byte[] data) { using (var memory = new MemoryStream(data)) { @@ -142,7 +142,7 @@ protected virtual void WriteClaim(BinaryWriter writer, Claim claim) } } - public virtual AuthenticationTicket Read(BinaryReader reader) + public virtual AuthenticationTicket? Read(BinaryReader reader) { if (reader == null) { diff --git a/src/Security/build.cmd b/src/Security/build.cmd new file mode 100644 index 000000000000..2406296662e9 --- /dev/null +++ b/src/Security/build.cmd @@ -0,0 +1,3 @@ +@ECHO OFF +SET RepoRoot=%~dp0..\.. +%RepoRoot%\build.cmd -projects %~dp0**\*.*proj %* diff --git a/src/Shared/ChunkingCookieManager/ChunkingCookieManager.cs b/src/Shared/ChunkingCookieManager/ChunkingCookieManager.cs index 098e3d669076..395e23d5cc01 100644 --- a/src/Shared/ChunkingCookieManager/ChunkingCookieManager.cs +++ b/src/Shared/ChunkingCookieManager/ChunkingCookieManager.cs @@ -1,6 +1,8 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +#nullable enable + using System; using System.Collections.Generic; using System.Globalization; @@ -61,7 +63,7 @@ public ChunkingCookieManager() public bool ThrowForPartialCookies { get; set; } // Parse the "chunks-XX" to determine how many chunks there should be. - private static int ParseChunksCount(string value) + private static int ParseChunksCount(string? value) { if (value != null && value.StartsWith(ChunkCountPrefix, StringComparison.Ordinal)) { @@ -82,7 +84,7 @@ private static int ParseChunksCount(string value) /// /// /// The reassembled cookie, if any, or null. - public string GetRequestCookie(HttpContext context, string key) + public string? GetRequestCookie(HttpContext context, string key) { if (context == null) { @@ -144,7 +146,7 @@ public string GetRequestCookie(HttpContext context, string key) /// /// /// - public void AppendResponseCookie(HttpContext context, string key, string value, CookieOptions options) + public void AppendResponseCookie(HttpContext context, string key, string? value, CookieOptions options) { if (context == null) {