Replace NotNullAttribute with thrown exceptions

This commit is contained in:
Pranav K 2015-09-28 08:03:31 -07:00
parent 952f2ec53c
commit 6ed7d1f3c0
57 changed files with 1187 additions and 227 deletions

View File

@ -6,7 +6,6 @@ using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.Linq; using System.Linq;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.Framework.Internal;
using Microsoft.Framework.Primitives; using Microsoft.Framework.Primitives;
using Microsoft.Framework.WebEncoders; using Microsoft.Framework.WebEncoders;
using Microsoft.Net.Http.Headers; using Microsoft.Net.Http.Headers;
@ -66,8 +65,18 @@ namespace Microsoft.AspNet.Authentication.Cookies
/// <param name="context"></param> /// <param name="context"></param>
/// <param name="key"></param> /// <param name="key"></param>
/// <returns>The reassembled cookie, if any, or null.</returns> /// <returns>The reassembled cookie, if any, or null.</returns>
public string GetRequestCookie([NotNull] HttpContext context, [NotNull] string key) public string GetRequestCookie(HttpContext context, string key)
{ {
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
var requestCookies = context.Request.Cookies; var requestCookies = context.Request.Cookies;
var value = requestCookies[key]; var value = requestCookies[key];
var chunksCount = ParseChunksCount(value); var chunksCount = ParseChunksCount(value);
@ -123,8 +132,23 @@ namespace Microsoft.AspNet.Authentication.Cookies
/// <param name="key"></param> /// <param name="key"></param>
/// <param name="value"></param> /// <param name="value"></param>
/// <param name="options"></param> /// <param name="options"></param>
public void AppendResponseCookie([NotNull] HttpContext context, [NotNull] string key, string value, [NotNull] CookieOptions options) public void AppendResponseCookie(HttpContext context, string key, string value, CookieOptions options)
{ {
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
var escapedKey = Encoder.UrlEncode(key); var escapedKey = Encoder.UrlEncode(key);
var template = new SetCookieHeaderValue(escapedKey) var template = new SetCookieHeaderValue(escapedKey)
@ -198,8 +222,23 @@ namespace Microsoft.AspNet.Authentication.Cookies
/// <param name="context"></param> /// <param name="context"></param>
/// <param name="key"></param> /// <param name="key"></param>
/// <param name="options"></param> /// <param name="options"></param>
public void DeleteCookie([NotNull] HttpContext context, [NotNull] string key, [NotNull] CookieOptions options) public void DeleteCookie(HttpContext context, string key, CookieOptions options)
{ {
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
var escapedKey = Encoder.UrlEncode(key); var escapedKey = Encoder.UrlEncode(key);
var keys = new List<string>(); var keys = new List<string>();
keys.Add(escapedKey + "="); keys.Add(escapedKey + "=");
@ -266,18 +305,33 @@ namespace Microsoft.AspNet.Authentication.Cookies
} }
} }
private static bool IsQuoted([NotNull] string value) private static bool IsQuoted(string value)
{ {
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
return value.Length >= 2 && value[0] == '"' && value[value.Length - 1] == '"'; return value.Length >= 2 && value[0] == '"' && value[value.Length - 1] == '"';
} }
private static string RemoveQuotes([NotNull] string value) private static string RemoveQuotes(string value)
{ {
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
return value.Substring(1, value.Length - 2); return value.Substring(1, value.Length - 2);
} }
private static string Quote([NotNull] string value) private static string Quote(string value)
{ {
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
return '"' + value + '"'; return '"' + value + '"';
} }
} }

View File

