Review cleanup, rename Provider to Notifications, use NotNull.

This commit is contained in:
Chris Ross 2014-04-08 11:28:08 -07:00
parent d83d2e98d6
commit 551fca35d3
33 changed files with 116 additions and 241 deletions

View File

@ -1,13 +1,11 @@
using System; using System;
using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using Microsoft.AspNet; using Microsoft.AspNet;
using Microsoft.AspNet.Abstractions; using Microsoft.AspNet.Abstractions;
using Microsoft.AspNet.Abstractions.Security; using Microsoft.AspNet.DependencyInjection;
using Microsoft.AspNet.HttpFeature.Security; using Microsoft.AspNet.DependencyInjection.Fallback;
using Microsoft.AspNet.Security; using Microsoft.AspNet.Logging;
using Microsoft.AspNet.Security.Cookies; using Microsoft.AspNet.Security.Cookies;
using Microsoft.AspNet.Security.Infrastructure;
namespace CookieSample namespace CookieSample
{ {
@ -15,6 +13,11 @@ namespace CookieSample
{ {
public void Configuration(IBuilder app) public void Configuration(IBuilder app)
{ {
// TODO: Move to host.
var serviceCollection = new ServiceCollection();
serviceCollection.AddInstance<ILoggerFactory>(new NullLoggerFactory());
app.ServiceProvider = serviceCollection.BuildServiceProvider(app.ServiceProvider);
app.UseCookieAuthentication(new CookieAuthenticationOptions() app.UseCookieAuthentication(new CookieAuthenticationOptions()
{ {
@ -35,5 +38,23 @@ namespace CookieSample
await context.Response.WriteAsync("Hello old timer"); 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<object, Exception, string> formatter)
{
return false;
}
}
} }
} }

View File

@ -2,6 +2,7 @@
"version": "0.1-alpha-*", "version": "0.1-alpha-*",
"dependencies": { "dependencies": {
"Microsoft.AspNet.Abstractions": "0.1-alpha-*", "Microsoft.AspNet.Abstractions": "0.1-alpha-*",
"Microsoft.AspNet.DependencyInjection": "0.1-alpha-*",
"Microsoft.AspNet.Security": "", "Microsoft.AspNet.Security": "",
"Microsoft.AspNet.Security.Cookies": "", "Microsoft.AspNet.Security.Cookies": "",
"Microsoft.AspNet.Hosting": "0.1-alpha-*", "Microsoft.AspNet.Hosting": "0.1-alpha-*",
@ -9,6 +10,7 @@
"Microsoft.AspNet.Abstractions": "0.1-alpha-*", "Microsoft.AspNet.Abstractions": "0.1-alpha-*",
"Microsoft.AspNet.FeatureModel": "0.1-alpha-*", "Microsoft.AspNet.FeatureModel": "0.1-alpha-*",
"Microsoft.AspNet.HttpFeature": "0.1-alpha-*", "Microsoft.AspNet.HttpFeature": "0.1-alpha-*",
"Microsoft.AspNet.Logging": "0.1-alpha-*",
"Microsoft.AspNet.Server.WebListener": "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" }, "commands": { "web": "Microsoft.AspNet.Hosting server.name=Microsoft.AspNet.Server.WebListener server.urls=http://localhost:12345" },

View File

@ -1,10 +1,9 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. // 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.Abstractions;
using Microsoft.AspNet.DependencyInjection;
using Microsoft.AspNet.Logging; using Microsoft.AspNet.Logging;
using Microsoft.AspNet.Security.Cookies; using Microsoft.AspNet.Security.Cookies;
using Microsoft.AspNet.Security.DataHandler;
using Microsoft.AspNet.Security.DataProtection; using Microsoft.AspNet.Security.DataProtection;
namespace Microsoft.AspNet namespace Microsoft.AspNet
@ -20,43 +19,12 @@ namespace Microsoft.AspNet
/// <param name="app">The IAppBuilder passed to your configuration method</param> /// <param name="app">The IAppBuilder passed to your configuration method</param>
/// <param name="options">An options class that controls the middleware behavior</param> /// <param name="options">An options class that controls the middleware behavior</param>
/// <returns>The original app parameter</returns> /// <returns>The original app parameter</returns>
public static IBuilder UseCookieAuthentication(this IBuilder app, CookieAuthenticationOptions options) public static IBuilder UseCookieAuthentication([NotNull] this IBuilder app, [NotNull] CookieAuthenticationOptions options)
{ {
if (app == null) // TODO: Use UseMiddleware to inject dependencies once it can discover Invoke from a base class.
{ var dataProtectionProvider = app.ServiceProvider.GetService<IDataProtectionProvider>();
throw new ArgumentNullException("app"); var loggerFactory = app.ServiceProvider.GetService<ILoggerFactory>();
} return app.Use(next => new CookieAuthenticationMiddleware(next, dataProtectionProvider, loggerFactory, options).Invoke);
// 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<object, Exception, string> formatter)
{
return false;
}
} }
} }
} }

View File

@ -25,12 +25,8 @@ namespace Microsoft.AspNet.Security.Cookies
private DateTimeOffset _renewIssuedUtc; private DateTimeOffset _renewIssuedUtc;
private DateTimeOffset _renewExpiresUtc; private DateTimeOffset _renewExpiresUtc;
public CookieAuthenticationHandler(ILogger logger) public CookieAuthenticationHandler([NotNull] ILogger logger)
{ {
if (logger == null)
{
throw new ArgumentNullException("logger");
}
_logger = logger; _logger = logger;
} }
@ -81,7 +77,7 @@ namespace Microsoft.AspNet.Security.Cookies
var context = new CookieValidateIdentityContext(Context, ticket, Options); var context = new CookieValidateIdentityContext(Context, ticket, Options);
await Options.Provider.ValidateIdentity(context); await Options.Notifications.ValidateIdentity(context);
return new AuthenticationTicket(context.Identity, context.Properties); return new AuthenticationTicket(context.Identity, context.Properties);
} }
@ -131,7 +127,7 @@ namespace Microsoft.AspNet.Security.Cookies
context.Properties.IssuedUtc = issuedUtc; context.Properties.IssuedUtc = issuedUtc;
context.Properties.ExpiresUtc = expiresUtc; context.Properties.ExpiresUtc = expiresUtc;
Options.Provider.ResponseSignIn(context); Options.Notifications.ResponseSignIn(context);
if (context.Properties.IsPersistent) if (context.Properties.IsPersistent)
{ {
@ -153,7 +149,7 @@ namespace Microsoft.AspNet.Security.Cookies
Options, Options,
cookieOptions); cookieOptions);
Options.Provider.ResponseSignOut(context); Options.Notifications.ResponseSignOut(context);
Response.Cookies.Delete( Response.Cookies.Delete(
Options.CookieName, Options.CookieName,
@ -202,7 +198,7 @@ namespace Microsoft.AspNet.Security.Cookies
&& IsHostRelative(redirectUri)) && IsHostRelative(redirectUri))
{ {
var redirectContext = new CookieApplyRedirectContext(Context, Options, 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); new QueryString(Options.ReturnUrlParameter, currentUri);
var redirectContext = new CookieApplyRedirectContext(Context, Options, loginUri); var redirectContext = new CookieApplyRedirectContext(Context, Options, loginUri);
Options.Provider.ApplyRedirect(redirectContext); Options.Notifications.ApplyRedirect(redirectContext);
} }
} }
} }

