diff --git a/samples/CookieSample/Startup.cs b/samples/CookieSample/Startup.cs index a465d7884c..cac42ca38d 100644 --- a/samples/CookieSample/Startup.cs +++ b/samples/CookieSample/Startup.cs @@ -1,13 +1,11 @@ using System; -using System.Linq; using System.Security.Claims; using Microsoft.AspNet; using Microsoft.AspNet.Abstractions; -using Microsoft.AspNet.Abstractions.Security; -using Microsoft.AspNet.HttpFeature.Security; -using Microsoft.AspNet.Security; +using Microsoft.AspNet.DependencyInjection; +using Microsoft.AspNet.DependencyInjection.Fallback; +using Microsoft.AspNet.Logging; using Microsoft.AspNet.Security.Cookies; -using Microsoft.AspNet.Security.Infrastructure; namespace CookieSample { @@ -15,6 +13,11 @@ namespace CookieSample { public void Configuration(IBuilder app) { + // TODO: Move to host. + var serviceCollection = new ServiceCollection(); + serviceCollection.AddInstance(new NullLoggerFactory()); + app.ServiceProvider = serviceCollection.BuildServiceProvider(app.ServiceProvider); + app.UseCookieAuthentication(new CookieAuthenticationOptions() { @@ -35,5 +38,23 @@ namespace CookieSample await context.Response.WriteAsync("Hello old timer"); }); } + + // TODO: Temp workaround until the host reliably provides logging. + // If ILoggerFactory is never guaranteed, move this fallback into Microsoft.AspNet.Logging. + private class NullLoggerFactory : ILoggerFactory + { + public ILogger Create(string name) + { + return new NullLongger(); + } + } + + private class NullLongger : ILogger + { + public bool WriteCore(TraceType eventType, int eventId, object state, Exception exception, Func formatter) + { + return false; + } + } } } \ No newline at end of file diff --git a/samples/CookieSample/project.json b/samples/CookieSample/project.json index b25b4148d6..c5d7dde2cc 100644 --- a/samples/CookieSample/project.json +++ b/samples/CookieSample/project.json @@ -2,6 +2,7 @@ "version": "0.1-alpha-*", "dependencies": { "Microsoft.AspNet.Abstractions": "0.1-alpha-*", + "Microsoft.AspNet.DependencyInjection": "0.1-alpha-*", "Microsoft.AspNet.Security": "", "Microsoft.AspNet.Security.Cookies": "", "Microsoft.AspNet.Hosting": "0.1-alpha-*", @@ -9,6 +10,7 @@ "Microsoft.AspNet.Abstractions": "0.1-alpha-*", "Microsoft.AspNet.FeatureModel": "0.1-alpha-*", "Microsoft.AspNet.HttpFeature": "0.1-alpha-*", + "Microsoft.AspNet.Logging": "0.1-alpha-*", "Microsoft.AspNet.Server.WebListener": "0.1-alpha-*" }, "commands": { "web": "Microsoft.AspNet.Hosting server.name=Microsoft.AspNet.Server.WebListener server.urls=http://localhost:12345" }, diff --git a/src/Microsoft.AspNet.Security.Cookies/CookieAuthenticationExtensions.cs b/src/Microsoft.AspNet.Security.Cookies/CookieAuthenticationExtensions.cs index 3afed37607..c32f3e7b80 100644 --- a/src/Microsoft.AspNet.Security.Cookies/CookieAuthenticationExtensions.cs +++ b/src/Microsoft.AspNet.Security.Cookies/CookieAuthenticationExtensions.cs @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. -using System; using Microsoft.AspNet.Abstractions; +using Microsoft.AspNet.DependencyInjection; using Microsoft.AspNet.Logging; using Microsoft.AspNet.Security.Cookies; -using Microsoft.AspNet.Security.DataHandler; using Microsoft.AspNet.Security.DataProtection; namespace Microsoft.AspNet @@ -20,43 +19,12 @@ namespace Microsoft.AspNet /// The IAppBuilder passed to your configuration method /// An options class that controls the middleware behavior /// The original app parameter - public static IBuilder UseCookieAuthentication(this IBuilder app, CookieAuthenticationOptions options) + public static IBuilder UseCookieAuthentication([NotNull] this IBuilder app, [NotNull] CookieAuthenticationOptions options) { - if (app == null) - { - throw new ArgumentNullException("app"); - } - - // TODO: Extension methods for this? - var loggerFactory = (ILoggerFactory)app.ServiceProvider.GetService(typeof(ILoggerFactory)) ?? new NullLoggerFactory(); - ILogger logger = loggerFactory.Create(typeof(CookieAuthenticationMiddleware).FullName); - - if (options.TicketDataFormat == null) - { - IDataProtector dataProtector = app.CreateDataProtector( - typeof(CookieAuthenticationMiddleware).FullName, - options.AuthenticationType, "v1"); - options.TicketDataFormat = new TicketDataFormat(dataProtector); - } - - return app.Use(next => new CookieAuthenticationMiddleware(next, logger, options).Invoke); - } - - // TODO: Temp workaround until the host reliably provides logging. - private class NullLoggerFactory : ILoggerFactory - { - public ILogger Create(string name) - { - return new NullLongger(); - } - } - - private class NullLongger : ILogger - { - public bool WriteCore(TraceType eventType, int eventId, object state, Exception exception, Func formatter) - { - return false; - } + // TODO: Use UseMiddleware to inject dependencies once it can discover Invoke from a base class. + var dataProtectionProvider = app.ServiceProvider.GetService(); + var loggerFactory = app.ServiceProvider.GetService(); + return app.Use(next => new CookieAuthenticationMiddleware(next, dataProtectionProvider, loggerFactory, options).Invoke); } } } \ No newline at end of file diff --git a/src/Microsoft.AspNet.Security.Cookies/CookieAuthenticationHandler.cs b/src/Microsoft.AspNet.Security.Cookies/CookieAuthenticationHandler.cs index 0c8bc2b3f3..b03e8a2e2a 100644 --- a/src/Microsoft.AspNet.Security.Cookies/CookieAuthenticationHandler.cs +++ b/src/Microsoft.AspNet.Security.Cookies/CookieAuthenticationHandler.cs @@ -25,12 +25,8 @@ namespace Microsoft.AspNet.Security.Cookies private DateTimeOffset _renewIssuedUtc; private DateTimeOffset _renewExpiresUtc; - public CookieAuthenticationHandler(ILogger logger) + public CookieAuthenticationHandler([NotNull] ILogger logger) { - if (logger == null) - { - throw new ArgumentNullException("logger"); - } _logger = logger; } @@ -81,7 +77,7 @@ namespace Microsoft.AspNet.Security.Cookies var context = new CookieValidateIdentityContext(Context, ticket, Options); - await Options.Provider.ValidateIdentity(context); + await Options.Notifications.ValidateIdentity(context); return new AuthenticationTicket(context.Identity, context.Properties); } @@ -131,7 +127,7 @@ namespace Microsoft.AspNet.Security.Cookies context.Properties.IssuedUtc = issuedUtc; context.Properties.ExpiresUtc = expiresUtc; - Options.Provider.ResponseSignIn(context); + Options.Notifications.ResponseSignIn(context); if (context.Properties.IsPersistent) { @@ -153,7 +149,7 @@ namespace Microsoft.AspNet.Security.Cookies Options, cookieOptions); - Options.Provider.ResponseSignOut(context); + Options.Notifications.ResponseSignOut(context); Response.Cookies.Delete( Options.CookieName, @@ -202,7 +198,7 @@ namespace Microsoft.AspNet.Security.Cookies && IsHostRelative(redirectUri)) { var redirectContext = new CookieApplyRedirectContext(Context, Options, redirectUri); - Options.Provider.ApplyRedirect(redirectContext); + Options.Notifications.ApplyRedirect(redirectContext); } } } @@ -242,7 +238,7 @@ namespace Microsoft.AspNet.Security.Cookies new QueryString(Options.ReturnUrlParameter, currentUri); var redirectContext = new CookieApplyRedirectContext(Context, Options, loginUri); - Options.Provider.ApplyRedirect(redirectContext); + Options.Notifications.ApplyRedirect(redirectContext); } } } diff --git a/src/Microsoft.AspNet.Security.Cookies/CookieAuthenticationMiddleware.cs b/src/Microsoft.AspNet.Security.Cookies/CookieAuthenticationMiddleware.cs index 0435a127ef..7b1919c910 100644 --- a/src/Microsoft.AspNet.Security.Cookies/CookieAuthenticationMiddleware.cs +++ b/src/Microsoft.AspNet.Security.Cookies/CookieAuthenticationMiddleware.cs @@ -13,22 +13,25 @@ namespace Microsoft.AspNet.Security.Cookies { private readonly ILogger _logger; - public CookieAuthenticationMiddleware(RequestDelegate next, ILogger logger, CookieAuthenticationOptions options) + public CookieAuthenticationMiddleware(RequestDelegate next, IDataProtectionProvider dataProtectionProvider, ILoggerFactory loggerFactory, CookieAuthenticationOptions options) : base(next, options) { - if (Options.Provider == null) + if (Options.Notifications == null) { - Options.Provider = new CookieAuthenticationProvider(); + Options.Notifications = new CookieAuthenticationNotifications(); } if (String.IsNullOrEmpty(Options.CookieName)) { Options.CookieName = CookieAuthenticationDefaults.CookiePrefix + Options.AuthenticationType; } - if (logger == null) + if (options.TicketDataFormat == null) { - throw new ArgumentNullException("logger"); + IDataProtector dataProtector = DataProtectionHelpers.CreateDataProtector(dataProtectionProvider, + typeof(CookieAuthenticationMiddleware).FullName, options.AuthenticationType, "v1"); + options.TicketDataFormat = new TicketDataFormat(dataProtector); } - _logger = logger; + + _logger = loggerFactory.Create(typeof(CookieAuthenticationMiddleware).FullName); } protected override AuthenticationHandler CreateHandler() diff --git a/src/Microsoft.AspNet.Security.Cookies/CookieAuthenticationOptions.cs b/src/Microsoft.AspNet.Security.Cookies/CookieAuthenticationOptions.cs index 389a611c33..e865ad68ee 100644 --- a/src/Microsoft.AspNet.Security.Cookies/CookieAuthenticationOptions.cs +++ b/src/Microsoft.AspNet.Security.Cookies/CookieAuthenticationOptions.cs @@ -27,7 +27,7 @@ namespace Microsoft.AspNet.Security.Cookies CookieHttpOnly = true; CookieSecure = CookieSecureOption.SameAsRequest; SystemClock = new SystemClock(); - Provider = new CookieAuthenticationProvider(); + Notifications = new CookieAuthenticationNotifications(); } /// @@ -118,7 +118,7 @@ namespace Microsoft.AspNet.Security.Cookies /// calls methods on the provider which give the application control at certain points where processing is occuring. /// If it is not provided a default instance is supplied which does nothing when the methods are called. /// - public ICookieAuthenticationProvider Provider { get; set; } + public ICookieAuthenticationNotifications Notifications { get; set; } /// /// The TicketDataFormat is used to protect and unprotect the identity and other properties which are stored in the diff --git a/src/Microsoft.AspNet.Security.Cookies/NotNullAttribute.cs b/src/Microsoft.AspNet.Security.Cookies/NotNullAttribute.cs new file mode 100644 index 0000000000..b3b1edcbdb --- /dev/null +++ b/src/Microsoft.AspNet.Security.Cookies/NotNullAttribute.cs @@ -0,0 +1,9 @@ +using System; + +namespace Microsoft.AspNet.Security.Cookies +{ + [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] + internal sealed class NotNullAttribute : Attribute + { + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Security.Cookies/Provider/CookieApplyRedirectContext.cs b/src/Microsoft.AspNet.Security.Cookies/Notifications/CookieApplyRedirectContext.cs similarity index 96% rename from src/Microsoft.AspNet.Security.Cookies/Provider/CookieApplyRedirectContext.cs rename to src/Microsoft.AspNet.Security.Cookies/Notifications/CookieApplyRedirectContext.cs index 69ccc0c386..14c96dbe09 100644 --- a/src/Microsoft.AspNet.Security.Cookies/Provider/CookieApplyRedirectContext.cs +++ b/src/Microsoft.AspNet.Security.Cookies/Notifications/CookieApplyRedirectContext.cs @@ -2,7 +2,7 @@ using System.Diagnostics.CodeAnalysis; using Microsoft.AspNet.Abstractions; -using Microsoft.AspNet.Security.Provider; +using Microsoft.AspNet.Security.Notifications; namespace Microsoft.AspNet.Security.Cookies { diff --git a/src/Microsoft.AspNet.Security.Cookies/Provider/CookieAuthenticationProvider.cs b/src/Microsoft.AspNet.Security.Cookies/Notifications/CookieAuthenticationNotifications.cs similarity index 92% rename from src/Microsoft.AspNet.Security.Cookies/Provider/CookieAuthenticationProvider.cs rename to src/Microsoft.AspNet.Security.Cookies/Notifications/CookieAuthenticationNotifications.cs index 6b434c0b2b..f3496bbc73 100644 --- a/src/Microsoft.AspNet.Security.Cookies/Provider/CookieAuthenticationProvider.cs +++ b/src/Microsoft.AspNet.Security.Cookies/Notifications/CookieAuthenticationNotifications.cs @@ -6,16 +6,16 @@ using System.Threading.Tasks; namespace Microsoft.AspNet.Security.Cookies { /// - /// This default implementation of the ICookieAuthenticationProvider may be used if the + /// This default implementation of the ICookieAuthenticationNotifications may be used if the /// application only needs to override a few of the interface methods. This may be used as a base class /// or may be instantiated directly. /// - public class CookieAuthenticationProvider : ICookieAuthenticationProvider + public class CookieAuthenticationNotifications : ICookieAuthenticationNotifications { /// - /// Create a new instance of the default provider. + /// Create a new instance of the default notifications. /// - public CookieAuthenticationProvider() + public CookieAuthenticationNotifications() { OnValidateIdentity = context => Task.FromResult(0); OnResponseSignIn = context => { }; diff --git a/src/Microsoft.AspNet.Security.Cookies/Provider/CookieResponseSignInContext.cs b/src/Microsoft.AspNet.Security.Cookies/Notifications/CookieResponseSignInContext.cs similarity index 98% rename from src/Microsoft.AspNet.Security.Cookies/Provider/CookieResponseSignInContext.cs rename to src/Microsoft.AspNet.Security.Cookies/Notifications/CookieResponseSignInContext.cs index e3098e3590..4fefed2d9c 100644 --- a/src/Microsoft.AspNet.Security.Cookies/Provider/CookieResponseSignInContext.cs +++ b/src/Microsoft.AspNet.Security.Cookies/Notifications/CookieResponseSignInContext.cs @@ -3,7 +3,7 @@ using System.Security.Claims; using Microsoft.AspNet.Abstractions; using Microsoft.AspNet.Abstractions.Security; -using Microsoft.AspNet.Security.Provider; +using Microsoft.AspNet.Security.Notifications; namespace Microsoft.AspNet.Security.Cookies { diff --git a/src/Microsoft.AspNet.Security.Cookies/Provider/CookieResponseSignOutContext.cs b/src/Microsoft.AspNet.Security.Cookies/Notifications/CookieResponseSignOutContext.cs similarity index 96% rename from src/Microsoft.AspNet.Security.Cookies/Provider/CookieResponseSignOutContext.cs rename to src/Microsoft.AspNet.Security.Cookies/Notifications/CookieResponseSignOutContext.cs index e17028982a..e7d808c35b 100644 --- a/src/Microsoft.AspNet.Security.Cookies/Provider/CookieResponseSignOutContext.cs +++ b/src/Microsoft.AspNet.Security.Cookies/Notifications/CookieResponseSignOutContext.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using Microsoft.AspNet.Abstractions; -using Microsoft.AspNet.Security.Provider; +using Microsoft.AspNet.Security.Notifications; namespace Microsoft.AspNet.Security.Cookies { diff --git a/src/Microsoft.AspNet.Security.Cookies/Provider/CookieValidateIdentityContext.cs b/src/Microsoft.AspNet.Security.Cookies/Notifications/CookieValidateIdentityContext.cs similarity index 88% rename from src/Microsoft.AspNet.Security.Cookies/Provider/CookieValidateIdentityContext.cs rename to src/Microsoft.AspNet.Security.Cookies/Notifications/CookieValidateIdentityContext.cs index 4487582209..e48facc5b2 100644 --- a/src/Microsoft.AspNet.Security.Cookies/Provider/CookieValidateIdentityContext.cs +++ b/src/Microsoft.AspNet.Security.Cookies/Notifications/CookieValidateIdentityContext.cs @@ -7,7 +7,7 @@ using Microsoft.AspNet.Abstractions; using Microsoft.AspNet.Abstractions.Security; using Microsoft.AspNet.HttpFeature.Security; using Microsoft.AspNet.Security.Infrastructure; -using Microsoft.AspNet.Security.Provider; +using Microsoft.AspNet.Security.Notifications; namespace Microsoft.AspNet.Security.Cookies { @@ -22,14 +22,9 @@ namespace Microsoft.AspNet.Security.Cookies /// /// Contains the initial values for identity and extra data /// - public CookieValidateIdentityContext(HttpContext context, AuthenticationTicket ticket, CookieAuthenticationOptions options) + public CookieValidateIdentityContext([NotNull] HttpContext context, [NotNull] AuthenticationTicket ticket, [NotNull] CookieAuthenticationOptions options) : base(context, options) { - if (ticket == null) - { - throw new ArgumentNullException("ticket"); - } - Identity = ticket.Identity; Properties = ticket.Properties; } diff --git a/src/Microsoft.AspNet.Security.Cookies/Provider/DefaultBehavior.cs b/src/Microsoft.AspNet.Security.Cookies/Notifications/DefaultBehavior.cs similarity index 100% rename from src/Microsoft.AspNet.Security.Cookies/Provider/DefaultBehavior.cs rename to src/Microsoft.AspNet.Security.Cookies/Notifications/DefaultBehavior.cs diff --git a/src/Microsoft.AspNet.Security.Cookies/Provider/ICookieAuthenticationProvider.cs b/src/Microsoft.AspNet.Security.Cookies/Notifications/ICookieAuthenticationNotifications.cs similarity index 97% rename from src/Microsoft.AspNet.Security.Cookies/Provider/ICookieAuthenticationProvider.cs rename to src/Microsoft.AspNet.Security.Cookies/Notifications/ICookieAuthenticationNotifications.cs index f33a22259f..c9c07d227b 100644 --- a/src/Microsoft.AspNet.Security.Cookies/Provider/ICookieAuthenticationProvider.cs +++ b/src/Microsoft.AspNet.Security.Cookies/Notifications/ICookieAuthenticationNotifications.cs @@ -7,7 +7,7 @@ namespace Microsoft.AspNet.Security.Cookies /// /// Specifies callback methods which the invokes to enable developer control over the authentication process. /> /// - public interface ICookieAuthenticationProvider + public interface ICookieAuthenticationNotifications { /// /// Called each time a request identity has been validated by the middleware. By implementing this method the diff --git a/src/Microsoft.AspNet.Security/AppBuilderSecurityExtensions.cs b/src/Microsoft.AspNet.Security/AppBuilderSecurityExtensions.cs index 36c0e04ee2..077cdbd53f 100644 --- a/src/Microsoft.AspNet.Security/AppBuilderSecurityExtensions.cs +++ b/src/Microsoft.AspNet.Security/AppBuilderSecurityExtensions.cs @@ -16,12 +16,8 @@ namespace Microsoft.AspNet.Security /// /// App builder passed to the application startup code /// - public static string GetDefaultSignInAsAuthenticationType(this IAppBuilder app) + public static string GetDefaultSignInAsAuthenticationType([NotNull] this IAppBuilder app) { - if (app == null) - { - throw new ArgumentNullException("app"); - } object value; if (app.Properties.TryGetValue(Constants.DefaultSignInAsAuthenticationType, out value)) { @@ -40,16 +36,8 @@ namespace Microsoft.AspNet.Security /// /// App builder passed to the application startup code /// AuthenticationType that external middleware should sign in as. - public static void SetDefaultSignInAsAuthenticationType(this IAppBuilder app, string authenticationType) + public static void SetDefaultSignInAsAuthenticationType([NotNull] this IAppBuilder app, [NotNull] string authenticationType) { - if (app == null) - { - throw new ArgumentNullException("app"); - } - if (authenticationType == null) - { - throw new ArgumentNullException("authenticationType"); - } app.Properties[Constants.DefaultSignInAsAuthenticationType] = authenticationType; } } diff --git a/src/Microsoft.AspNet.Security/CertificateSubjectKeyIdentifierValidator.cs b/src/Microsoft.AspNet.Security/CertificateSubjectKeyIdentifierValidator.cs index a549c3740d..d25bb72239 100644 --- a/src/Microsoft.AspNet.Security/CertificateSubjectKeyIdentifierValidator.cs +++ b/src/Microsoft.AspNet.Security/CertificateSubjectKeyIdentifierValidator.cs @@ -18,13 +18,8 @@ namespace Microsoft.AspNet.Security /// Initializes a new instance of the class. /// /// A set of subject key identifiers which are valid for an HTTPS request. - public CertificateSubjectKeyIdentifierValidator(IEnumerable validSubjectKeyIdentifiers) + public CertificateSubjectKeyIdentifierValidator([NotNull] IEnumerable validSubjectKeyIdentifiers) { - if (validSubjectKeyIdentifiers == null) - { - throw new ArgumentNullException("validSubjectKeyIdentifiers"); - } - _validSubjectKeyIdentifiers = new HashSet(validSubjectKeyIdentifiers, StringComparer.OrdinalIgnoreCase); if (_validSubjectKeyIdentifiers.Count == 0) @@ -41,18 +36,13 @@ namespace Microsoft.AspNet.Security /// The chain of certificate authorities associated with the remote certificate. /// One or more errors associated with the remote certificate. /// A Boolean value that determines whether the specified certificate is accepted for authentication. - public bool Validate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) + public bool Validate(object sender, X509Certificate certificate, [NotNull] X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors != SslPolicyErrors.None) { return false; } - if (chain == null) - { - throw new ArgumentNullException("chain"); - } - if (chain.ChainElements.Count < 2) { // Self signed. diff --git a/src/Microsoft.AspNet.Security/CertificateSubjectPublicKeyInfoValidator.cs b/src/Microsoft.AspNet.Security/CertificateSubjectPublicKeyInfoValidator.cs index 0896c72d97..79645c50de 100644 --- a/src/Microsoft.AspNet.Security/CertificateSubjectPublicKeyInfoValidator.cs +++ b/src/Microsoft.AspNet.Security/CertificateSubjectPublicKeyInfoValidator.cs @@ -27,13 +27,8 @@ namespace Microsoft.AspNet.Security /// /// A collection of valid base64 encoded hashes of the certificate public key information blob. /// The algorithm used to generate the hashes. - public CertificateSubjectPublicKeyInfoValidator(IEnumerable validBase64EncodedSubjectPublicKeyInfoHashes, SubjectPublicKeyInfoAlgorithm algorithm) + public CertificateSubjectPublicKeyInfoValidator([NotNull] IEnumerable validBase64EncodedSubjectPublicKeyInfoHashes, SubjectPublicKeyInfoAlgorithm algorithm) { - if (validBase64EncodedSubjectPublicKeyInfoHashes == null) - { - throw new ArgumentNullException("validBase64EncodedSubjectPublicKeyInfoHashes"); - } - _validBase64EncodedSubjectPublicKeyInfoHashes = new HashSet(validBase64EncodedSubjectPublicKeyInfoHashes); if (_validBase64EncodedSubjectPublicKeyInfoHashes.Count == 0) @@ -57,18 +52,13 @@ namespace Microsoft.AspNet.Security /// The chain of certificate authorities associated with the remote certificate. /// One or more errors associated with the remote certificate. /// A Boolean value that determines whether the specified certificate is accepted for authentication. - public bool Validate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) + public bool Validate(object sender, X509Certificate certificate, [NotNull] X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors != SslPolicyErrors.None) { return false; } - if (chain == null) - { - throw new ArgumentNullException("chain"); - } - if (chain.ChainElements.Count < 2) { return false; diff --git a/src/Microsoft.AspNet.Security/CertificateThumbprintValidator.cs b/src/Microsoft.AspNet.Security/CertificateThumbprintValidator.cs index 464d579011..5661d55915 100644 --- a/src/Microsoft.AspNet.Security/CertificateThumbprintValidator.cs +++ b/src/Microsoft.AspNet.Security/CertificateThumbprintValidator.cs @@ -18,13 +18,8 @@ namespace Microsoft.AspNet.Security /// Initializes a new instance of the class. /// /// A set of thumbprints which are valid for an HTTPS request. - public CertificateThumbprintValidator(IEnumerable validThumbprints) + public CertificateThumbprintValidator([NotNull] IEnumerable validThumbprints) { - if (validThumbprints == null) - { - throw new ArgumentNullException("validThumbprints"); - } - _validCertificateThumbprints = new HashSet(validThumbprints, StringComparer.OrdinalIgnoreCase); if (_validCertificateThumbprints.Count == 0) @@ -41,18 +36,13 @@ namespace Microsoft.AspNet.Security /// The chain of certificate authorities associated with the remote certificate. /// One or more errors associated with the remote certificate. /// A Boolean value that determines whether the specified certificate is accepted for authentication. - public bool Validate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) + public bool Validate(object sender, X509Certificate certificate, [NotNull] X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors != SslPolicyErrors.None) { return false; } - if (chain == null) - { - throw new ArgumentNullException("chain"); - } - if (chain.ChainElements.Count < 2) { // Self signed. diff --git a/src/Microsoft.AspNet.Security/DataHandler/Encoder/Base64UrlTextEncoder.cs b/src/Microsoft.AspNet.Security/DataHandler/Encoder/Base64UrlTextEncoder.cs index ca377ae65e..250ea7019c 100644 --- a/src/Microsoft.AspNet.Security/DataHandler/Encoder/Base64UrlTextEncoder.cs +++ b/src/Microsoft.AspNet.Security/DataHandler/Encoder/Base64UrlTextEncoder.cs @@ -6,23 +6,13 @@ namespace Microsoft.AspNet.Security.DataHandler.Encoder { public class Base64UrlTextEncoder : ITextEncoder { - public string Encode(byte[] data) + public string Encode([NotNull] byte[] data) { - if (data == null) - { - throw new ArgumentNullException("data"); - } - return Convert.ToBase64String(data).TrimEnd('=').Replace('+', '-').Replace('/', '_'); } - public byte[] Decode(string text) + public byte[] Decode([NotNull] string text) { - if (text == null) - { - throw new ArgumentNullException("text"); - } - return Convert.FromBase64String(Pad(text.Replace('-', '+').Replace('_', '/'))); } diff --git a/src/Microsoft.AspNet.Security/DataHandler/Serializer/PropertiesSerializer.cs b/src/Microsoft.AspNet.Security/DataHandler/Serializer/PropertiesSerializer.cs index 1ba7164059..0ea3a4ba30 100644 --- a/src/Microsoft.AspNet.Security/DataHandler/Serializer/PropertiesSerializer.cs +++ b/src/Microsoft.AspNet.Security/DataHandler/Serializer/PropertiesSerializer.cs @@ -38,17 +38,8 @@ namespace Microsoft.AspNet.Security.DataHandler.Serializer } } - public static void Write(BinaryWriter writer, AuthenticationProperties properties) + public static void Write([NotNull] BinaryWriter writer, [NotNull] AuthenticationProperties properties) { - if (writer == null) - { - throw new ArgumentNullException("writer"); - } - if (properties == null) - { - throw new ArgumentNullException("properties"); - } - writer.Write(FormatVersion); writer.Write(properties.Dictionary.Count); foreach (var kv in properties.Dictionary) @@ -58,13 +49,8 @@ namespace Microsoft.AspNet.Security.DataHandler.Serializer } } - public static AuthenticationProperties Read(BinaryReader reader) + public static AuthenticationProperties Read([NotNull] BinaryReader reader) { - if (reader == null) - { - throw new ArgumentNullException("reader"); - } - if (reader.ReadInt32() != FormatVersion) { return null; diff --git a/src/Microsoft.AspNet.Security/DataHandler/Serializer/TicketSerializer.cs b/src/Microsoft.AspNet.Security/DataHandler/Serializer/TicketSerializer.cs index de3abbd92e..70406d1d95 100644 --- a/src/Microsoft.AspNet.Security/DataHandler/Serializer/TicketSerializer.cs +++ b/src/Microsoft.AspNet.Security/DataHandler/Serializer/TicketSerializer.cs @@ -44,17 +44,8 @@ namespace Microsoft.AspNet.Security.DataHandler.Serializer } } - public static void Write(BinaryWriter writer, AuthenticationTicket model) + public static void Write([NotNull] BinaryWriter writer, [NotNull] AuthenticationTicket model) { - if (writer == null) - { - throw new ArgumentNullException("writer"); - } - if (model == null) - { - throw new ArgumentNullException("model"); - } - writer.Write(FormatVersion); ClaimsIdentity identity = model.Identity; writer.Write(identity.AuthenticationType); @@ -72,13 +63,8 @@ namespace Microsoft.AspNet.Security.DataHandler.Serializer PropertiesSerializer.Write(writer, model.Properties); } - public static AuthenticationTicket Read(BinaryReader reader) + public static AuthenticationTicket Read([NotNull] BinaryReader reader) { - if (reader == null) - { - throw new ArgumentNullException("reader"); - } - if (reader.ReadInt32() != FormatVersion) { return null; diff --git a/src/Microsoft.AspNet.Security/DataProtection/BuilderExtensions.cs b/src/Microsoft.AspNet.Security/DataProtection/DataProtectionHelpers.cs similarity index 57% rename from src/Microsoft.AspNet.Security/DataProtection/BuilderExtensions.cs rename to src/Microsoft.AspNet.Security/DataProtection/DataProtectionHelpers.cs index f441afdb78..8ed6c5db21 100644 --- a/src/Microsoft.AspNet.Security/DataProtection/BuilderExtensions.cs +++ b/src/Microsoft.AspNet.Security/DataProtection/DataProtectionHelpers.cs @@ -5,16 +5,10 @@ using Microsoft.AspNet.Abstractions; namespace Microsoft.AspNet.Security.DataProtection { - public static class BuilderExtensions + public static class DataProtectionHelpers { - public static IDataProtector CreateDataProtector(this IBuilder app, params string[] purposes) + public static IDataProtector CreateDataProtector(IDataProtectionProvider dataProtectionProvider, params string[] purposes) { - if (app == null) - { - throw new ArgumentNullException("app"); - } - - var dataProtectionProvider = (IDataProtectionProvider)app.ServiceProvider.GetService(typeof(IDataProtectionProvider)); if (dataProtectionProvider == null) { dataProtectionProvider = DataProtectionProvider.CreateFromDpapi(); diff --git a/src/Microsoft.AspNet.Security/Infrastructure/AuthenticationHandler.cs b/src/Microsoft.AspNet.Security/Infrastructure/AuthenticationHandler.cs index f27c4d41b6..5b7f1e2106 100644 --- a/src/Microsoft.AspNet.Security/Infrastructure/AuthenticationHandler.cs +++ b/src/Microsoft.AspNet.Security/Infrastructure/AuthenticationHandler.cs @@ -75,7 +75,7 @@ namespace Microsoft.AspNet.Security.Infrastructure AuthenticationTicket ticket = await AuthenticateAsync(); if (ticket != null && ticket.Identity != null) { - Context.AddUserIdentity(ticket.Identity); + SecurityHelper.AddUserIdentity(Context, ticket.Identity); } } } @@ -322,13 +322,8 @@ namespace Microsoft.AspNet.Security.Infrastructure return Task.FromResult(0); } - protected void GenerateCorrelationId(AuthenticationProperties properties) + protected void GenerateCorrelationId([NotNull] AuthenticationProperties properties) { - if (properties == null) - { - throw new ArgumentNullException("properties"); - } - string correlationKey = Constants.CorrelationPrefix + BaseOptions.AuthenticationType; var nonceBytes = new byte[32]; @@ -349,13 +344,8 @@ namespace Microsoft.AspNet.Security.Infrastructure [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Owin.Logging.LoggerExtensions.WriteWarning(Microsoft.Owin.Logging.ILogger,System.String,System.String[])", Justification = "Logging is not Localized")] - protected bool ValidateCorrelationId(AuthenticationProperties properties, ILogger logger) + protected bool ValidateCorrelationId([NotNull] AuthenticationProperties properties, [NotNull] ILogger logger) { - if (properties == null) - { - throw new ArgumentNullException("properties"); - } - string correlationKey = Constants.CorrelationPrefix + BaseOptions.AuthenticationType; string correlationCookie = Request.Cookies[correlationKey]; diff --git a/src/Microsoft.AspNet.Security/Infrastructure/AuthenticationMiddleware.cs b/src/Microsoft.AspNet.Security/Infrastructure/AuthenticationMiddleware.cs index c50afdc3c7..f4fecd5231 100644 --- a/src/Microsoft.AspNet.Security/Infrastructure/AuthenticationMiddleware.cs +++ b/src/Microsoft.AspNet.Security/Infrastructure/AuthenticationMiddleware.cs @@ -10,13 +10,8 @@ namespace Microsoft.AspNet.Security.Infrastructure { private readonly RequestDelegate _next; - protected AuthenticationMiddleware(RequestDelegate next, TOptions options) + protected AuthenticationMiddleware([NotNull] RequestDelegate next, [NotNull] TOptions options) { - if (options == null) - { - throw new ArgumentNullException("options"); - } - Options = options; _next = next; } diff --git a/src/Microsoft.AspNet.Security/Infrastructure/AuthenticationTokenCreateContext.cs b/src/Microsoft.AspNet.Security/Infrastructure/AuthenticationTokenCreateContext.cs index 228e01e1e5..e418a113fe 100644 --- a/src/Microsoft.AspNet.Security/Infrastructure/AuthenticationTokenCreateContext.cs +++ b/src/Microsoft.AspNet.Security/Infrastructure/AuthenticationTokenCreateContext.cs @@ -2,7 +2,7 @@ using System; using Microsoft.AspNet.Abstractions; -using Microsoft.AspNet.Security.Provider; +using Microsoft.AspNet.Security.Notifications; namespace Microsoft.AspNet.Security.Infrastructure { @@ -11,19 +11,11 @@ namespace Microsoft.AspNet.Security.Infrastructure private readonly ISecureDataFormat _secureDataFormat; public AuthenticationTokenCreateContext( - HttpContext context, - ISecureDataFormat secureDataFormat, - AuthenticationTicket ticket) + [NotNull] HttpContext context, + [NotNull] ISecureDataFormat secureDataFormat, + [NotNull] AuthenticationTicket ticket) : base(context) { - if (secureDataFormat == null) - { - throw new ArgumentNullException("secureDataFormat"); - } - if (ticket == null) - { - throw new ArgumentNullException("ticket"); - } _secureDataFormat = secureDataFormat; Ticket = ticket; } @@ -37,12 +29,8 @@ namespace Microsoft.AspNet.Security.Infrastructure return _secureDataFormat.Protect(Ticket); } - public void SetToken(string tokenValue) + public void SetToken([NotNull] string tokenValue) { - if (tokenValue == null) - { - throw new ArgumentNullException("tokenValue"); - } Token = tokenValue; } } diff --git a/src/Microsoft.AspNet.Security/Infrastructure/AuthenticationTokenReceiveContext.cs b/src/Microsoft.AspNet.Security/Infrastructure/AuthenticationTokenReceiveContext.cs index ccbc81f020..7e4f840277 100644 --- a/src/Microsoft.AspNet.Security/Infrastructure/AuthenticationTokenReceiveContext.cs +++ b/src/Microsoft.AspNet.Security/Infrastructure/AuthenticationTokenReceiveContext.cs @@ -2,7 +2,7 @@ using System; using Microsoft.AspNet.Abstractions; -using Microsoft.AspNet.Security.Provider; +using Microsoft.AspNet.Security.Notifications; namespace Microsoft.AspNet.Security.Infrastructure { @@ -11,18 +11,11 @@ namespace Microsoft.AspNet.Security.Infrastructure private readonly ISecureDataFormat _secureDataFormat; public AuthenticationTokenReceiveContext( - HttpContext context, - ISecureDataFormat secureDataFormat, - string token) : base(context) + [NotNull] HttpContext context, + [NotNull] ISecureDataFormat secureDataFormat, + [NotNull] string token) + : base(context) { - if (secureDataFormat == null) - { - throw new ArgumentNullException("secureDataFormat"); - } - if (token == null) - { - throw new ArgumentNullException("token"); - } _secureDataFormat = secureDataFormat; Token = token; } @@ -36,12 +29,8 @@ namespace Microsoft.AspNet.Security.Infrastructure Ticket = _secureDataFormat.Unprotect(protectedData); } - public void SetTicket(AuthenticationTicket ticket) + public void SetTicket([NotNull] AuthenticationTicket ticket) { - if (ticket == null) - { - throw new ArgumentNullException("ticket"); - } Ticket = ticket; } } diff --git a/src/Microsoft.AspNet.Security/Infrastructure/NotNullAttribute.cs b/src/Microsoft.AspNet.Security/Infrastructure/NotNullAttribute.cs new file mode 100644 index 0000000000..131cec58eb --- /dev/null +++ b/src/Microsoft.AspNet.Security/Infrastructure/NotNullAttribute.cs @@ -0,0 +1,9 @@ +using System; + +namespace Microsoft.AspNet.Security +{ + [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] + internal sealed class NotNullAttribute : Attribute + { + } +} \ No newline at end of file diff --git a/src/Microsoft.AspNet.Security/Infrastructure/SecurityHelper.cs b/src/Microsoft.AspNet.Security/Infrastructure/SecurityHelper.cs index 0337c4f481..a4e42b92d8 100644 --- a/src/Microsoft.AspNet.Security/Infrastructure/SecurityHelper.cs +++ b/src/Microsoft.AspNet.Security/Infrastructure/SecurityHelper.cs @@ -18,12 +18,8 @@ namespace Microsoft.AspNet.Security.Infrastructure /// Add an additional ClaimsIdentity to the ClaimsPrincipal /// /// - public static void AddUserIdentity(this HttpContext context, IIdentity identity) + public static void AddUserIdentity([NotNull] HttpContext context, [NotNull] IIdentity identity) { - if (identity == null) - { - throw new ArgumentNullException("identity"); - } var newClaimsPrincipal = new ClaimsPrincipal(identity); ClaimsPrincipal existingPrincipal = context.User; diff --git a/src/Microsoft.AspNet.Security/Provider/BaseContext.cs b/src/Microsoft.AspNet.Security/Notifications/BaseContext.cs similarity index 92% rename from src/Microsoft.AspNet.Security/Provider/BaseContext.cs rename to src/Microsoft.AspNet.Security/Notifications/BaseContext.cs index c73dbf6b36..57b50ed364 100644 --- a/src/Microsoft.AspNet.Security/Provider/BaseContext.cs +++ b/src/Microsoft.AspNet.Security/Notifications/BaseContext.cs @@ -2,7 +2,7 @@ using Microsoft.AspNet.Abstractions; -namespace Microsoft.AspNet.Security.Provider +namespace Microsoft.AspNet.Security.Notifications { public abstract class BaseContext { diff --git a/src/Microsoft.AspNet.Security/Provider/BaseContext`1.cs b/src/Microsoft.AspNet.Security/Notifications/BaseContext`1.cs similarity index 94% rename from src/Microsoft.AspNet.Security/Provider/BaseContext`1.cs rename to src/Microsoft.AspNet.Security/Notifications/BaseContext`1.cs index 2fd3c8ae22..be656e4c24 100644 --- a/src/Microsoft.AspNet.Security/Provider/BaseContext`1.cs +++ b/src/Microsoft.AspNet.Security/Notifications/BaseContext`1.cs @@ -2,7 +2,7 @@ using Microsoft.AspNet.Abstractions; -namespace Microsoft.AspNet.Security.Provider +namespace Microsoft.AspNet.Security.Notifications { /// /// Base class used for certain event contexts diff --git a/src/Microsoft.AspNet.Security/Provider/EndpointContext.cs b/src/Microsoft.AspNet.Security/Notifications/EndpointContext.cs similarity index 91% rename from src/Microsoft.AspNet.Security/Provider/EndpointContext.cs rename to src/Microsoft.AspNet.Security/Notifications/EndpointContext.cs index e210296b9f..58c175326e 100644 --- a/src/Microsoft.AspNet.Security/Provider/EndpointContext.cs +++ b/src/Microsoft.AspNet.Security/Notifications/EndpointContext.cs @@ -2,7 +2,7 @@ using Microsoft.AspNet.Abstractions; -namespace Microsoft.AspNet.Security.Provider +namespace Microsoft.AspNet.Security.Notifications { public abstract class EndpointContext : BaseContext { diff --git a/src/Microsoft.AspNet.Security/Provider/EndpointContext`1.cs b/src/Microsoft.AspNet.Security/Notifications/EndpointContext`1.cs similarity index 95% rename from src/Microsoft.AspNet.Security/Provider/EndpointContext`1.cs rename to src/Microsoft.AspNet.Security/Notifications/EndpointContext`1.cs index e3dd6997cd..15c7a64780 100644 --- a/src/Microsoft.AspNet.Security/Provider/EndpointContext`1.cs +++ b/src/Microsoft.AspNet.Security/Notifications/EndpointContext`1.cs @@ -2,7 +2,7 @@ using Microsoft.AspNet.Abstractions; -namespace Microsoft.AspNet.Security.Provider +namespace Microsoft.AspNet.Security.Notifications { /// /// Base class used for certain event contexts diff --git a/src/Microsoft.AspNet.Security/Provider/ReturnEndpointContext.cs b/src/Microsoft.AspNet.Security/Notifications/ReturnEndpointContext.cs similarity index 95% rename from src/Microsoft.AspNet.Security/Provider/ReturnEndpointContext.cs rename to src/Microsoft.AspNet.Security/Notifications/ReturnEndpointContext.cs index 13e712eb9f..ce1f309a11 100644 --- a/src/Microsoft.AspNet.Security/Provider/ReturnEndpointContext.cs +++ b/src/Microsoft.AspNet.Security/Notifications/ReturnEndpointContext.cs @@ -5,7 +5,7 @@ using System.Security.Claims; using Microsoft.AspNet.Abstractions; using Microsoft.AspNet.Abstractions.Security; -namespace Microsoft.AspNet.Security.Provider +namespace Microsoft.AspNet.Security.Notifications { public abstract class ReturnEndpointContext : EndpointContext {