@ -3,7 +3,6 @@
using System; using System;
using Microsoft.AspNet.Authentication.Cookies; using Microsoft.AspNet.Authentication.Cookies;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Builder namespace Microsoft.AspNet.Builder
{ {
@ -17,8 +16,13 @@ namespace Microsoft.AspNet.Builder
/// </summary> /// </summary>
/// <param name="app">The IApplicationBuilder passed to your configuration method</param> /// <param name="app">The IApplicationBuilder passed to your configuration method</param>
/// <returns>The original app parameter</returns> /// <returns>The original app parameter</returns>
public static IApplicationBuilder UseCookieAuthentication([NotNull] this IApplicationBuilder app) public static IApplicationBuilder UseCookieAuthentication(this IApplicationBuilder app)
{ {
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
return app.UseCookieAuthentication(new CookieAuthenticationOptions()); return app.UseCookieAuthentication(new CookieAuthenticationOptions());
} }
@ -28,8 +32,13 @@ namespace Microsoft.AspNet.Builder
/// <param name="app">The IApplicationBuilder passed to your configuration method</param> /// <param name="app">The IApplicationBuilder passed to your configuration method</param>
/// <param name="configureOptions">Used to configure the options for the middleware</param> /// <param name="configureOptions">Used to configure the options for the middleware</param>
/// <returns>The original app parameter</returns> /// <returns>The original app parameter</returns>
public static IApplicationBuilder UseCookieAuthentication([NotNull] this IApplicationBuilder app, Action<CookieAuthenticationOptions> configureOptions) public static IApplicationBuilder UseCookieAuthentication(this IApplicationBuilder app, Action<CookieAuthenticationOptions> configureOptions)
{ {
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
var options = new CookieAuthenticationOptions(); var options = new CookieAuthenticationOptions();
if (configureOptions != null) if (configureOptions != null)
{ {
@ -44,8 +53,18 @@ namespace Microsoft.AspNet.Builder
/// <param name="app">The IApplicationBuilder passed to your configuration method</param> /// <param name="app">The IApplicationBuilder passed to your configuration method</param>
/// <param name="options">Used to configure the middleware</param> /// <param name="options">Used to configure the middleware</param>
/// <returns>The original app parameter</returns> /// <returns>The original app parameter</returns>
public static IApplicationBuilder UseCookieAuthentication([NotNull] this IApplicationBuilder app, [NotNull] CookieAuthenticationOptions options) public static IApplicationBuilder UseCookieAuthentication(this IApplicationBuilder app, CookieAuthenticationOptions options)
{ {
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
return app.UseMiddleware<CookieAuthenticationMiddleware>(options); return app.UseMiddleware<CookieAuthenticationMiddleware>(options);
} }
} }

View File

@ -9,7 +9,6 @@ using System.Threading.Tasks;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.Http.Features.Authentication; using Microsoft.AspNet.Http.Features.Authentication;
using Microsoft.Framework.Internal;
using Microsoft.Framework.Logging; using Microsoft.Framework.Logging;
using Microsoft.Framework.Primitives; using Microsoft.Framework.Primitives;
using Microsoft.Net.Http.Headers; using Microsoft.Net.Http.Headers;
@ -402,8 +401,13 @@ namespace Microsoft.AspNet.Authentication.Cookies
return true; return true;
} }
protected override async Task<bool> HandleUnauthorizedAsync([NotNull] ChallengeContext context) protected override async Task<bool> HandleUnauthorizedAsync(ChallengeContext context)
{ {
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var redirectUri = new AuthenticationProperties(context.Properties).RedirectUri; var redirectUri = new AuthenticationProperties(context.Properties).RedirectUri;
try try
{ {

View File

@ -4,7 +4,6 @@
using System; using System;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
using Microsoft.Framework.Internal;
using Microsoft.Framework.Logging; using Microsoft.Framework.Logging;
using Microsoft.Framework.WebEncoders; using Microsoft.Framework.WebEncoders;
@ -13,13 +12,38 @@ namespace Microsoft.AspNet.Authentication.Cookies
public class CookieAuthenticationMiddleware : AuthenticationMiddleware<CookieAuthenticationOptions> public class CookieAuthenticationMiddleware : AuthenticationMiddleware<CookieAuthenticationOptions>
{ {
public CookieAuthenticationMiddleware( public CookieAuthenticationMiddleware(
[NotNull] RequestDelegate next, RequestDelegate next,
[NotNull] IDataProtectionProvider dataProtectionProvider, IDataProtectionProvider dataProtectionProvider,
[NotNull] ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
[NotNull] IUrlEncoder urlEncoder, IUrlEncoder urlEncoder,
[NotNull] CookieAuthenticationOptions options) CookieAuthenticationOptions options)
: base(next, options, loggerFactory, urlEncoder) : base(next, options, loggerFactory, urlEncoder)
{ {
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
if (dataProtectionProvider == null)
{
throw new ArgumentNullException(nameof(dataProtectionProvider));
}
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
if (urlEncoder == null)
{
throw new ArgumentNullException(nameof(urlEncoder));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (Options.Events == null) if (Options.Events == null)
{ {
Options.Events = new CookieAuthenticationEvents(); Options.Events = new CookieAuthenticationEvents();

View File

@ -4,7 +4,6 @@
using System; using System;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.Framework.Internal;
using Microsoft.Framework.OptionsModel; using Microsoft.Framework.OptionsModel;
namespace Microsoft.AspNet.Authentication.Cookies namespace Microsoft.AspNet.Authentication.Cookies
@ -39,9 +38,13 @@ namespace Microsoft.AspNet.Authentication.Cookies
public string CookieName public string CookieName
{ {
get { return _cookieName; } get { return _cookieName; }
[param: NotNull]
set set
{ {
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_cookieName = value; _cookieName = value;
} }
} }

View File

@ -4,7 +4,6 @@
using System; using System;
using Microsoft.AspNet.Authentication.Cookies; using Microsoft.AspNet.Authentication.Cookies;
using Microsoft.Framework.Configuration; using Microsoft.Framework.Configuration;
using Microsoft.Framework.Internal;
namespace Microsoft.Framework.DependencyInjection namespace Microsoft.Framework.DependencyInjection
{ {
@ -13,13 +12,33 @@ namespace Microsoft.Framework.DependencyInjection
/// </summary> /// </summary>
public static class CookieServiceCollectionExtensions public static class CookieServiceCollectionExtensions
{ {
public static IServiceCollection AddCookieAuthentication([NotNull] this IServiceCollection services, [NotNull] Action<CookieAuthenticationOptions> configure) public static IServiceCollection AddCookieAuthentication(this IServiceCollection services, Action<CookieAuthenticationOptions> configure)
{ {
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if (configure == null)
{
throw new ArgumentNullException(nameof(configure));
}
return services.Configure(configure); return services.Configure(configure);
} }
public static IServiceCollection AddCookieAuthentication([NotNull] this IServiceCollection services, [NotNull] IConfiguration config) public static IServiceCollection AddCookieAuthentication(this IServiceCollection services, IConfiguration config)
{ {
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if (config == null)
{
throw new ArgumentNullException(nameof(config));
}
return services.Configure<CookieAuthenticationOptions>(config); return services.Configure<CookieAuthenticationOptions>(config);
} }
} }

View File

@ -1,10 +1,10 @@
// 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. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Security.Claims; using System.Security.Claims;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Authentication.Cookies namespace Microsoft.AspNet.Authentication.Cookies
{ {
@ -19,9 +19,24 @@ namespace Microsoft.AspNet.Authentication.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 CookieValidatePrincipalContext([NotNull] HttpContext context, [NotNull] AuthenticationTicket ticket, [NotNull] CookieAuthenticationOptions options) public CookieValidatePrincipalContext(HttpContext context, AuthenticationTicket ticket, CookieAuthenticationOptions options)
: base(context, options) : base(context, options)
{ {
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (ticket == null)
{
throw new ArgumentNullException(nameof(ticket));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
Principal = ticket.Principal; Principal = ticket.Principal;
Properties = ticket.Properties; Properties = ticket.Properties;
} }

View File

@ -5,9 +5,11 @@
"type": "git", "type": "git",
"url": "git://github.com/aspnet/security" "url": "git://github.com/aspnet/security"
}, },
"compilationOptions": {
"warningsAsErrors": true
},
"dependencies": { "dependencies": {
"Microsoft.AspNet.Authentication": "1.0.0-*", "Microsoft.AspNet.Authentication": "1.0.0-*",
"Microsoft.Framework.NotNullAttribute.Sources": { "type": "build", "version": "1.0.0-*" },
"Microsoft.Framework.WebEncoders": "1.0.0-*", "Microsoft.Framework.WebEncoders": "1.0.0-*",
"Newtonsoft.Json": "6.0.6" "Newtonsoft.Json": "6.0.6"
}, },

View File

@ -3,7 +3,6 @@
using System; using System;
using Microsoft.AspNet.Authentication.Facebook; using Microsoft.AspNet.Authentication.Facebook;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Builder namespace Microsoft.AspNet.Builder
{ {
@ -17,8 +16,18 @@ namespace Microsoft.AspNet.Builder
/// </summary> /// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/> passed to the configure method.</param> /// <param name="app">The <see cref="IApplicationBuilder"/> passed to the configure method.</param>
/// <returns>The updated <see cref="IApplicationBuilder"/>.</returns> /// <returns>The updated <see cref="IApplicationBuilder"/>.</returns>
public static IApplicationBuilder UseFacebookAuthentication([NotNull] this IApplicationBuilder app, [NotNull] FacebookOptions options) public static IApplicationBuilder UseFacebookAuthentication(this IApplicationBuilder app, FacebookOptions options)
{ {
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
return app.UseMiddleware<FacebookMiddleware>(options); return app.UseMiddleware<FacebookMiddleware>(options);
} }
@ -28,8 +37,13 @@ namespace Microsoft.AspNet.Builder
/// <param name="app">The <see cref="IApplicationBuilder"/> passed to the configure method.</param> /// <param name="app">The <see cref="IApplicationBuilder"/> passed to the configure method.</param>
/// <param name="configureOptions">Configures the options.</param> /// <param name="configureOptions">Configures the options.</param>
/// <returns>The updated <see cref="IApplicationBuilder"/>.</returns> /// <returns>The updated <see cref="IApplicationBuilder"/>.</returns>
public static IApplicationBuilder UseFacebookAuthentication([NotNull] this IApplicationBuilder app, Action<FacebookOptions> configureOptions) public static IApplicationBuilder UseFacebookAuthentication(this IApplicationBuilder app, Action<FacebookOptions> configureOptions)
{ {
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
var options = new FacebookOptions(); var options = new FacebookOptions();
if (configureOptions != null) if (configureOptions != null)
{ {

View File

@ -1,7 +1,7 @@
// 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. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Framework.Internal; using System;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
namespace Microsoft.AspNet.Authentication.Facebook namespace Microsoft.AspNet.Authentication.Facebook
@ -15,26 +15,66 @@ namespace Microsoft.AspNet.Authentication.Facebook
/// <summary> /// <summary>
/// Gets the Facebook user ID. /// Gets the Facebook user ID.
/// </summary> /// </summary>
public static string GetId([NotNull] JObject user) => user.Value<string>("id"); public static string GetId(JObject user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return user.Value<string>("id");
}
/// <summary> /// <summary>
/// Gets the user's name. /// Gets the user's name.
/// </summary> /// </summary>
public static string GetName([NotNull] JObject user) => user.Value<string>("name"); public static string GetName(JObject user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return user.Value<string>("name");
}
/// <summary> /// <summary>
/// Gets the user's link. /// Gets the user's link.
/// </summary> /// </summary>
public static string GetLink([NotNull] JObject user) => user.Value<string>("link"); public static string GetLink(JObject user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return user.Value<string>("link");
}
/// <summary> /// <summary>
/// Gets the Facebook username. /// Gets the Facebook username.
/// </summary> /// </summary>
public static string GetUserName([NotNull] JObject user) => user.Value<string>("username"); public static string GetUserName(JObject user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return user.Value<string>("username");
}
/// <summary> /// <summary>
/// Gets the Facebook email. /// Gets the Facebook email.
/// </summary> /// </summary>
public static string GetEmail([NotNull] JObject user) => user.Value<string>("email"); public static string GetEmail(JObject user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return user.Value<string>("email");
}
} }
} }

View File

@ -6,7 +6,6 @@ using System.Globalization;
using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
using Microsoft.Framework.Internal;
using Microsoft.Framework.Logging; using Microsoft.Framework.Logging;
using Microsoft.Framework.OptionsModel; using Microsoft.Framework.OptionsModel;
using Microsoft.Framework.WebEncoders; using Microsoft.Framework.WebEncoders;
@ -29,14 +28,44 @@ namespace Microsoft.AspNet.Authentication.Facebook
/// <param name="options">Configuration options for the middleware.</param> /// <param name="options">Configuration options for the middleware.</param>
/// <param name="configureOptions"></param> /// <param name="configureOptions"></param>
public FacebookMiddleware( public FacebookMiddleware(
[NotNull] RequestDelegate next, RequestDelegate next,
[NotNull] IDataProtectionProvider dataProtectionProvider, IDataProtectionProvider dataProtectionProvider,
[NotNull] ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
[NotNull] IUrlEncoder encoder, IUrlEncoder encoder,
[NotNull] IOptions<SharedAuthenticationOptions> sharedOptions, IOptions<SharedAuthenticationOptions> sharedOptions,
[NotNull] FacebookOptions options) FacebookOptions options)
: base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options) : base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options)
{ {
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
if (dataProtectionProvider == null)
{
throw new ArgumentNullException(nameof(dataProtectionProvider));
}
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
if (encoder == null)
{
throw new ArgumentNullException(nameof(encoder));
}
if (sharedOptions == null)
{
throw new ArgumentNullException(nameof(sharedOptions));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (string.IsNullOrEmpty(Options.AppId)) if (string.IsNullOrEmpty(Options.AppId))
{ {
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, nameof(Options.AppId))); throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, nameof(Options.AppId)));

View File

@ -5,9 +5,11 @@
"type": "git", "type": "git",
"url": "git://github.com/aspnet/security" "url": "git://github.com/aspnet/security"
}, },
"compilationOptions": {
"warningsAsErrors": true
},
"dependencies": { "dependencies": {
"Microsoft.AspNet.Authentication.OAuth": "1.0.0-*", "Microsoft.AspNet.Authentication.OAuth": "1.0.0-*",
"Microsoft.Framework.NotNullAttribute.Sources": { "type": "build", "version": "1.0.0-*" },
"Newtonsoft.Json": "6.0.6" "Newtonsoft.Json": "6.0.6"
}, },
"frameworks": { "frameworks": {

View File

@ -3,7 +3,6 @@
using System; using System;
using Microsoft.AspNet.Authentication.Google; using Microsoft.AspNet.Authentication.Google;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Builder namespace Microsoft.AspNet.Builder
{ {
@ -18,8 +17,18 @@ namespace Microsoft.AspNet.Builder
/// <param name="app">The <see cref="IApplicationBuilder"/> passed to the configure method.</param> /// <param name="app">The <see cref="IApplicationBuilder"/> passed to the configure method.</param>
/// <param name="options">The Middleware options.</param> /// <param name="options">The Middleware options.</param>
/// <returns>The updated <see cref="IApplicationBuilder"/>.</returns> /// <returns>The updated <see cref="IApplicationBuilder"/>.</returns>
public static IApplicationBuilder UseGoogleAuthentication([NotNull] this IApplicationBuilder app, [NotNull] GoogleOptions options) public static IApplicationBuilder UseGoogleAuthentication(this IApplicationBuilder app, GoogleOptions options)
{ {
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
return app.UseMiddleware<GoogleMiddleware>(options); return app.UseMiddleware<GoogleMiddleware>(options);
} }
@ -30,8 +39,13 @@ namespace Microsoft.AspNet.Builder
/// <param name="configureOptions">Used to configure Middleware options.</param> /// <param name="configureOptions">Used to configure Middleware options.</param>
/// <param name="optionsName">Name of the options instance to be used</param> /// <param name="optionsName">Name of the options instance to be used</param>
/// <returns>The updated <see cref="IApplicationBuilder"/>.</returns> /// <returns>The updated <see cref="IApplicationBuilder"/>.</returns>
public static IApplicationBuilder UseGoogleAuthentication([NotNull] this IApplicationBuilder app, Action<GoogleOptions> configureOptions) public static IApplicationBuilder UseGoogleAuthentication(this IApplicationBuilder app, Action<GoogleOptions> configureOptions)
{ {
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
var options = new GoogleOptions(); var options = new GoogleOptions();
if (configureOptions != null) if (configureOptions != null)
{ {

View File

@ -1,6 +1,7 @@
// 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. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.Framework.Internal; using Microsoft.Framework.Internal;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
@ -15,32 +16,80 @@ namespace Microsoft.AspNet.Authentication.Google
/// <summary> /// <summary>
/// Gets the Google user ID. /// Gets the Google user ID.
/// </summary> /// </summary>
public static string GetId([NotNull] JObject user) => user.Value<string>("id"); public static string GetId(JObject user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return user.Value<string>("id");
}
/// <summary> /// <summary>
/// Gets the user's name. /// Gets the user's name.
/// </summary> /// </summary>
public static string GetName([NotNull] JObject user) => user.Value<string>("displayName"); public static string GetName(JObject user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return user.Value<string>("displayName");
}
/// <summary> /// <summary>
/// Gets the user's given name. /// Gets the user's given name.
/// </summary> /// </summary>
public static string GetGivenName([NotNull] JObject user) => TryGetValue(user, "name", "givenName"); public static string GetGivenName(JObject user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return TryGetValue(user, "name", "givenName");
}
/// <summary> /// <summary>
/// Gets the user's family name. /// Gets the user's family name.
/// </summary> /// </summary>
public static string GetFamilyName([NotNull] JObject user) => TryGetValue(user, "name", "familyName"); public static string GetFamilyName(JObject user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return TryGetValue(user, "name", "familyName");
}
/// <summary> /// <summary>
/// Gets the user's profile link. /// Gets the user's profile link.
/// </summary> /// </summary>
public static string GetProfile([NotNull] JObject user) => user.Value<string>("url"); public static string GetProfile(JObject user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return user.Value<string>("url");
}
/// <summary> /// <summary>
/// Gets the user's email. /// Gets the user's email.
/// </summary> /// </summary>
public static string GetEmail([NotNull] JObject user) => TryGetFirstValue(user, "emails", "value"); public static string GetEmail(JObject user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return TryGetFirstValue(user, "emails", "value");
}
// Get the given subProperty from a property. // Get the given subProperty from a property.
private static string TryGetValue(JObject user, string propertyName, string subProperty) private static string TryGetValue(JObject user, string propertyName, string subProperty)

View File

@ -1,11 +1,11 @@
// 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. // 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.Diagnostics.CodeAnalysis;
using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
using Microsoft.Framework.Internal;
using Microsoft.Framework.Logging; using Microsoft.Framework.Logging;
using Microsoft.Framework.OptionsModel; using Microsoft.Framework.OptionsModel;
using Microsoft.Framework.WebEncoders; using Microsoft.Framework.WebEncoders;
@ -29,14 +29,44 @@ namespace Microsoft.AspNet.Authentication.Google
/// <param name="options">Configuration options for the middleware.</param> /// <param name="options">Configuration options for the middleware.</param>
/// <param name="configureOptions"></param> /// <param name="configureOptions"></param>
public GoogleMiddleware( public GoogleMiddleware(
[NotNull] RequestDelegate next, RequestDelegate next,
[NotNull] IDataProtectionProvider dataProtectionProvider, IDataProtectionProvider dataProtectionProvider,
[NotNull] ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
[NotNull] IUrlEncoder encoder, IUrlEncoder encoder,
[NotNull] IOptions<SharedAuthenticationOptions> sharedOptions, IOptions<SharedAuthenticationOptions> sharedOptions,
[NotNull] GoogleOptions options) GoogleOptions options)
: base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options) : base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options)
{ {
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
if (dataProtectionProvider == null)
{
throw new ArgumentNullException(nameof(dataProtectionProvider));
}
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
if (encoder == null)
{
throw new ArgumentNullException(nameof(encoder));
}
if (sharedOptions == null)
{
throw new ArgumentNullException(nameof(sharedOptions));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (Options.Scope.Count == 0) if (Options.Scope.Count == 0)
{ {
// Google OAuth 2.0 asks for non-empty scope. If user didn't set it, set default scope to // Google OAuth 2.0 asks for non-empty scope. If user didn't set it, set default scope to

View File

@ -5,9 +5,11 @@
"type": "git", "type": "git",
"url": "git://github.com/aspnet/security" "url": "git://github.com/aspnet/security"
}, },
"compilationOptions": {
"warningsAsErrors": true
},
"dependencies": { "dependencies": {
"Microsoft.AspNet.Authentication.OAuth": "1.0.0-*", "Microsoft.AspNet.Authentication.OAuth": "1.0.0-*"
"Microsoft.Framework.NotNullAttribute.Sources": { "type": "build", "version": "1.0.0-*" }
}, },
"frameworks": { "frameworks": {
"dnx451": { }, "dnx451": { },

View File

@ -3,8 +3,6 @@
using System; using System;
using Microsoft.AspNet.Authentication.JwtBearer; using Microsoft.AspNet.Authentication.JwtBearer;
using Microsoft.Framework.Internal;
using Microsoft.Framework.OptionsModel;
namespace Microsoft.AspNet.Builder namespace Microsoft.AspNet.Builder
{ {
@ -24,8 +22,18 @@ namespace Microsoft.AspNet.Builder
/// <param name="app">The application builder</param> /// <param name="app">The application builder</param>
/// <param name="options">Options which control the processing of the bearer header.</param> /// <param name="options">Options which control the processing of the bearer header.</param>
/// <returns>The application builder</returns> /// <returns>The application builder</returns>
public static IApplicationBuilder UseJwtBearerAuthentication([NotNull] this IApplicationBuilder app, [NotNull] JwtBearerOptions options) public static IApplicationBuilder UseJwtBearerAuthentication(this IApplicationBuilder app, JwtBearerOptions options)
{ {
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
return app.UseMiddleware<JwtBearerMiddleware>(options); return app.UseMiddleware<JwtBearerMiddleware>(options);
} }
@ -40,8 +48,13 @@ namespace Microsoft.AspNet.Builder
/// <param name="app">The application builder</param> /// <param name="app">The application builder</param>
/// <param name="configureOptions">Used to configure Middleware options.</param> /// <param name="configureOptions">Used to configure Middleware options.</param>
/// <returns>The application builder</returns> /// <returns>The application builder</returns>
public static IApplicationBuilder UseJwtBearerAuthentication([NotNull] this IApplicationBuilder app, Action<JwtBearerOptions> configureOptions) public static IApplicationBuilder UseJwtBearerAuthentication(this IApplicationBuilder app, Action<JwtBearerOptions> configureOptions)
{ {
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
var options = new JwtBearerOptions(); var options = new JwtBearerOptions();
if (configureOptions != null) if (configureOptions != null)
{ {

View File

@ -4,7 +4,6 @@
using System; using System;
using System.Net.Http; using System.Net.Http;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.Framework.Internal;
using Microsoft.Framework.Logging; using Microsoft.Framework.Logging;
using Microsoft.Framework.WebEncoders; using Microsoft.Framework.WebEncoders;
using Microsoft.IdentityModel.Protocols; using Microsoft.IdentityModel.Protocols;
@ -25,12 +24,32 @@ namespace Microsoft.AspNet.Authentication.JwtBearer
/// extension method. /// extension method.
/// </summary> /// </summary>
public JwtBearerMiddleware( public JwtBearerMiddleware(
[NotNull] RequestDelegate next, RequestDelegate next,
[NotNull] ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
[NotNull] IUrlEncoder encoder, IUrlEncoder encoder,
[NotNull] JwtBearerOptions options) JwtBearerOptions options)
: base(next, options, loggerFactory, encoder) : base(next, options, loggerFactory, encoder)
{ {
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
if (encoder == null)
{
throw new ArgumentNullException(nameof(encoder));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (Options.Events == null) if (Options.Events == null)
{ {
Options.Events = new JwtBearerEvents(); Options.Events = new JwtBearerEvents();

View File

@ -5,9 +5,11 @@
"type": "git", "type": "git",
"url": "git://github.com/aspnet/security" "url": "git://github.com/aspnet/security"
}, },
"compilationOptions": {
"warningsAsErrors": true
},
"dependencies": { "dependencies": {
"Microsoft.AspNet.Authentication": "1.0.0-*", "Microsoft.AspNet.Authentication": "1.0.0-*",
"Microsoft.Framework.NotNullAttribute.Sources": { "type": "build", "version": "1.0.0-*" },
"Microsoft.IdentityModel.Protocols.OpenIdConnect": "2.0.0-beta8-*" "Microsoft.IdentityModel.Protocols.OpenIdConnect": "2.0.0-beta8-*"
}, },
"frameworks": { "frameworks": {

View File

@ -3,7 +3,6 @@
using System; using System;
using Microsoft.AspNet.Authentication.MicrosoftAccount; using Microsoft.AspNet.Authentication.MicrosoftAccount;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Builder namespace Microsoft.AspNet.Builder
{ {
@ -12,13 +11,28 @@ namespace Microsoft.AspNet.Builder
/// </summary> /// </summary>
public static class MicrosoftAccountAuthenticationExtensions public static class MicrosoftAccountAuthenticationExtensions
{ {
public static IApplicationBuilder UseMicrosoftAccountAuthentication([NotNull] this IApplicationBuilder app, [NotNull] MicrosoftAccountOptions options) public static IApplicationBuilder UseMicrosoftAccountAuthentication(this IApplicationBuilder app, MicrosoftAccountOptions options)
{ {
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
return app.UseMiddleware<MicrosoftAccountMiddleware>(options); return app.UseMiddleware<MicrosoftAccountMiddleware>(options);
} }
public static IApplicationBuilder UseMicrosoftAccountAuthentication([NotNull] this IApplicationBuilder app, Action<MicrosoftAccountOptions> configureOptions) public static IApplicationBuilder UseMicrosoftAccountAuthentication(this IApplicationBuilder app, Action<MicrosoftAccountOptions> configureOptions)
{ {
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
var options = new MicrosoftAccountOptions(); var options = new MicrosoftAccountOptions();
if (configureOptions != null) if (configureOptions != null)
{ {

View File

@ -1,7 +1,7 @@
// 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. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.Framework.Internal; using System;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
namespace Microsoft.AspNet.Authentication.MicrosoftAccount namespace Microsoft.AspNet.Authentication.MicrosoftAccount
@ -15,27 +15,66 @@ namespace Microsoft.AspNet.Authentication.MicrosoftAccount
/// <summary> /// <summary>
/// Gets the Microsoft Account user ID. /// Gets the Microsoft Account user ID.
/// </summary> /// </summary>
public static string GetId([NotNull] JObject user) => user.Value<string>("id"); public static string GetId(JObject user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return user.Value<string>("id");
}
/// <summary> /// <summary>
/// Gets the user's name. /// Gets the user's name.
/// </summary> /// </summary>
public static string GetName([NotNull] JObject user) => user.Value<string>("name"); public static string GetName(JObject user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return user.Value<string>("name");
}
/// <summary> /// <summary>
/// Gets the user's first name. /// Gets the user's first name.
/// </summary> /// </summary>
public static string GetFirstName([NotNull] JObject user) => user.Value<string>("first_name"); public static string GetFirstName(JObject user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return user.Value<string>("first_name");
}
/// <summary> /// <summary>
/// Gets the user's last name. /// Gets the user's last name.
/// </summary> /// </summary>
public static string GetLastName([NotNull] JObject user) => user.Value<string>("last_name"); public static string GetLastName(JObject user)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return user.Value<string>("last_name");
}
/// <summary> /// <summary>
/// Gets the user's email address. /// Gets the user's email address.
/// </summary> /// </summary>
public static string GetEmail([NotNull] JObject user) => user.Value<JObject>("emails") public static string GetEmail(JObject user)
?.Value<string>("preferred"); {
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
return user.Value<JObject>("emails")?.Value<string>("preferred");
}
} }
} }

View File

@ -1,10 +1,10 @@
// 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. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
using Microsoft.Framework.Internal;
using Microsoft.Framework.Logging; using Microsoft.Framework.Logging;
using Microsoft.Framework.OptionsModel; using Microsoft.Framework.OptionsModel;
using Microsoft.Framework.WebEncoders; using Microsoft.Framework.WebEncoders;
@ -27,14 +27,44 @@ namespace Microsoft.AspNet.Authentication.MicrosoftAccount
/// <param name="options">Configuration options for the middleware.</param> /// <param name="options">Configuration options for the middleware.</param>
/// <param name="configureOptions"></param> /// <param name="configureOptions"></param>
public MicrosoftAccountMiddleware( public MicrosoftAccountMiddleware(
[NotNull] RequestDelegate next, RequestDelegate next,
[NotNull] IDataProtectionProvider dataProtectionProvider, IDataProtectionProvider dataProtectionProvider,
[NotNull] ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
[NotNull] IUrlEncoder encoder, IUrlEncoder encoder,
[NotNull] IOptions<SharedAuthenticationOptions> sharedOptions, IOptions<SharedAuthenticationOptions> sharedOptions,
[NotNull] MicrosoftAccountOptions options) MicrosoftAccountOptions options)
: base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options) : base(next, dataProtectionProvider, loggerFactory, encoder, sharedOptions, options)
{ {
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
if (dataProtectionProvider == null)
{
throw new ArgumentNullException(nameof(dataProtectionProvider));
}
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
if (encoder == null)
{
throw new ArgumentNullException(nameof(encoder));
}
if (sharedOptions == null)
{
throw new ArgumentNullException(nameof(sharedOptions));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (Options.Scope.Count == 0) if (Options.Scope.Count == 0)
{ {
// LiveID requires a scope string, so if the user didn't set one we go for the least possible. // LiveID requires a scope string, so if the user didn't set one we go for the least possible.

View File

@ -5,9 +5,11 @@
"type": "git", "type": "git",
"url": "git://github.com/aspnet/security" "url": "git://github.com/aspnet/security"
}, },
"compilationOptions": {
"warningsAsErrors": true
},
"dependencies": { "dependencies": {
"Microsoft.AspNet.Authentication.OAuth": "1.0.0-*", "Microsoft.AspNet.Authentication.OAuth": "1.0.0-*"
"Microsoft.Framework.NotNullAttribute.Sources": { "type": "build", "version": "1.0.0-*" }
}, },
"frameworks": { "frameworks": {
"dnx451": { }, "dnx451": { },

View File

@ -7,7 +7,6 @@ using System.Net.Http;
using System.Security.Claims; using System.Security.Claims;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.Framework.Internal;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
namespace Microsoft.AspNet.Authentication.OAuth namespace Microsoft.AspNet.Authentication.OAuth
@ -25,10 +24,10 @@ namespace Microsoft.AspNet.Authentication.OAuth
/// <param name="backchannel">The HTTP client used by the authentication middleware</param> /// <param name="backchannel">The HTTP client used by the authentication middleware</param>
/// <param name="tokens">The tokens returned from the token endpoint.</param> /// <param name="tokens">The tokens returned from the token endpoint.</param>
public OAuthCreatingTicketContext( public OAuthCreatingTicketContext(
[NotNull] HttpContext context, HttpContext context,
[NotNull] OAuthOptions options, OAuthOptions options,
[NotNull] HttpClient backchannel, HttpClient backchannel,
[NotNull] OAuthTokenResponse tokens) OAuthTokenResponse tokens)
: this(context, options, backchannel, tokens, user: new JObject()) : this(context, options, backchannel, tokens, user: new JObject())
{ {
} }
@ -42,13 +41,38 @@ namespace Microsoft.AspNet.Authentication.OAuth
/// <param name="tokens">The tokens returned from the token endpoint.</param> /// <param name="tokens">The tokens returned from the token endpoint.</param>
/// <param name="user">The JSON-serialized user.</param> /// <param name="user">The JSON-serialized user.</param>
public OAuthCreatingTicketContext( public OAuthCreatingTicketContext(
[NotNull] HttpContext context, HttpContext context,
[NotNull] OAuthOptions options, OAuthOptions options,
[NotNull] HttpClient backchannel, HttpClient backchannel,
[NotNull] OAuthTokenResponse tokens, OAuthTokenResponse tokens,
[NotNull] JObject user) JObject user)
: base(context, options) : base(context, options)
{ {
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (backchannel == null)
{
throw new ArgumentNullException(nameof(backchannel));
}
if (tokens == null)
{
throw new ArgumentNullException(nameof(tokens));
}
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
TokenResponse = tokens; TokenResponse = tokens;
Backchannel = backchannel; Backchannel = backchannel;
User = user; User = user;
@ -96,7 +120,7 @@ namespace Microsoft.AspNet.Authentication.OAuth
return null; return null;
} }
} }
/// <summary> /// <summary>
/// Gets the backchannel used to communicate with the provider. /// Gets the backchannel used to communicate with the provider.
/// </summary> /// </summary>

View File

@ -3,8 +3,6 @@
using System; using System;
using Microsoft.AspNet.Authentication.OAuth; using Microsoft.AspNet.Authentication.OAuth;
using Microsoft.Framework.Internal;
using Microsoft.Framework.OptionsModel;
namespace Microsoft.AspNet.Builder namespace Microsoft.AspNet.Builder
{ {
@ -19,8 +17,18 @@ namespace Microsoft.AspNet.Builder
/// <param name="app">The <see cref="IApplicationBuilder"/> passed to the configure method.</param> /// <param name="app">The <see cref="IApplicationBuilder"/> passed to the configure method.</param>
/// <param name="configureOptions">Configures the middleware options.</param> /// <param name="configureOptions">Configures the middleware options.</param>
/// <returns>The updated <see cref="IApplicationBuilder"/>.</returns> /// <returns>The updated <see cref="IApplicationBuilder"/>.</returns>
public static IApplicationBuilder UseOAuthAuthentication([NotNull] this IApplicationBuilder app, [NotNull] Action<OAuthOptions> configureOptions) public static IApplicationBuilder UseOAuthAuthentication(this IApplicationBuilder app, Action<OAuthOptions> configureOptions)
{ {
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
var options = new OAuthOptions(); var options = new OAuthOptions();
if (configureOptions != null) if (configureOptions != null)
{ {
@ -35,8 +43,18 @@ namespace Microsoft.AspNet.Builder
/// <param name="app">The <see cref="IApplicationBuilder"/> passed to the configure method.</param> /// <param name="app">The <see cref="IApplicationBuilder"/> passed to the configure method.</param>
/// <param name="options">The middleware configuration options.</param> /// <param name="options">The middleware configuration options.</param>
/// <returns>The updated <see cref="IApplicationBuilder"/>.</returns> /// <returns>The updated <see cref="IApplicationBuilder"/>.</returns>
public static IApplicationBuilder UseOAuthAuthentication([NotNull] this IApplicationBuilder app, [NotNull] OAuthOptions options) public static IApplicationBuilder UseOAuthAuthentication(this IApplicationBuilder app, OAuthOptions options)
{ {
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
return app.UseMiddleware<OAuthMiddleware<OAuthOptions>>(options); return app.UseMiddleware<OAuthMiddleware<OAuthOptions>>(options);
} }
} }

View File

@ -13,7 +13,6 @@ using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.Http.Extensions; using Microsoft.AspNet.Http.Extensions;
using Microsoft.AspNet.Http.Features.Authentication; using Microsoft.AspNet.Http.Features.Authentication;
using Microsoft.AspNet.WebUtilities; using Microsoft.AspNet.WebUtilities;
using Microsoft.Framework.Internal;
using Microsoft.Framework.Logging; using Microsoft.Framework.Logging;
using Microsoft.Framework.Primitives; using Microsoft.Framework.Primitives;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
@ -148,7 +147,7 @@ namespace Microsoft.AspNet.Authentication.OAuth
ClaimValueTypes.String, Options.ClaimsIssuer)); ClaimValueTypes.String, Options.ClaimsIssuer));
} }
} }
return await CreateTicketAsync(identity, properties, tokens); return await CreateTicketAsync(identity, properties, tokens);
} }
catch (Exception ex) catch (Exception ex)
@ -188,7 +187,7 @@ namespace Microsoft.AspNet.Authentication.OAuth
Principal = new ClaimsPrincipal(identity), Principal = new ClaimsPrincipal(identity),
Properties = properties Properties = properties
}; };
await Options.Events.CreatingTicket(context); await Options.Events.CreatingTicket(context);
if (context.Principal?.Identity == null) if (context.Principal?.Identity == null)
@ -199,8 +198,13 @@ namespace Microsoft.AspNet.Authentication.OAuth
return new AuthenticationTicket(context.Principal, context.Properties, Options.AuthenticationScheme); return new AuthenticationTicket(context.Principal, context.Properties, Options.AuthenticationScheme);
} }
protected override async Task<bool> HandleUnauthorizedAsync([NotNull] ChallengeContext context) protected override async Task<bool> HandleUnauthorizedAsync(ChallengeContext context)
{ {
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var properties = new AuthenticationProperties(context.Properties); var properties = new AuthenticationProperties(context.Properties);
if (string.IsNullOrEmpty(properties.RedirectUri)) if (string.IsNullOrEmpty(properties.RedirectUri))
{ {
@ -257,8 +261,13 @@ namespace Microsoft.AspNet.Authentication.OAuth
return string.Join(" ", Options.Scope); return string.Join(" ", Options.Scope);
} }
protected void GenerateCorrelationId([NotNull] AuthenticationProperties properties) protected void GenerateCorrelationId(AuthenticationProperties properties)
{ {
if (properties == null)
{
throw new ArgumentNullException(nameof(properties));
}
var correlationKey = Constants.CorrelationPrefix + Options.AuthenticationScheme; var correlationKey = Constants.CorrelationPrefix + Options.AuthenticationScheme;
var nonceBytes = new byte[32]; var nonceBytes = new byte[32];
@ -276,8 +285,13 @@ namespace Microsoft.AspNet.Authentication.OAuth
Response.Cookies.Append(correlationKey, correlationId, cookieOptions); Response.Cookies.Append(correlationKey, correlationId, cookieOptions);
} }
protected bool ValidateCorrelationId([NotNull] AuthenticationProperties properties) protected bool ValidateCorrelationId(AuthenticationProperties properties)
{ {
if (properties == null)
{
throw new ArgumentNullException(nameof(properties));
}
var correlationKey = Constants.CorrelationPrefix + Options.AuthenticationScheme; var correlationKey = Constants.CorrelationPrefix + Options.AuthenticationScheme;
var correlationCookie = Request.Cookies[correlationKey]; var correlationCookie = Request.Cookies[correlationKey];
if (string.IsNullOrEmpty(correlationCookie)) if (string.IsNullOrEmpty(correlationCookie))

View File

@ -7,7 +7,6 @@ using System.Globalization;
using System.Net.Http; using System.Net.Http;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
using Microsoft.Framework.Internal;
using Microsoft.Framework.Logging; using Microsoft.Framework.Logging;
using Microsoft.Framework.OptionsModel; using Microsoft.Framework.OptionsModel;
using Microsoft.Framework.WebEncoders; using Microsoft.Framework.WebEncoders;
@ -28,14 +27,44 @@ namespace Microsoft.AspNet.Authentication.OAuth
/// <param name="loggerFactory"></param> /// <param name="loggerFactory"></param>
/// <param name="options">Configuration options for the middleware.</param> /// <param name="options">Configuration options for the middleware.</param>
public OAuthMiddleware( public OAuthMiddleware(
[NotNull] RequestDelegate next, RequestDelegate next,
[NotNull] IDataProtectionProvider dataProtectionProvider, IDataProtectionProvider dataProtectionProvider,
[NotNull] ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
[NotNull] IUrlEncoder encoder, IUrlEncoder encoder,
[NotNull] IOptions<SharedAuthenticationOptions> sharedOptions, IOptions<SharedAuthenticationOptions> sharedOptions,
[NotNull] TOptions options) TOptions options)
: base(next, options, loggerFactory, encoder) : base(next, options, loggerFactory, encoder)
{ {
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
if (dataProtectionProvider == null)
{
throw new ArgumentNullException(nameof(dataProtectionProvider));
}
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
if (encoder == null)
{
throw new ArgumentNullException(nameof(encoder));
}
if (sharedOptions == null)
{
throw new ArgumentNullException(nameof(sharedOptions));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
// todo: review error handling // todo: review error handling
if (string.IsNullOrEmpty(Options.AuthenticationScheme)) if (string.IsNullOrEmpty(Options.AuthenticationScheme))
{ {

View File

@ -5,9 +5,11 @@
"type": "git", "type": "git",
"url": "git://github.com/aspnet/security" "url": "git://github.com/aspnet/security"
}, },
"compilationOptions": {
"warningsAsErrors": true
},
"dependencies": { "dependencies": {
"Microsoft.AspNet.Authentication": "1.0.0-*", "Microsoft.AspNet.Authentication": "1.0.0-*",
"Microsoft.Framework.NotNullAttribute.Sources": { "type": "build", "version": "1.0.0-*" },
"Newtonsoft.Json": "6.0.6" "Newtonsoft.Json": "6.0.6"
}, },
"frameworks": { "frameworks": {

View File

@ -3,7 +3,6 @@
using System; using System;
using Microsoft.AspNet.Authentication.OpenIdConnect; using Microsoft.AspNet.Authentication.OpenIdConnect;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Builder namespace Microsoft.AspNet.Builder
{ {
@ -18,8 +17,13 @@ namespace Microsoft.AspNet.Builder
/// <param name="app">The application builder</param> /// <param name="app">The application builder</param>
/// <param name="options">Options which control the processing of the OpenIdConnect protocol and token validation.</param> /// <param name="options">Options which control the processing of the OpenIdConnect protocol and token validation.</param>
/// <returns>The application builder</returns> /// <returns>The application builder</returns>
public static IApplicationBuilder UseOpenIdConnectAuthentication([NotNull] this IApplicationBuilder app, Action<OpenIdConnectOptions> configureOptions) public static IApplicationBuilder UseOpenIdConnectAuthentication(this IApplicationBuilder app, Action<OpenIdConnectOptions> configureOptions)
{ {
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
var options = new OpenIdConnectOptions(); var options = new OpenIdConnectOptions();
if (configureOptions != null) if (configureOptions != null)
@ -35,8 +39,18 @@ namespace Microsoft.AspNet.Builder
/// <param name="app">The application builder</param> /// <param name="app">The application builder</param>
/// <param name="options">Options which control the processing of the OpenIdConnect protocol and token validation.</param> /// <param name="options">Options which control the processing of the OpenIdConnect protocol and token validation.</param>
/// <returns>The application builder</returns> /// <returns>The application builder</returns>
public static IApplicationBuilder UseOpenIdConnectAuthentication([NotNull] this IApplicationBuilder app, [NotNull] OpenIdConnectOptions options) public static IApplicationBuilder UseOpenIdConnectAuthentication(this IApplicationBuilder app, OpenIdConnectOptions options)
{ {
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
return app.UseMiddleware<OpenIdConnectMiddleware>(options); return app.UseMiddleware<OpenIdConnectMiddleware>(options);
} }
} }

View File

@ -16,7 +16,6 @@ using System.Threading.Tasks;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.Http.Features.Authentication; using Microsoft.AspNet.Http.Features.Authentication;
using Microsoft.Framework.Internal;
using Microsoft.Framework.Logging; using Microsoft.Framework.Logging;
using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.Net.Http.Headers; using Microsoft.Net.Http.Headers;
@ -160,8 +159,13 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
/// <remarks>Uses log id's OIDCH-0026 - OIDCH-0050, next num: 37</remarks> /// <remarks>Uses log id's OIDCH-0026 - OIDCH-0050, next num: 37</remarks>
protected override async Task<bool> HandleUnauthorizedAsync([NotNull] ChallengeContext context) protected override async Task<bool> HandleUnauthorizedAsync(ChallengeContext context)
{ {
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
Logger.LogDebug(Resources.OIDCH_0026_ApplyResponseChallengeAsync, this.GetType()); Logger.LogDebug(Resources.OIDCH_0026_ApplyResponseChallengeAsync, this.GetType());
// order for local RedirectUri // order for local RedirectUri
@ -727,7 +731,7 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
/// <param name="saveRefreshToken">A <see cref="bool"/> indicating whether the refresh token should be stored.</param> /// <param name="saveRefreshToken">A <see cref="bool"/> indicating whether the refresh token should be stored.</param>
private void SaveTokens(ClaimsPrincipal principal, OpenIdConnectMessage message, bool saveRefreshToken) private void SaveTokens(ClaimsPrincipal principal, OpenIdConnectMessage message, bool saveRefreshToken)
{ {
var identity = (ClaimsIdentity) principal.Identity; var identity = (ClaimsIdentity)principal.Identity;
if (!string.IsNullOrEmpty(message.AccessToken)) if (!string.IsNullOrEmpty(message.AccessToken))
{ {
@ -827,8 +831,13 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
return null; return null;
} }
private void GenerateCorrelationId([NotNull] AuthenticationProperties properties) private void GenerateCorrelationId(AuthenticationProperties properties)
{ {
if (properties == null)
{
throw new ArgumentNullException(nameof(properties));
}
var correlationKey = OpenIdConnectDefaults.CookieStatePrefix; var correlationKey = OpenIdConnectDefaults.CookieStatePrefix;
var nonceBytes = new byte[32]; var nonceBytes = new byte[32];
@ -847,8 +856,13 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
Response.Cookies.Append(correlationKey + correlationId, NonceProperty, cookieOptions); Response.Cookies.Append(correlationKey + correlationId, NonceProperty, cookieOptions);
} }
private bool ValidateCorrelationId([NotNull] AuthenticationProperties properties) private bool ValidateCorrelationId(AuthenticationProperties properties)
{ {
if (properties == null)
{
throw new ArgumentNullException(nameof(properties));
}
var correlationKey = OpenIdConnectDefaults.CookieStatePrefix; var correlationKey = OpenIdConnectDefaults.CookieStatePrefix;
string correlationId; string correlationId;

View File

@ -8,7 +8,6 @@ using System.Text;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.Framework.Internal;
using Microsoft.Framework.Logging; using Microsoft.Framework.Logging;
using Microsoft.Framework.OptionsModel; using Microsoft.Framework.OptionsModel;
using Microsoft.Framework.WebEncoders; using Microsoft.Framework.WebEncoders;
@ -34,15 +33,50 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
/// <param name="options"></param> /// <param name="options"></param>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Managed by caller")] [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Managed by caller")]
public OpenIdConnectMiddleware( public OpenIdConnectMiddleware(
[NotNull] RequestDelegate next, RequestDelegate next,
[NotNull] IDataProtectionProvider dataProtectionProvider, IDataProtectionProvider dataProtectionProvider,
[NotNull] ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
[NotNull] IUrlEncoder encoder, IUrlEncoder encoder,
[NotNull] IServiceProvider services, IServiceProvider services,
[NotNull] IOptions<SharedAuthenticationOptions> sharedOptions, IOptions<SharedAuthenticationOptions> sharedOptions,
[NotNull] OpenIdConnectOptions options) OpenIdConnectOptions options)
: base(next, options, loggerFactory, encoder) : base(next, options, loggerFactory, encoder)
{ {
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
if (dataProtectionProvider == null)
{
throw new ArgumentNullException(nameof(dataProtectionProvider));
}
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
if (encoder == null)
{
throw new ArgumentNullException(nameof(encoder));
}
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if (sharedOptions == null)
{
throw new ArgumentNullException(nameof(sharedOptions));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (string.IsNullOrEmpty(Options.SignInScheme) && !string.IsNullOrEmpty(sharedOptions.Value.SignInScheme)) if (string.IsNullOrEmpty(Options.SignInScheme) && !string.IsNullOrEmpty(sharedOptions.Value.SignInScheme))
{ {
Options.SignInScheme = sharedOptions.Value.SignInScheme; Options.SignInScheme = sharedOptions.Value.SignInScheme;
@ -74,7 +108,7 @@ namespace Microsoft.AspNet.Authentication.OpenIdConnect
Options.StringDataFormat = new SecureDataFormat<string>(new StringSerializer(), dataProtector); Options.StringDataFormat = new SecureDataFormat<string>(new StringSerializer(), dataProtector);
} }
// if the user has not set the AuthorizeCallback, set it from the redirect_uri // if the user has not set the AuthorizeCallback, set it from the redirect_uri
if (!Options.CallbackPath.HasValue) if (!Options.CallbackPath.HasValue)
{ {

View File

@ -5,9 +5,11 @@
"type": "git", "type": "git",
"url": "git://github.com/aspnet/security" "url": "git://github.com/aspnet/security"
}, },
"compilationOptions": {
"warningsAsErrors": true
},
"dependencies": { "dependencies": {
"Microsoft.AspNet.Authentication": "1.0.0-*", "Microsoft.AspNet.Authentication": "1.0.0-*",
"Microsoft.Framework.NotNullAttribute.Sources": { "type": "build", "version": "1.0.0-*" },
"Microsoft.IdentityModel.Protocols.OpenIdConnect": "2.0.0-beta8-*" "Microsoft.IdentityModel.Protocols.OpenIdConnect": "2.0.0-beta8-*"
}, },
"frameworks": { "frameworks": {
@ -18,7 +20,6 @@
}, },
"dnxcore50": { "dnxcore50": {
"dependencies": { "dependencies": {
"System.Collections.Specialized": "4.0.1-beta-*",
"System.Net.Http": "4.0.1-beta-*" "System.Net.Http": "4.0.1-beta-*"
} }
} }

View File

@ -1,10 +1,10 @@
// 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. // 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.Diagnostics.CodeAnalysis;
using System.IO; using System.IO;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Authentication.Twitter namespace Microsoft.AspNet.Authentication.Twitter
{ {
@ -56,8 +56,18 @@ namespace Microsoft.AspNet.Authentication.Twitter
/// </summary> /// </summary>
/// <param name="writer">The writer to use in writing the token</param> /// <param name="writer">The writer to use in writing the token</param>
/// <param name="token">The token to write</param> /// <param name="token">The token to write</param>
public static void Write([NotNull] BinaryWriter writer, [NotNull] RequestToken token) public static void Write(BinaryWriter writer, RequestToken token)
{ {
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
if (token == null)
{
throw new ArgumentNullException(nameof(token));
}
writer.Write(FormatVersion); writer.Write(FormatVersion);
writer.Write(token.Token); writer.Write(token.Token);
writer.Write(token.TokenSecret); writer.Write(token.TokenSecret);
@ -70,8 +80,13 @@ namespace Microsoft.AspNet.Authentication.Twitter
/// </summary> /// </summary>
/// <param name="reader">The reader to use in reading the token bytes</param> /// <param name="reader">The reader to use in reading the token bytes</param>
/// <returns>The token</returns> /// <returns>The token</returns>
public static RequestToken Read([NotNull] BinaryReader reader) public static RequestToken Read(BinaryReader reader)
{ {
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
if (reader.ReadInt32() != FormatVersion) if (reader.ReadInt32() != FormatVersion)
{ {
return null; return null;

View File

@ -3,7 +3,6 @@
using System; using System;
using Microsoft.AspNet.Authentication.Twitter; using Microsoft.AspNet.Authentication.Twitter;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Builder namespace Microsoft.AspNet.Builder
{ {
@ -12,8 +11,13 @@ namespace Microsoft.AspNet.Builder
/// </summary> /// </summary>
public static class TwitterAppBuilderExtensions public static class TwitterAppBuilderExtensions
{ {
public static IApplicationBuilder UseTwitterAuthentication([NotNull] this IApplicationBuilder app, Action<TwitterOptions> configureOptions = null) public static IApplicationBuilder UseTwitterAuthentication(this IApplicationBuilder app, Action<TwitterOptions> configureOptions = null)
{ {
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
var options = new TwitterOptions(); var options = new TwitterOptions();
if (configureOptions != null) if (configureOptions != null)
{ {
@ -22,8 +26,18 @@ namespace Microsoft.AspNet.Builder
return app.UseTwitterAuthentication(options); return app.UseTwitterAuthentication(options);
} }
public static IApplicationBuilder UseTwitterAuthentication([NotNull] this IApplicationBuilder app, [NotNull] TwitterOptions options) public static IApplicationBuilder UseTwitterAuthentication(this IApplicationBuilder app, TwitterOptions options)
{ {
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
return app.UseMiddleware<TwitterMiddleware>(options); return app.UseMiddleware<TwitterMiddleware>(options);
} }

View File

@ -14,7 +14,6 @@ using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.Http.Features.Authentication; using Microsoft.AspNet.Http.Features.Authentication;
using Microsoft.AspNet.Http.Internal; using Microsoft.AspNet.Http.Internal;
using Microsoft.AspNet.WebUtilities; using Microsoft.AspNet.WebUtilities;
using Microsoft.Framework.Internal;
using Microsoft.Framework.Logging; using Microsoft.Framework.Logging;
using Microsoft.Framework.Primitives; using Microsoft.Framework.Primitives;
@ -91,7 +90,7 @@ namespace Microsoft.AspNet.Authentication.Twitter
Response.Cookies.Delete(StateCookie, cookieOptions); Response.Cookies.Delete(StateCookie, cookieOptions);
var accessToken = await ObtainAccessTokenAsync(Options.ConsumerKey, Options.ConsumerSecret, requestToken, oauthVerifier); var accessToken = await ObtainAccessTokenAsync(Options.ConsumerKey, Options.ConsumerSecret, requestToken, oauthVerifier);
var identity = new ClaimsIdentity(new[] var identity = new ClaimsIdentity(new[]
{ {
new Claim(ClaimTypes.NameIdentifier, accessToken.UserId, ClaimValueTypes.String, Options.ClaimsIssuer), new Claim(ClaimTypes.NameIdentifier, accessToken.UserId, ClaimValueTypes.String, Options.ClaimsIssuer),
@ -105,7 +104,7 @@ namespace Microsoft.AspNet.Authentication.Twitter
{ {
identity.AddClaim(new Claim("access_token", accessToken.Token, ClaimValueTypes.String, Options.ClaimsIssuer)); identity.AddClaim(new Claim("access_token", accessToken.Token, ClaimValueTypes.String, Options.ClaimsIssuer));
} }
return await CreateTicketAsync(identity, properties, accessToken); return await CreateTicketAsync(identity, properties, accessToken);
} }
catch (Exception ex) catch (Exception ex)
@ -124,7 +123,7 @@ namespace Microsoft.AspNet.Authentication.Twitter
}; };
await Options.Events.CreatingTicket(context); await Options.Events.CreatingTicket(context);
if (context.Principal?.Identity == null) if (context.Principal?.Identity == null)
{ {
return null; return null;
@ -133,8 +132,13 @@ namespace Microsoft.AspNet.Authentication.Twitter
return new AuthenticationTicket(context.Principal, context.Properties, Options.AuthenticationScheme); return new AuthenticationTicket(context.Principal, context.Properties, Options.AuthenticationScheme);
} }
protected override async Task<bool> HandleUnauthorizedAsync([NotNull] ChallengeContext context) protected override async Task<bool> HandleUnauthorizedAsync(ChallengeContext context)
{ {
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var properties = new AuthenticationProperties(context.Properties); var properties = new AuthenticationProperties(context.Properties);
if (string.IsNullOrEmpty(properties.RedirectUri)) if (string.IsNullOrEmpty(properties.RedirectUri))
{ {

View File

@ -7,7 +7,6 @@ using System.Globalization;
using System.Net.Http; using System.Net.Http;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.DataProtection; using Microsoft.AspNet.DataProtection;
using Microsoft.Framework.Internal;
using Microsoft.Framework.Logging; using Microsoft.Framework.Logging;
using Microsoft.Framework.OptionsModel; using Microsoft.Framework.OptionsModel;
using Microsoft.Framework.WebEncoders; using Microsoft.Framework.WebEncoders;
@ -33,14 +32,44 @@ namespace Microsoft.AspNet.Authentication.Twitter
/// <param name="options">Configuration options for the middleware</param> /// <param name="options">Configuration options for the middleware</param>
/// <param name="configureOptions"></param> /// <param name="configureOptions"></param>
public TwitterMiddleware( public TwitterMiddleware(
[NotNull] RequestDelegate next, RequestDelegate next,
[NotNull] IDataProtectionProvider dataProtectionProvider, IDataProtectionProvider dataProtectionProvider,
[NotNull] ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
[NotNull] IUrlEncoder encoder, IUrlEncoder encoder,
[NotNull] IOptions<SharedAuthenticationOptions> sharedOptions, IOptions<SharedAuthenticationOptions> sharedOptions,
[NotNull] TwitterOptions options) TwitterOptions options)
: base(next, options, loggerFactory, encoder) : base(next, options, loggerFactory, encoder)
{ {
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
if (dataProtectionProvider == null)
{
throw new ArgumentNullException(nameof(dataProtectionProvider));
}
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
if (encoder == null)
{
throw new ArgumentNullException(nameof(encoder));
}
if (sharedOptions == null)
{
throw new ArgumentNullException(nameof(sharedOptions));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (string.IsNullOrEmpty(Options.ConsumerSecret)) if (string.IsNullOrEmpty(Options.ConsumerSecret))
{ {
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, nameof(Options.ConsumerSecret))); throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, nameof(Options.ConsumerSecret)));

View File

@ -5,9 +5,11 @@
"type": "git", "type": "git",
"url": "git://github.com/aspnet/security" "url": "git://github.com/aspnet/security"
}, },
"compilationOptions": {
"warningsAsErrors": true
},
"dependencies": { "dependencies": {
"Microsoft.AspNet.Authentication": "1.0.0-*", "Microsoft.AspNet.Authentication": "1.0.0-*"
"Microsoft.Framework.NotNullAttribute.Sources": { "type": "build", "version": "1.0.0-*" }
}, },
"frameworks": { "frameworks": {
"dnx451": { "dnx451": {

View File

@ -63,8 +63,28 @@ namespace Microsoft.AspNet.Authentication
/// <param name="context">The utility object to observe the current request and response</param> /// <param name="context">The utility object to observe the current request and response</param>
/// <param name="logger">The logging factory used to create loggers</param> /// <param name="logger">The logging factory used to create loggers</param>
/// <returns>async completion</returns> /// <returns>async completion</returns>
public async Task InitializeAsync([NotNull] TOptions options, [NotNull] HttpContext context, [NotNull] ILogger logger, [NotNull] IUrlEncoder encoder) public async Task InitializeAsync(TOptions options, HttpContext context, ILogger logger, IUrlEncoder encoder)
{ {
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
if (encoder == null)
{
throw new ArgumentNullException(nameof(encoder));
}
Options = options; Options = options;
Context = context; Context = context;
OriginalPathBase = Request.PathBase; OriginalPathBase = Request.PathBase;

View File

@ -5,7 +5,6 @@ using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.Framework.Internal;
using Microsoft.Framework.Logging; using Microsoft.Framework.Logging;
using Microsoft.Framework.WebEncoders; using Microsoft.Framework.WebEncoders;
@ -16,11 +15,31 @@ namespace Microsoft.AspNet.Authentication
private readonly RequestDelegate _next; private readonly RequestDelegate _next;
protected AuthenticationMiddleware( protected AuthenticationMiddleware(
[NotNull] RequestDelegate next, RequestDelegate next,
[NotNull] TOptions options, TOptions options,
[NotNull] ILoggerFactory loggerFactory, ILoggerFactory loggerFactory,
[NotNull] IUrlEncoder encoder) IUrlEncoder encoder)
{ {
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
if (encoder == null)
{
throw new ArgumentNullException(nameof(encoder));
}
Options = options; Options = options;
Logger = loggerFactory.CreateLogger(this.GetType().FullName); Logger = loggerFactory.CreateLogger(this.GetType().FullName);
UrlEncoder = encoder; UrlEncoder = encoder;

View File

@ -3,21 +3,35 @@
using System; using System;
using Microsoft.AspNet.Authentication; using Microsoft.AspNet.Authentication;
using Microsoft.Framework.Internal;
namespace Microsoft.Framework.DependencyInjection namespace Microsoft.Framework.DependencyInjection
{ {
public static class AuthenticationServiceCollectionExtensions public static class AuthenticationServiceCollectionExtensions
{ {
public static IServiceCollection AddAuthentication([NotNull] this IServiceCollection services) public static IServiceCollection AddAuthentication(this IServiceCollection services)
{ {
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
services.AddWebEncoders(); services.AddWebEncoders();
services.AddDataProtection(); services.AddDataProtection();
return services; return services;
} }
public static IServiceCollection AddAuthentication([NotNull] this IServiceCollection services, [NotNull] Action<SharedAuthenticationOptions> configureOptions) public static IServiceCollection AddAuthentication(this IServiceCollection services, Action<SharedAuthenticationOptions> configureOptions)
{ {
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if (configureOptions == null)
{
throw new ArgumentNullException(nameof(configureOptions));
}
services.Configure(configureOptions); services.Configure(configureOptions);
return services.AddAuthentication(); return services.AddAuthentication();
} }

View File

@ -1,10 +1,10 @@
// 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. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Authentication namespace Microsoft.AspNet.Authentication
{ {
@ -13,9 +13,19 @@ namespace Microsoft.AspNet.Authentication
private readonly RequestDelegate _next; private readonly RequestDelegate _next;
public ClaimsTransformationMiddleware( public ClaimsTransformationMiddleware(
[NotNull] RequestDelegate next, RequestDelegate next,
[NotNull] ClaimsTransformationOptions options) ClaimsTransformationOptions options)
{ {
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
Options = options; Options = options;
_next = next; _next = next;
} }
@ -26,7 +36,8 @@ namespace Microsoft.AspNet.Authentication
{ {
var handler = new ClaimsTransformationHandler(Options.Transformer); var handler = new ClaimsTransformationHandler(Options.Transformer);
handler.RegisterAuthenticationHandler(context.GetAuthentication()); handler.RegisterAuthenticationHandler(context.GetAuthentication());
try { try
{
if (Options.Transformer != null) if (Options.Transformer != null)
{ {
context.User = await Options.Transformer.TransformAsync(context.User); context.User = await Options.Transformer.TransformAsync(context.User);

View File

@ -1,11 +1,11 @@
// 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. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.IO; using System.IO;
using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Authentication;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Authentication namespace Microsoft.AspNet.Authentication
{ {
@ -41,8 +41,18 @@ namespace Microsoft.AspNet.Authentication
} }
} }
public virtual void Write([NotNull] BinaryWriter writer, [NotNull] AuthenticationProperties properties) public virtual void Write(BinaryWriter writer, AuthenticationProperties properties)
{ {
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
if (properties == null)
{
throw new ArgumentNullException(nameof(properties));
}
writer.Write(FormatVersion); writer.Write(FormatVersion);
writer.Write(properties.Items.Count); writer.Write(properties.Items.Count);
@ -53,8 +63,13 @@ namespace Microsoft.AspNet.Authentication
} }
} }
public virtual AuthenticationProperties Read([NotNull] BinaryReader reader) public virtual AuthenticationProperties Read(BinaryReader reader)
{ {
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
if (reader.ReadInt32() != FormatVersion) if (reader.ReadInt32() != FormatVersion)
{ {
return null; return null;

View File

@ -5,7 +5,6 @@ using System;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Authentication namespace Microsoft.AspNet.Authentication
{ {
@ -39,8 +38,18 @@ namespace Microsoft.AspNet.Authentication
} }
} }
public virtual void Write([NotNull] BinaryWriter writer, [NotNull] AuthenticationTicket ticket) public virtual void Write(BinaryWriter writer, AuthenticationTicket ticket)
{ {
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
if (ticket == null)
{
throw new ArgumentNullException(nameof(ticket));
}
writer.Write(FormatVersion); writer.Write(FormatVersion);
writer.Write(ticket.AuthenticationScheme); writer.Write(ticket.AuthenticationScheme);
@ -61,8 +70,18 @@ namespace Microsoft.AspNet.Authentication
PropertiesSerializer.Default.Write(writer, ticket.Properties); PropertiesSerializer.Default.Write(writer, ticket.Properties);
} }
protected virtual void WriteIdentity([NotNull] BinaryWriter writer, [NotNull] ClaimsIdentity identity) protected virtual void WriteIdentity(BinaryWriter writer, ClaimsIdentity identity)
{ {
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
if (identity == null)
{
throw new ArgumentNullException(nameof(identity));
}
var authenticationType = identity.AuthenticationType ?? string.Empty; var authenticationType = identity.AuthenticationType ?? string.Empty;
writer.Write(authenticationType); writer.Write(authenticationType);
@ -99,8 +118,18 @@ namespace Microsoft.AspNet.Authentication
} }
} }
protected virtual void WriteClaim([NotNull] BinaryWriter writer, [NotNull] Claim claim) protected virtual void WriteClaim(BinaryWriter writer, Claim claim)
{ {
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
if (claim == null)
{
throw new ArgumentNullException(nameof(claim));
}
WriteWithDefault(writer, claim.Type, claim.Subject?.NameClaimType ?? ClaimsIdentity.DefaultNameClaimType); WriteWithDefault(writer, claim.Type, claim.Subject?.NameClaimType ?? ClaimsIdentity.DefaultNameClaimType);
writer.Write(claim.Value); writer.Write(claim.Value);
WriteWithDefault(writer, claim.ValueType, ClaimValueTypes.String); WriteWithDefault(writer, claim.ValueType, ClaimValueTypes.String);
@ -117,8 +146,13 @@ namespace Microsoft.AspNet.Authentication
} }
} }
public virtual AuthenticationTicket Read([NotNull] BinaryReader reader) public virtual AuthenticationTicket Read(BinaryReader reader)
{ {
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
if (reader.ReadInt32() != FormatVersion) if (reader.ReadInt32() != FormatVersion)
{ {
return null; return null;
@ -145,8 +179,13 @@ namespace Microsoft.AspNet.Authentication
return new AuthenticationTicket(new ClaimsPrincipal(identities), properties, scheme); return new AuthenticationTicket(new ClaimsPrincipal(identities), properties, scheme);
} }
protected virtual ClaimsIdentity ReadIdentity([NotNull] BinaryReader reader) protected virtual ClaimsIdentity ReadIdentity(BinaryReader reader)
{ {
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
var authenticationType = reader.ReadString(); var authenticationType = reader.ReadString();
var nameClaimType = ReadWithDefault(reader, ClaimsIdentity.DefaultNameClaimType); var nameClaimType = ReadWithDefault(reader, ClaimsIdentity.DefaultNameClaimType);
var roleClaimType = ReadWithDefault(reader, ClaimsIdentity.DefaultRoleClaimType); var roleClaimType = ReadWithDefault(reader, ClaimsIdentity.DefaultRoleClaimType);
@ -181,8 +220,18 @@ namespace Microsoft.AspNet.Authentication
return identity; return identity;
} }
protected virtual Claim ReadClaim([NotNull] BinaryReader reader, [NotNull] ClaimsIdentity identity) protected virtual Claim ReadClaim(BinaryReader reader, ClaimsIdentity identity)
{ {
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
if (identity == null)
{
throw new ArgumentNullException(nameof(identity));
}
var type = ReadWithDefault(reader, identity.NameClaimType); var type = ReadWithDefault(reader, identity.NameClaimType);
var value = reader.ReadString(); var value = reader.ReadString();
var valueType = ReadWithDefault(reader, ClaimValueTypes.String); var valueType = ReadWithDefault(reader, ClaimValueTypes.String);
@ -193,7 +242,7 @@ namespace Microsoft.AspNet.Authentication
// Read the number of properties stored in the claim. // Read the number of properties stored in the claim.
var count = reader.ReadInt32(); var count = reader.ReadInt32();
for (var index = 0; index != count; ++index) for (var index = 0; index != count; ++index)
{ {
var key = reader.ReadString(); var key = reader.ReadString();

View File

@ -5,12 +5,14 @@
"type": "git", "type": "git",
"url": "git://github.com/aspnet/security" "url": "git://github.com/aspnet/security"
}, },
"compilationOptions": {
"warningsAsErrors": true
},
"dependencies": { "dependencies": {
"Microsoft.AspNet.DataProtection": "1.0.0-*", "Microsoft.AspNet.DataProtection": "1.0.0-*",
"Microsoft.AspNet.Http": "1.0.0-*", "Microsoft.AspNet.Http": "1.0.0-*",
"Microsoft.AspNet.Http.Extensions": "1.0.0-*", "Microsoft.AspNet.Http.Extensions": "1.0.0-*",
"Microsoft.Framework.Logging.Abstractions": "1.0.0-*", "Microsoft.Framework.Logging.Abstractions": "1.0.0-*",
"Microsoft.Framework.NotNullAttribute.Sources": { "type": "build", "version": "1.0.0-*" },
"Microsoft.Framework.SecurityHelper.Sources": { "type": "build", "version": "1.0.0-*" }, "Microsoft.Framework.SecurityHelper.Sources": { "type": "build", "version": "1.0.0-*" },
"Microsoft.Framework.OptionsModel": "1.0.0-*", "Microsoft.Framework.OptionsModel": "1.0.0-*",
"Microsoft.Framework.WebEncoders": "1.0.0-*" "Microsoft.Framework.WebEncoders": "1.0.0-*"

View File

@ -1,10 +1,10 @@
// 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. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Authorization namespace Microsoft.AspNet.Authorization
{ {
@ -18,10 +18,15 @@ namespace Microsoft.AspNet.Authorization
private bool _succeedCalled; private bool _succeedCalled;
public AuthorizationContext( public AuthorizationContext(
[NotNull] IEnumerable<IAuthorizationRequirement> requirements, IEnumerable<IAuthorizationRequirement> requirements,
ClaimsPrincipal user, ClaimsPrincipal user,
object resource) object resource)
{ {
if (requirements == null)
{
throw new ArgumentNullException(nameof(requirements));
}
Requirements = requirements; Requirements = requirements;
User = user; User = user;
Resource = resource; Resource = resource;
@ -36,7 +41,8 @@ namespace Microsoft.AspNet.Authorization
public bool HasFailed { get { return _failCalled; } } public bool HasFailed { get { return _failCalled; } }
public bool HasSucceeded { public bool HasSucceeded
{
get get
{ {
return !_failCalled && _succeedCalled && !PendingRequirements.Any(); return !_failCalled && _succeedCalled && !PendingRequirements.Any();

View File

@ -3,7 +3,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Authorization namespace Microsoft.AspNet.Authorization
{ {
@ -16,21 +15,46 @@ namespace Microsoft.AspNet.Authorization
/// </summary> /// </summary>
public AuthorizationPolicy DefaultPolicy { get; set; } = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build(); public AuthorizationPolicy DefaultPolicy { get; set; } = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
public void AddPolicy([NotNull] string name, [NotNull] AuthorizationPolicy policy) public void AddPolicy(string name, AuthorizationPolicy policy)
{ {
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (policy == null)
{
throw new ArgumentNullException(nameof(policy));
}
PolicyMap[name] = policy; PolicyMap[name] = policy;
} }
public void AddPolicy([NotNull] string name, [NotNull] Action<AuthorizationPolicyBuilder> configurePolicy) public void AddPolicy(string name, Action<AuthorizationPolicyBuilder> configurePolicy)
{ {
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (configurePolicy == null)
{
throw new ArgumentNullException(nameof(configurePolicy));
}
var policyBuilder = new AuthorizationPolicyBuilder(); var policyBuilder = new AuthorizationPolicyBuilder();
configurePolicy(policyBuilder); configurePolicy(policyBuilder);
PolicyMap[name] = policyBuilder.Build(); PolicyMap[name] = policyBuilder.Build();
} }
public AuthorizationPolicy GetPolicy([NotNull] string name) public AuthorizationPolicy GetPolicy(string name)
{ {
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
return PolicyMap.ContainsKey(name) ? PolicyMap[name] : null; return PolicyMap.ContainsKey(name) ? PolicyMap[name] : null;
} }
} }
} }

View File

@ -4,14 +4,23 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Authorization namespace Microsoft.AspNet.Authorization
{ {
public class AuthorizationPolicy public class AuthorizationPolicy
{ {
public AuthorizationPolicy([NotNull] IEnumerable<IAuthorizationRequirement> requirements, [NotNull] IEnumerable<string> activeAuthenticationSchemes) public AuthorizationPolicy(IEnumerable<IAuthorizationRequirement> requirements, IEnumerable<string> activeAuthenticationSchemes)
{ {
if (requirements == null)
{
throw new ArgumentNullException(nameof(requirements));
}
if (activeAuthenticationSchemes == null)
{
throw new ArgumentNullException(nameof(activeAuthenticationSchemes));
}
if (requirements.Count() == 0) if (requirements.Count() == 0)
{ {
throw new InvalidOperationException(Resources.Exception_AuthorizationPolicyEmpty); throw new InvalidOperationException(Resources.Exception_AuthorizationPolicyEmpty);
@ -23,13 +32,23 @@ namespace Microsoft.AspNet.Authorization
public IReadOnlyList<IAuthorizationRequirement> Requirements { get; } public IReadOnlyList<IAuthorizationRequirement> Requirements { get; }
public IReadOnlyList<string> ActiveAuthenticationSchemes { get; } public IReadOnlyList<string> ActiveAuthenticationSchemes { get; }
public static AuthorizationPolicy Combine([NotNull] params AuthorizationPolicy[] policies) public static AuthorizationPolicy Combine(params AuthorizationPolicy[] policies)
{ {
if (policies == null)
{
throw new ArgumentNullException(nameof(policies));
}
return Combine((IEnumerable<AuthorizationPolicy>)policies); return Combine((IEnumerable<AuthorizationPolicy>)policies);
} }
public static AuthorizationPolicy Combine([NotNull] IEnumerable<AuthorizationPolicy> policies) public static AuthorizationPolicy Combine(IEnumerable<AuthorizationPolicy> policies)
{ {
if (policies == null)
{
throw new ArgumentNullException(nameof(policies));
}
var builder = new AuthorizationPolicyBuilder(); var builder = new AuthorizationPolicyBuilder();
foreach (var policy in policies) foreach (var policy in policies)
{ {
@ -38,8 +57,18 @@ namespace Microsoft.AspNet.Authorization
return builder.Build(); return builder.Build();
} }
public static AuthorizationPolicy Combine([NotNull] AuthorizationOptions options, [NotNull] IEnumerable<AuthorizeAttribute> attributes) public static AuthorizationPolicy Combine(AuthorizationOptions options, IEnumerable<AuthorizeAttribute> attributes)
{ {
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (attributes == null)
{
throw new ArgumentNullException(nameof(attributes));
}
var policyBuilder = new AuthorizationPolicyBuilder(); var policyBuilder = new AuthorizationPolicyBuilder();
var any = false; var any = false;
foreach (var authorizeAttribute in attributes.OfType<AuthorizeAttribute>()) foreach (var authorizeAttribute in attributes.OfType<AuthorizeAttribute>())

View File

@ -4,7 +4,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Authorization namespace Microsoft.AspNet.Authorization
{ {
@ -41,43 +40,78 @@ namespace Microsoft.AspNet.Authorization
return this; return this;
} }
public AuthorizationPolicyBuilder Combine([NotNull] AuthorizationPolicy policy) public AuthorizationPolicyBuilder Combine(AuthorizationPolicy policy)
{ {
if (policy == null)
{
throw new ArgumentNullException(nameof(policy));
}
AddAuthenticationSchemes(policy.ActiveAuthenticationSchemes.ToArray()); AddAuthenticationSchemes(policy.ActiveAuthenticationSchemes.ToArray());
AddRequirements(policy.Requirements.ToArray()); AddRequirements(policy.Requirements.ToArray());
return this; return this;
} }
public AuthorizationPolicyBuilder RequireClaim([NotNull] string claimType, params string[] requiredValues) public AuthorizationPolicyBuilder RequireClaim(string claimType, params string[] requiredValues)
{ {
if (claimType == null)
{
throw new ArgumentNullException(nameof(claimType));
}
return RequireClaim(claimType, (IEnumerable<string>)requiredValues); return RequireClaim(claimType, (IEnumerable<string>)requiredValues);
} }
public AuthorizationPolicyBuilder RequireClaim([NotNull] string claimType, IEnumerable<string> requiredValues) public AuthorizationPolicyBuilder RequireClaim(string claimType, IEnumerable<string> requiredValues)
{ {
if (claimType == null)
{
throw new ArgumentNullException(nameof(claimType));
}
Requirements.Add(new ClaimsAuthorizationRequirement(claimType, requiredValues)); Requirements.Add(new ClaimsAuthorizationRequirement(claimType, requiredValues));
return this; return this;
} }
public AuthorizationPolicyBuilder RequireClaim([NotNull] string claimType) public AuthorizationPolicyBuilder RequireClaim(string claimType)
{ {
if (claimType == null)
{
throw new ArgumentNullException(nameof(claimType));
}
Requirements.Add(new ClaimsAuthorizationRequirement(claimType, allowedValues: null)); Requirements.Add(new ClaimsAuthorizationRequirement(claimType, allowedValues: null));
return this; return this;
} }
public AuthorizationPolicyBuilder RequireRole([NotNull] params string[] roles) public AuthorizationPolicyBuilder RequireRole(params string[] roles)
{ {
if (roles == null)
{
throw new ArgumentNullException(nameof(roles));
}
return RequireRole((IEnumerable<string>)roles); return RequireRole((IEnumerable<string>)roles);
} }
public AuthorizationPolicyBuilder RequireRole([NotNull] IEnumerable<string> roles) public AuthorizationPolicyBuilder RequireRole(IEnumerable<string> roles)
{ {
if (roles == null)
{
throw new ArgumentNullException(nameof(roles));
}
Requirements.Add(new RolesAuthorizationRequirement(roles)); Requirements.Add(new RolesAuthorizationRequirement(roles));
return this; return this;
} }
public AuthorizationPolicyBuilder RequireUserName([NotNull] string userName) public AuthorizationPolicyBuilder RequireUserName(string userName)
{ {
if (userName == null)
{
throw new ArgumentNullException(nameof(userName));
}
Requirements.Add(new NameAuthorizationRequirement(userName)); Requirements.Add(new NameAuthorizationRequirement(userName));
return this; return this;
} }
@ -88,8 +122,13 @@ namespace Microsoft.AspNet.Authorization
return this; return this;
} }
public AuthorizationPolicyBuilder RequireDelegate([NotNull] Action<AuthorizationContext, DelegateRequirement> handler) public AuthorizationPolicyBuilder RequireDelegate(Action<AuthorizationContext, DelegateRequirement> handler)
{ {
if (handler == null)
{
throw new ArgumentNullException(nameof(handler));
}
Requirements.Add(new DelegateRequirement(handler)); Requirements.Add(new DelegateRequirement(handler));
return this; return this;
} }

View File

@ -4,22 +4,36 @@
using System; using System;
using Microsoft.AspNet.Authorization; using Microsoft.AspNet.Authorization;
using Microsoft.Framework.DependencyInjection.Extensions; using Microsoft.Framework.DependencyInjection.Extensions;
using Microsoft.Framework.Internal;
namespace Microsoft.Framework.DependencyInjection namespace Microsoft.Framework.DependencyInjection
{ {
public static class AuthorizationServiceCollectionExtensions public static class AuthorizationServiceCollectionExtensions
{ {
public static IServiceCollection AddAuthorization([NotNull] this IServiceCollection services) public static IServiceCollection AddAuthorization(this IServiceCollection services)
{ {
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
services.AddOptions(); services.AddOptions();
services.TryAdd(ServiceDescriptor.Transient<IAuthorizationService, DefaultAuthorizationService>()); services.TryAdd(ServiceDescriptor.Transient<IAuthorizationService, DefaultAuthorizationService>());
services.TryAddEnumerable(ServiceDescriptor.Transient<IAuthorizationHandler, PassThroughAuthorizationHandler>()); services.TryAddEnumerable(ServiceDescriptor.Transient<IAuthorizationHandler, PassThroughAuthorizationHandler>());
return services; return services;
} }
public static IServiceCollection AddAuthorization([NotNull] this IServiceCollection services, [NotNull] Action<AuthorizationOptions> configure) public static IServiceCollection AddAuthorization(this IServiceCollection services, Action<AuthorizationOptions> configure)
{ {
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if (configure == null)
{
throw new ArgumentNullException(nameof(configure));
}
services.Configure(configure); services.Configure(configure);
return services.AddAuthorization(); return services.AddAuthorization();
} }

View File

@ -1,10 +1,10 @@
// 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. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq; using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Authorization namespace Microsoft.AspNet.Authorization
{ {
@ -17,8 +17,18 @@ namespace Microsoft.AspNet.Authorization
/// <param name="resource"></param> /// <param name="resource"></param>
/// <param name="requirement"></param> /// <param name="requirement"></param>
/// <returns></returns> /// <returns></returns>
public static Task<bool> AuthorizeAsync([NotNull] this IAuthorizationService service, ClaimsPrincipal user, object resource, [NotNull] IAuthorizationRequirement requirement) public static Task<bool> AuthorizeAsync(this IAuthorizationService service, ClaimsPrincipal user, object resource, IAuthorizationRequirement requirement)
{ {
if (service == null)
{
throw new ArgumentNullException(nameof(service));
}
if (requirement == null)
{
throw new ArgumentNullException(nameof(requirement));
}
return service.AuthorizeAsync(user, resource, new IAuthorizationRequirement[] { requirement }); return service.AuthorizeAsync(user, resource, new IAuthorizationRequirement[] { requirement });
} }
@ -30,8 +40,18 @@ namespace Microsoft.AspNet.Authorization
/// <param name="resource">The resource the policy should be checked with.</param> /// <param name="resource">The resource the policy should be checked with.</param>
/// <param name="policy">The policy to check against a specific context.</param> /// <param name="policy">The policy to check against a specific context.</param>
/// <returns><value>true</value> when the user fulfills the policy, <value>false</value> otherwise.</returns> /// <returns><value>true</value> when the user fulfills the policy, <value>false</value> otherwise.</returns>
public static Task<bool> AuthorizeAsync([NotNull] this IAuthorizationService service, ClaimsPrincipal user, object resource, [NotNull] AuthorizationPolicy policy) public static Task<bool> AuthorizeAsync(this IAuthorizationService service, ClaimsPrincipal user, object resource, AuthorizationPolicy policy)
{ {
if (service == null)
{
throw new ArgumentNullException(nameof(service));
}
if (policy == null)
{
throw new ArgumentNullException(nameof(policy));
}
return service.AuthorizeAsync(user, resource, policy.Requirements.ToArray()); return service.AuthorizeAsync(user, resource, policy.Requirements.ToArray());
} }
@ -42,8 +62,18 @@ namespace Microsoft.AspNet.Authorization
/// <param name="user">The user to check the policy against.</param> /// <param name="user">The user to check the policy against.</param>
/// <param name="policy">The policy to check against a specific context.</param> /// <param name="policy">The policy to check against a specific context.</param>
/// <returns><value>true</value> when the user fulfills the policy, <value>false</value> otherwise.</returns> /// <returns><value>true</value> when the user fulfills the policy, <value>false</value> otherwise.</returns>
public static Task<bool> AuthorizeAsync([NotNull] this IAuthorizationService service, ClaimsPrincipal user, [NotNull] AuthorizationPolicy policy) public static Task<bool> AuthorizeAsync(this IAuthorizationService service, ClaimsPrincipal user, AuthorizationPolicy policy)
{ {
if (service == null)
{
throw new ArgumentNullException(nameof(service));
}
if (policy == null)
{
throw new ArgumentNullException(nameof(policy));
}
return service.AuthorizeAsync(user, resource: null, policy: policy); return service.AuthorizeAsync(user, resource: null, policy: policy);
} }
@ -54,8 +84,18 @@ namespace Microsoft.AspNet.Authorization
/// <param name="user">The user to check the policy against.</param> /// <param name="user">The user to check the policy against.</param>
/// <param name="policyName">The name of the policy to check against a specific context.</param> /// <param name="policyName">The name of the policy to check against a specific context.</param>
/// <returns><value>true</value> when the user fulfills the policy, <value>false</value> otherwise.</returns> /// <returns><value>true</value> when the user fulfills the policy, <value>false</value> otherwise.</returns>
public static Task<bool> AuthorizeAsync([NotNull] this IAuthorizationService service, ClaimsPrincipal user, [NotNull] string policyName) public static Task<bool> AuthorizeAsync(this IAuthorizationService service, ClaimsPrincipal user, string policyName)
{ {
if (service == null)
{
throw new ArgumentNullException(nameof(service));
}
if (policyName == null)
{
throw new ArgumentNullException(nameof(policyName));
}
return service.AuthorizeAsync(user, resource: null, policyName: policyName); return service.AuthorizeAsync(user, resource: null, policyName: policyName);
} }
} }

View File

@ -4,7 +4,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Authorization namespace Microsoft.AspNet.Authorization
{ {
@ -12,8 +11,13 @@ namespace Microsoft.AspNet.Authorization
// If AllowedValues is null or empty, that means any claim is valid // If AllowedValues is null or empty, that means any claim is valid
public class ClaimsAuthorizationRequirement : AuthorizationHandler<ClaimsAuthorizationRequirement>, IAuthorizationRequirement public class ClaimsAuthorizationRequirement : AuthorizationHandler<ClaimsAuthorizationRequirement>, IAuthorizationRequirement
{ {
public ClaimsAuthorizationRequirement([NotNull] string claimType, IEnumerable<string> allowedValues) public ClaimsAuthorizationRequirement(string claimType, IEnumerable<string> allowedValues)
{ {
if (claimType == null)
{
throw new ArgumentNullException(nameof(claimType));
}
ClaimType = claimType; ClaimType = claimType;
AllowedValues = allowedValues; AllowedValues = allowedValues;
} }

View File

@ -1,11 +1,11 @@
// 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. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Framework.Internal;
using Microsoft.Framework.OptionsModel; using Microsoft.Framework.OptionsModel;
namespace Microsoft.AspNet.Authorization namespace Microsoft.AspNet.Authorization
@ -21,8 +21,13 @@ namespace Microsoft.AspNet.Authorization
_options = options.Value; _options = options.Value;
} }
public async Task<bool> AuthorizeAsync(ClaimsPrincipal user, object resource, [NotNull] IEnumerable<IAuthorizationRequirement> requirements) public async Task<bool> AuthorizeAsync(ClaimsPrincipal user, object resource, IEnumerable<IAuthorizationRequirement> requirements)
{ {
if (requirements == null)
{
throw new ArgumentNullException(nameof(requirements));
}
var authContext = new AuthorizationContext(requirements, user, resource); var authContext = new AuthorizationContext(requirements, user, resource);
foreach (var handler in _handlers) foreach (var handler in _handlers)
{ {
@ -33,6 +38,11 @@ namespace Microsoft.AspNet.Authorization
public Task<bool> AuthorizeAsync(ClaimsPrincipal user, object resource, string policyName) public Task<bool> AuthorizeAsync(ClaimsPrincipal user, object resource, string policyName)
{ {
if (policyName == null)
{
throw new ArgumentNullException(nameof(policyName));
}
var policy = _options.GetPolicy(policyName); var policy = _options.GetPolicy(policyName);
return (policy == null) return (policy == null)
? Task.FromResult(false) ? Task.FromResult(false)

View File

@ -4,7 +4,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Security.Claims; using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Authorization namespace Microsoft.AspNet.Authorization
{ {
@ -20,7 +19,7 @@ namespace Microsoft.AspNet.Authorization
/// <param name="resource"></param> /// <param name="resource"></param>
/// <param name="requirements"></param> /// <param name="requirements"></param>
/// <returns></returns> /// <returns></returns>
Task<bool> AuthorizeAsync(ClaimsPrincipal user, object resource, [NotNull] IEnumerable<IAuthorizationRequirement> requirements); Task<bool> AuthorizeAsync(ClaimsPrincipal user, object resource, IEnumerable<IAuthorizationRequirement> requirements);
/// <summary> /// <summary>
/// Checks if a user meets a specific authorization policy /// Checks if a user meets a specific authorization policy
@ -29,6 +28,6 @@ namespace Microsoft.AspNet.Authorization
/// <param name="resource">The resource the policy should be checked with.</param> /// <param name="resource">The resource the policy should be checked with.</param>
/// <param name="policyName">The name of the policy to check against a specific context.</param> /// <param name="policyName">The name of the policy to check against a specific context.</param>
/// <returns><value>true</value> when the user fulfills the policy, <value>false</value> otherwise.</returns> /// <returns><value>true</value> when the user fulfills the policy, <value>false</value> otherwise.</returns>
Task<bool> AuthorizeAsync(ClaimsPrincipal user, object resource, [NotNull] string policyName); Task<bool> AuthorizeAsync(ClaimsPrincipal user, object resource, string policyName);
} }
} }

View File

@ -2,9 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Authorization namespace Microsoft.AspNet.Authorization
{ {
@ -13,8 +11,13 @@ namespace Microsoft.AspNet.Authorization
/// </summary> /// </summary>
public class NameAuthorizationRequirement : AuthorizationHandler<NameAuthorizationRequirement>, IAuthorizationRequirement public class NameAuthorizationRequirement : AuthorizationHandler<NameAuthorizationRequirement>, IAuthorizationRequirement
{ {
public NameAuthorizationRequirement([NotNull] string requiredName) public NameAuthorizationRequirement(string requiredName)
{ {
if (requiredName == null)
{
throw new ArgumentNullException(nameof(requiredName));
}
RequiredName = requiredName; RequiredName = requiredName;
} }

View File

@ -4,7 +4,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Authorization namespace Microsoft.AspNet.Authorization
{ {
@ -12,8 +11,13 @@ namespace Microsoft.AspNet.Authorization
// If AllowedRoles is null or empty, that means any role is valid // If AllowedRoles is null or empty, that means any role is valid
public class RolesAuthorizationRequirement : AuthorizationHandler<RolesAuthorizationRequirement>, IAuthorizationRequirement public class RolesAuthorizationRequirement : AuthorizationHandler<RolesAuthorizationRequirement>, IAuthorizationRequirement
{ {
public RolesAuthorizationRequirement([NotNull] IEnumerable<string> allowedRoles) public RolesAuthorizationRequirement(IEnumerable<string> allowedRoles)
{ {
if (allowedRoles == null)
{
throw new ArgumentNullException(nameof(allowedRoles));
}
if (allowedRoles.Count() == 0) if (allowedRoles.Count() == 0)
{ {
throw new InvalidOperationException(Resources.Exception_RoleRequirementEmpty); throw new InvalidOperationException(Resources.Exception_RoleRequirementEmpty);

View File

@ -5,10 +5,12 @@
"type": "git", "type": "git",
"url": "git://github.com/aspnet/security" "url": "git://github.com/aspnet/security"
}, },
"compilationOptions": {
"warningsAsErrors": true
},
"dependencies": { "dependencies": {
"Microsoft.AspNet.Http.Features": "1.0.0-*", "Microsoft.AspNet.Http.Features": "1.0.0-*",
"Microsoft.Framework.Logging.Abstractions": "1.0.0-*", "Microsoft.Framework.Logging.Abstractions": "1.0.0-*",
"Microsoft.Framework.NotNullAttribute.Sources": { "type": "build", "version": "1.0.0-*" },
"Microsoft.Framework.OptionsModel": "1.0.0-*" "Microsoft.Framework.OptionsModel": "1.0.0-*"
}, },
"frameworks": { "frameworks": {

View File

@ -5,6 +5,9 @@
"type": "git", "type": "git",
"url": "git://github.com/aspnet/security" "url": "git://github.com/aspnet/security"
}, },
"compilationOptions": {
"warningsAsErrors": true
},
"dependencies": { "dependencies": {
"Microsoft.AspNet.Http": "1.0.0-*" "Microsoft.AspNet.Http": "1.0.0-*"
}, },