View File

@ -13,22 +13,25 @@ namespace Microsoft.AspNet.Security.Cookies
{ {
private readonly ILogger _logger; 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) : base(next, options)
{ {
if (Options.Provider == null) if (Options.Notifications == null)
{ {
Options.Provider = new CookieAuthenticationProvider(); Options.Notifications = new CookieAuthenticationNotifications();
} }
if (String.IsNullOrEmpty(Options.CookieName)) if (String.IsNullOrEmpty(Options.CookieName))
{ {
Options.CookieName = CookieAuthenticationDefaults.CookiePrefix + Options.AuthenticationType; 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<CookieAuthenticationOptions> CreateHandler() protected override AuthenticationHandler<CookieAuthenticationOptions> CreateHandler()

View File

@ -27,7 +27,7 @@ namespace Microsoft.AspNet.Security.Cookies
CookieHttpOnly = true; CookieHttpOnly = true;
CookieSecure = CookieSecureOption.SameAsRequest; CookieSecure = CookieSecureOption.SameAsRequest;
SystemClock = new SystemClock(); SystemClock = new SystemClock();
Provider = new CookieAuthenticationProvider(); Notifications = new CookieAuthenticationNotifications();
} }
/// <summary> /// <summary>
@ -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. /// 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. /// If it is not provided a default instance is supplied which does nothing when the methods are called.
/// </summary> /// </summary>
public ICookieAuthenticationProvider Provider { get; set; } public ICookieAuthenticationNotifications Notifications { get; set; }
/// <summary> /// <summary>
/// The TicketDataFormat is used to protect and unprotect the identity and other properties which are stored in the /// The TicketDataFormat is used to protect and unprotect the identity and other properties which are stored in the

View File

@ -0,0 +1,9 @@
using System;
namespace Microsoft.AspNet.Security.Cookies
{
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
internal sealed class NotNullAttribute : Attribute
{
}
}

View File

@ -2,7 +2,7 @@
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNet.Abstractions; using Microsoft.AspNet.Abstractions;
using Microsoft.AspNet.Security.Provider; using Microsoft.AspNet.Security.Notifications;
namespace Microsoft.AspNet.Security.Cookies namespace Microsoft.AspNet.Security.Cookies
{ {

View File

@ -6,16 +6,16 @@ using System.Threading.Tasks;
namespace Microsoft.AspNet.Security.Cookies namespace Microsoft.AspNet.Security.Cookies
{ {
/// <summary> /// <summary>
/// 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 /// application only needs to override a few of the interface methods. This may be used as a base class
/// or may be instantiated directly. /// or may be instantiated directly.
/// </summary> /// </summary>
public class CookieAuthenticationProvider : ICookieAuthenticationProvider public class CookieAuthenticationNotifications : ICookieAuthenticationNotifications
{ {
/// <summary> /// <summary>
/// Create a new instance of the default provider. /// Create a new instance of the default notifications.
/// </summary> /// </summary>
public CookieAuthenticationProvider() public CookieAuthenticationNotifications()
{ {
OnValidateIdentity = context => Task.FromResult(0); OnValidateIdentity = context => Task.FromResult(0);
OnResponseSignIn = context => { }; OnResponseSignIn = context => { };

View File

@ -3,7 +3,7 @@
using System.Security.Claims; using System.Security.Claims;
using Microsoft.AspNet.Abstractions; using Microsoft.AspNet.Abstractions;
using Microsoft.AspNet.Abstractions.Security; using Microsoft.AspNet.Abstractions.Security;
using Microsoft.AspNet.Security.Provider; using Microsoft.AspNet.Security.Notifications;
namespace Microsoft.AspNet.Security.Cookies namespace Microsoft.AspNet.Security.Cookies
{ {

View File

@ -1,7 +1,7 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. // 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.Abstractions;
using Microsoft.AspNet.Security.Provider; using Microsoft.AspNet.Security.Notifications;
namespace Microsoft.AspNet.Security.Cookies namespace Microsoft.AspNet.Security.Cookies
{ {

View File

@ -7,7 +7,7 @@ using Microsoft.AspNet.Abstractions;
using Microsoft.AspNet.Abstractions.Security; using Microsoft.AspNet.Abstractions.Security;
using Microsoft.AspNet.HttpFeature.Security; using Microsoft.AspNet.HttpFeature.Security;
using Microsoft.AspNet.Security.Infrastructure; using Microsoft.AspNet.Security.Infrastructure;
using Microsoft.AspNet.Security.Provider; using Microsoft.AspNet.Security.Notifications;
namespace Microsoft.AspNet.Security.Cookies namespace Microsoft.AspNet.Security.Cookies
{ {
@ -22,14 +22,9 @@ namespace Microsoft.AspNet.Security.Cookies
/// <param name="context"></param> /// <param name="context"></param>
/// <param name="ticket">Contains the initial values for identity and extra data</param> /// <param name="ticket">Contains the initial values for identity and extra data</param>
/// <param name="options"></param> /// <param name="options"></param>
public CookieValidateIdentityContext(HttpContext context, AuthenticationTicket ticket, CookieAuthenticationOptions options) public CookieValidateIdentityContext([NotNull] HttpContext context, [NotNull] AuthenticationTicket ticket, [NotNull] CookieAuthenticationOptions options)
: base(context, options) : base(context, options)
{ {
if (ticket == null)
{
throw new ArgumentNullException("ticket");
}
Identity = ticket.Identity; Identity = ticket.Identity;
Properties = ticket.Properties; Properties = ticket.Properties;
} }

View File

@ -7,7 +7,7 @@ namespace Microsoft.AspNet.Security.Cookies
/// <summary> /// <summary>
/// Specifies callback methods which the <see cref="CookieAuthenticationMiddleware"></see> invokes to enable developer control over the authentication process. /> /// Specifies callback methods which the <see cref="CookieAuthenticationMiddleware"></see> invokes to enable developer control over the authentication process. />
/// </summary> /// </summary>
public interface ICookieAuthenticationProvider public interface ICookieAuthenticationNotifications
{ {
/// <summary> /// <summary>
/// Called each time a request identity has been validated by the middleware. By implementing this method the /// Called each time a request identity has been validated by the middleware. By implementing this method the

View File

@ -16,12 +16,8 @@ namespace Microsoft.AspNet.Security
/// </summary> /// </summary>
/// <param name="app">App builder passed to the application startup code</param> /// <param name="app">App builder passed to the application startup code</param>
/// <returns></returns> /// <returns></returns>
public static string GetDefaultSignInAsAuthenticationType(this IAppBuilder app) public static string GetDefaultSignInAsAuthenticationType([NotNull] this IAppBuilder app)
{ {
if (app == null)
{
throw new ArgumentNullException("app");
}
object value; object value;
if (app.Properties.TryGetValue(Constants.DefaultSignInAsAuthenticationType, out value)) if (app.Properties.TryGetValue(Constants.DefaultSignInAsAuthenticationType, out value))
{ {
@ -40,16 +36,8 @@ namespace Microsoft.AspNet.Security
/// </summary> /// </summary>
/// <param name="app">App builder passed to the application startup code</param> /// <param name="app">App builder passed to the application startup code</param>
/// <param name="authenticationType">AuthenticationType that external middleware should sign in as.</param> /// <param name="authenticationType">AuthenticationType that external middleware should sign in as.</param>
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; app.Properties[Constants.DefaultSignInAsAuthenticationType] = authenticationType;
} }
} }

View File

@ -18,13 +18,8 @@ namespace Microsoft.AspNet.Security
/// Initializes a new instance of the <see cref="CertificateSubjectKeyIdentifierValidator"/> class. /// Initializes a new instance of the <see cref="CertificateSubjectKeyIdentifierValidator"/> class.
/// </summary> /// </summary>
/// <param name="validSubjectKeyIdentifiers">A set of subject key identifiers which are valid for an HTTPS request.</param> /// <param name="validSubjectKeyIdentifiers">A set of subject key identifiers which are valid for an HTTPS request.</param>
public CertificateSubjectKeyIdentifierValidator(IEnumerable<string> validSubjectKeyIdentifiers) public CertificateSubjectKeyIdentifierValidator([NotNull] IEnumerable<string> validSubjectKeyIdentifiers)
{ {
if (validSubjectKeyIdentifiers == null)
{
throw new ArgumentNullException("validSubjectKeyIdentifiers");
}
_validSubjectKeyIdentifiers = new HashSet<string>(validSubjectKeyIdentifiers, StringComparer.OrdinalIgnoreCase); _validSubjectKeyIdentifiers = new HashSet<string>(validSubjectKeyIdentifiers, StringComparer.OrdinalIgnoreCase);
if (_validSubjectKeyIdentifiers.Count == 0) if (_validSubjectKeyIdentifiers.Count == 0)
@ -41,18 +36,13 @@ namespace Microsoft.AspNet.Security
/// <param name="chain">The chain of certificate authorities associated with the remote certificate.</param> /// <param name="chain">The chain of certificate authorities associated with the remote certificate.</param>
/// <param name="sslPolicyErrors">One or more errors associated with the remote certificate.</param> /// <param name="sslPolicyErrors">One or more errors associated with the remote certificate.</param>
/// <returns>A Boolean value that determines whether the specified certificate is accepted for authentication.</returns> /// <returns>A Boolean value that determines whether the specified certificate is accepted for authentication.</returns>
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) if (sslPolicyErrors != SslPolicyErrors.None)
{ {
return false; return false;
} }
if (chain == null)
{
throw new ArgumentNullException("chain");
}
if (chain.ChainElements.Count < 2) if (chain.ChainElements.Count < 2)
{ {
// Self signed. // Self signed.

View File

@ -27,13 +27,8 @@ namespace Microsoft.AspNet.Security
/// </summary> /// </summary>
/// <param name="validBase64EncodedSubjectPublicKeyInfoHashes">A collection of valid base64 encoded hashes of the certificate public key information blob.</param> /// <param name="validBase64EncodedSubjectPublicKeyInfoHashes">A collection of valid base64 encoded hashes of the certificate public key information blob.</param>
/// <param name="algorithm">The algorithm used to generate the hashes.</param> /// <param name="algorithm">The algorithm used to generate the hashes.</param>
public CertificateSubjectPublicKeyInfoValidator(IEnumerable<string> validBase64EncodedSubjectPublicKeyInfoHashes, SubjectPublicKeyInfoAlgorithm algorithm) public CertificateSubjectPublicKeyInfoValidator([NotNull] IEnumerable<string> validBase64EncodedSubjectPublicKeyInfoHashes, SubjectPublicKeyInfoAlgorithm algorithm)
{ {
if (validBase64EncodedSubjectPublicKeyInfoHashes == null)
{
throw new ArgumentNullException("validBase64EncodedSubjectPublicKeyInfoHashes");
}
_validBase64EncodedSubjectPublicKeyInfoHashes = new HashSet<string>(validBase64EncodedSubjectPublicKeyInfoHashes); _validBase64EncodedSubjectPublicKeyInfoHashes = new HashSet<string>(validBase64EncodedSubjectPublicKeyInfoHashes);
if (_validBase64EncodedSubjectPublicKeyInfoHashes.Count == 0) if (_validBase64EncodedSubjectPublicKeyInfoHashes.Count == 0)
@ -57,18 +52,13 @@ namespace Microsoft.AspNet.Security
/// <param name="chain">The chain of certificate authorities associated with the remote certificate.</param> /// <param name="chain">The chain of certificate authorities associated with the remote certificate.</param>
/// <param name="sslPolicyErrors">One or more errors associated with the remote certificate.</param> /// <param name="sslPolicyErrors">One or more errors associated with the remote certificate.</param>
/// <returns>A Boolean value that determines whether the specified certificate is accepted for authentication.</returns> /// <returns>A Boolean value that determines whether the specified certificate is accepted for authentication.</returns>
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) if (sslPolicyErrors != SslPolicyErrors.None)
{ {
return false; return false;
} }
if (chain == null)
{
throw new ArgumentNullException("chain");
}
if (chain.ChainElements.Count < 2) if (chain.ChainElements.Count < 2)
{ {
return false; return false;

View File

@ -18,13 +18,8 @@ namespace Microsoft.AspNet.Security
/// Initializes a new instance of the <see cref="CertificateThumbprintValidator"/> class. /// Initializes a new instance of the <see cref="CertificateThumbprintValidator"/> class.
/// </summary> /// </summary>
/// <param name="validThumbprints">A set of thumbprints which are valid for an HTTPS request.</param> /// <param name="validThumbprints">A set of thumbprints which are valid for an HTTPS request.</param>
public CertificateThumbprintValidator(IEnumerable<string> validThumbprints) public CertificateThumbprintValidator([NotNull] IEnumerable<string> validThumbprints)
{ {
if (validThumbprints == null)
{
throw new ArgumentNullException("validThumbprints");
}
_validCertificateThumbprints = new HashSet<string>(validThumbprints, StringComparer.OrdinalIgnoreCase); _validCertificateThumbprints = new HashSet<string>(validThumbprints, StringComparer.OrdinalIgnoreCase);
if (_validCertificateThumbprints.Count == 0) if (_validCertificateThumbprints.Count == 0)
@ -41,18 +36,13 @@ namespace Microsoft.AspNet.Security
/// <param name="chain">The chain of certificate authorities associated with the remote certificate.</param> /// <param name="chain">The chain of certificate authorities associated with the remote certificate.</param>
/// <param name="sslPolicyErrors">One or more errors associated with the remote certificate.</param> /// <param name="sslPolicyErrors">One or more errors associated with the remote certificate.</param>
/// <returns>A Boolean value that determines whether the specified certificate is accepted for authentication.</returns> /// <returns>A Boolean value that determines whether the specified certificate is accepted for authentication.</returns>
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) if (sslPolicyErrors != SslPolicyErrors.None)
{ {
return false; return false;
} }
if (chain == null)
{
throw new ArgumentNullException("chain");
}
if (chain.ChainElements.Count < 2) if (chain.ChainElements.Count < 2)
{ {
// Self signed. // Self signed.

View File

@ -6,23 +6,13 @@ namespace Microsoft.AspNet.Security.DataHandler.Encoder
{ {
public class Base64UrlTextEncoder : ITextEncoder 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('/', '_'); 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('_', '/'))); return Convert.FromBase64String(Pad(text.Replace('-', '+').Replace('_', '/')));
} }

View File

@ -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(FormatVersion);
writer.Write(properties.Dictionary.Count); writer.Write(properties.Dictionary.Count);
foreach (var kv in properties.Dictionary) 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) if (reader.ReadInt32() != FormatVersion)
{ {
return null; return null;

View File

@ -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); writer.Write(FormatVersion);
ClaimsIdentity identity = model.Identity; ClaimsIdentity identity = model.Identity;
writer.Write(identity.AuthenticationType); writer.Write(identity.AuthenticationType);
@ -72,13 +63,8 @@ namespace Microsoft.AspNet.Security.DataHandler.Serializer
PropertiesSerializer.Write(writer, model.Properties); 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) if (reader.ReadInt32() != FormatVersion)
{ {
return null; return null;

View File

@ -5,16 +5,10 @@ using Microsoft.AspNet.Abstractions;
namespace Microsoft.AspNet.Security.DataProtection 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) if (dataProtectionProvider == null)
{ {
dataProtectionProvider = DataProtectionProvider.CreateFromDpapi(); dataProtectionProvider = DataProtectionProvider.CreateFromDpapi();

View File

@ -75,7 +75,7 @@ namespace Microsoft.AspNet.Security.Infrastructure
AuthenticationTicket ticket = await AuthenticateAsync(); AuthenticationTicket ticket = await AuthenticateAsync();
if (ticket != null && ticket.Identity != null) 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); 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; string correlationKey = Constants.CorrelationPrefix + BaseOptions.AuthenticationType;
var nonceBytes = new byte[32]; 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", [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[])", MessageId = "Microsoft.Owin.Logging.LoggerExtensions.WriteWarning(Microsoft.Owin.Logging.ILogger,System.String,System.String[])",
Justification = "Logging is not Localized")] 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 correlationKey = Constants.CorrelationPrefix + BaseOptions.AuthenticationType;
string correlationCookie = Request.Cookies[correlationKey]; string correlationCookie = Request.Cookies[correlationKey];

View File

@ -10,13 +10,8 @@ namespace Microsoft.AspNet.Security.Infrastructure
{ {
private readonly RequestDelegate _next; 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; Options = options;
_next = next; _next = next;
} }

View File

@ -2,7 +2,7 @@
using System; using System;
using Microsoft.AspNet.Abstractions; using Microsoft.AspNet.Abstractions;
using Microsoft.AspNet.Security.Provider; using Microsoft.AspNet.Security.Notifications;
namespace Microsoft.AspNet.Security.Infrastructure namespace Microsoft.AspNet.Security.Infrastructure
{ {
@ -11,19 +11,11 @@ namespace Microsoft.AspNet.Security.Infrastructure
private readonly ISecureDataFormat<AuthenticationTicket> _secureDataFormat; private readonly ISecureDataFormat<AuthenticationTicket> _secureDataFormat;
public AuthenticationTokenCreateContext( public AuthenticationTokenCreateContext(
HttpContext context, [NotNull] HttpContext context,
ISecureDataFormat<AuthenticationTicket> secureDataFormat, [NotNull] ISecureDataFormat<AuthenticationTicket> secureDataFormat,
AuthenticationTicket ticket) [NotNull] AuthenticationTicket ticket)
: base(context) : base(context)
{ {
if (secureDataFormat == null)
{
throw new ArgumentNullException("secureDataFormat");
}
if (ticket == null)
{
throw new ArgumentNullException("ticket");
}
_secureDataFormat = secureDataFormat; _secureDataFormat = secureDataFormat;
Ticket = ticket; Ticket = ticket;
} }
@ -37,12 +29,8 @@ namespace Microsoft.AspNet.Security.Infrastructure
return _secureDataFormat.Protect(Ticket); return _secureDataFormat.Protect(Ticket);
} }
public void SetToken(string tokenValue) public void SetToken([NotNull] string tokenValue)
{ {
if (tokenValue == null)
{
throw new ArgumentNullException("tokenValue");
}
Token = tokenValue; Token = tokenValue;
} }
} }

View File

@ -2,7 +2,7 @@
using System; using System;
using Microsoft.AspNet.Abstractions; using Microsoft.AspNet.Abstractions;
using Microsoft.AspNet.Security.Provider; using Microsoft.AspNet.Security.Notifications;
namespace Microsoft.AspNet.Security.Infrastructure namespace Microsoft.AspNet.Security.Infrastructure
{ {
@ -11,18 +11,11 @@ namespace Microsoft.AspNet.Security.Infrastructure
private readonly ISecureDataFormat<AuthenticationTicket> _secureDataFormat; private readonly ISecureDataFormat<AuthenticationTicket> _secureDataFormat;
public AuthenticationTokenReceiveContext( public AuthenticationTokenReceiveContext(
HttpContext context, [NotNull] HttpContext context,
ISecureDataFormat<AuthenticationTicket> secureDataFormat, [NotNull] ISecureDataFormat<AuthenticationTicket> secureDataFormat,
string token) : base(context) [NotNull] string token)
: base(context)
{ {
if (secureDataFormat == null)
{
throw new ArgumentNullException("secureDataFormat");
}
if (token == null)
{
throw new ArgumentNullException("token");
}
_secureDataFormat = secureDataFormat; _secureDataFormat = secureDataFormat;
Token = token; Token = token;
} }
@ -36,12 +29,8 @@ namespace Microsoft.AspNet.Security.Infrastructure
Ticket = _secureDataFormat.Unprotect(protectedData); Ticket = _secureDataFormat.Unprotect(protectedData);
} }
public void SetTicket(AuthenticationTicket ticket) public void SetTicket([NotNull] AuthenticationTicket ticket)
{ {
if (ticket == null)
{
throw new ArgumentNullException("ticket");
}
Ticket = ticket; Ticket = ticket;
} }
} }

View File

@ -0,0 +1,9 @@
using System;
namespace Microsoft.AspNet.Security
{
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
internal sealed class NotNullAttribute : Attribute
{
}
}

View File

@ -18,12 +18,8 @@ namespace Microsoft.AspNet.Security.Infrastructure
/// Add an additional ClaimsIdentity to the ClaimsPrincipal /// Add an additional ClaimsIdentity to the ClaimsPrincipal
/// </summary> /// </summary>
/// <param name="identity"></param> /// <param name="identity"></param>
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); var newClaimsPrincipal = new ClaimsPrincipal(identity);
ClaimsPrincipal existingPrincipal = context.User; ClaimsPrincipal existingPrincipal = context.User;

View File

@ -2,7 +2,7 @@
using Microsoft.AspNet.Abstractions; using Microsoft.AspNet.Abstractions;
namespace Microsoft.AspNet.Security.Provider namespace Microsoft.AspNet.Security.Notifications
{ {
public abstract class BaseContext public abstract class BaseContext
{ {

View File

@ -2,7 +2,7 @@
using Microsoft.AspNet.Abstractions; using Microsoft.AspNet.Abstractions;
namespace Microsoft.AspNet.Security.Provider namespace Microsoft.AspNet.Security.Notifications
{ {
/// <summary> /// <summary>
/// Base class used for certain event contexts /// Base class used for certain event contexts

View File

@ -2,7 +2,7 @@
using Microsoft.AspNet.Abstractions; using Microsoft.AspNet.Abstractions;
namespace Microsoft.AspNet.Security.Provider namespace Microsoft.AspNet.Security.Notifications
{ {
public abstract class EndpointContext : BaseContext public abstract class EndpointContext : BaseContext
{ {

View File

@ -2,7 +2,7 @@
using Microsoft.AspNet.Abstractions; using Microsoft.AspNet.Abstractions;
namespace Microsoft.AspNet.Security.Provider namespace Microsoft.AspNet.Security.Notifications
{ {
/// <summary> /// <summary>
/// Base class used for certain event contexts /// Base class used for certain event contexts

View File

@ -5,7 +5,7 @@ using System.Security.Claims;
using Microsoft.AspNet.Abstractions; using Microsoft.AspNet.Abstractions;
using Microsoft.AspNet.Abstractions.Security; using Microsoft.AspNet.Abstractions.Security;
namespace Microsoft.AspNet.Security.Provider namespace Microsoft.AspNet.Security.Notifications
{ {
public abstract class ReturnEndpointContext : EndpointContext public abstract class ReturnEndpointContext : EndpointContext
{ {