From 6611a6d4dad9c192aa88448e78e96a2112eab3b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcin=20Sm=C3=B3=C5=82ka?= Date: Tue, 29 Aug 2017 14:01:43 +0200 Subject: [PATCH] Upgrade for ASP Core 2.0 --- README.md | 73 +++++++-------- .../BasicAuthenticationExtensions.cs | 88 +++++++++++++++++++ .../BasicAuthenticationHandler.cs | 74 ++++++++++------ .../BasicAuthenticationMiddleware.cs | 62 ------------- .../BasicAuthenticationOptions.cs | 37 +++----- .../ApplicationBuilderExtensions.cs | 59 ------------- .../Events/BasicAuthenticationEvents.cs | 13 ++- .../Events/IBasicAuthenticationEvents.cs | 43 --------- .../Events/ValidatePrincipalContext.cs | 24 ++--- ...tCS.AspNetCore.Authentication.Basic.csproj | 23 ++--- .../AuthorizationTest.cs | 13 +-- .../Startup.cs | 57 ++---------- .../WebHostBuilderHelper.cs | 54 ++++++++---- ...spNetCore.Authentication.BasicTests.csproj | 27 +++--- 14 files changed, 280 insertions(+), 367 deletions(-) create mode 100644 src/ZNetCS.AspNetCore.Authentication.Basic/BasicAuthenticationExtensions.cs delete mode 100644 src/ZNetCS.AspNetCore.Authentication.Basic/BasicAuthenticationMiddleware.cs delete mode 100644 src/ZNetCS.AspNetCore.Authentication.Basic/DependecyInjection/ApplicationBuilderExtensions.cs delete mode 100644 src/ZNetCS.AspNetCore.Authentication.Basic/Events/IBasicAuthenticationEvents.cs diff --git a/README.md b/README.md index 86497df..8404626 100644 --- a/README.md +++ b/README.md @@ -19,15 +19,16 @@ When you install the package, it should be added to your `.csproj`. Alternativel ```xml - + ``` -In order to use the basic authentication middleware, you must configure the services in the `Configure` call of `Startup`. Because basic +In order to use the basic authentication middleware, you must configure the services in the `Configure` and `ConfigureServices` call of `Startup`. Because basic authentication is manual process handled on each request, there is need to validate credentials manually (see below). ```csharp -using ZNetCS.AspNetCore.Authentication.Basic.DependencyInjection; +using ZNetCS.AspNetCore.Authentication.Basic; +using ZNetCS.AspNetCore.Authentication.Basic.Events; ``` ``` @@ -35,43 +36,45 @@ using ZNetCS.AspNetCore.Authentication.Basic.DependencyInjection; ``` ```csharp - public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { - var options = new BasicAuthenticationOptions - { - Realm = "My Application", - Events = new BasicAuthenticationEvents - { - OnValidatePrincipal = context => + + // default authentication initilaization + app.UseAuthentication(); + + // other middleware e.g. MVC etc +} + +public void ConfigureServices(IServiceCollection services) +{ + services + .AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme) + .AddBasicAuthentication( + options => { - // here validation comes - if ((context.UserName == "userName") && (context.Password == "password")) + options.Realm = "My Application"; + options.Events = new BasicAuthenticationEvents { - var claims = new List + OnValidatePrincipal = context => { - new Claim(ClaimTypes.Name, context.UserName, context.Options.ClaimsIssuer) - }; - - var ticket = new AuthenticationTicket( - new ClaimsPrincipal( - new ClaimsIdentity(claims, context.Options.AuthenticationScheme)), - new AuthenticationProperties(), - context.Options.AuthenticationScheme); - - // return success result with ticket - return Task.FromResult(AuthenticateResult.Success(ticket)); - } - - // return failed result - return Task.FromResult(AuthenticateResult.Fail("Authentication failed.")); - } - } - }; - - app.UseBasicAuthentication(options); - - // other middleware e.g. MVC etc + if ((context.UserName == "userName") && (context.Password == "password")) + { + var claims = new List + { + new Claim(ClaimTypes.Name, context.UserName, context.Options.ClaimsIssuer) + }; + + var ticket = new AuthenticationTicket( + new ClaimsPrincipal(new ClaimsIdentity(claims, BasicAuthenticationDefaults.AuthenticationScheme)), + new Microsoft.AspNetCore.Authentication.AuthenticationProperties(), + BasicAuthenticationDefaults.AuthenticationScheme); + + return Task.FromResult(AuthenticateResult.Success(ticket)); + } + + return Task.FromResult(AuthenticateResult.Fail("Authentication failed.")); + }; + }); } ``` diff --git a/src/ZNetCS.AspNetCore.Authentication.Basic/BasicAuthenticationExtensions.cs b/src/ZNetCS.AspNetCore.Authentication.Basic/BasicAuthenticationExtensions.cs new file mode 100644 index 0000000..be196bc --- /dev/null +++ b/src/ZNetCS.AspNetCore.Authentication.Basic/BasicAuthenticationExtensions.cs @@ -0,0 +1,88 @@ +// -------------------------------------------------------------------------------------------------------------------- +// +// Copyright (c) Marcin Smółka zNET Computer Solutions. All rights reserved. +// +// +// The basic authentication extensions. +// +// -------------------------------------------------------------------------------------------------------------------- + +namespace ZNetCS.AspNetCore.Authentication.Basic +{ + #region Usings + + using System; + + using Microsoft.AspNetCore.Authentication; + + #endregion + + /// + /// The basic authentication extensions. + /// + public static class BasicAuthenticationExtensions + { + #region Public Methods + + /// + /// Adds basic authentication. + /// + /// + /// The authentication builder. + /// + public static AuthenticationBuilder AddBasicAuthentication(this AuthenticationBuilder builder) + { + return builder.AddBasicAuthentication(BasicAuthenticationDefaults.AuthenticationScheme); + } + + /// + /// Adds basic authentication. + /// + /// + /// The authentication builder. + /// + /// + /// The authentication scheme. + /// + public static AuthenticationBuilder AddBasicAuthentication(this AuthenticationBuilder builder, string authenticationScheme) + { + return builder.AddBasicAuthentication(authenticationScheme, null); + } + + /// + /// Adds basic authentication. + /// + /// + /// The authentication builder. + /// + /// + /// The configure options. + /// + public static AuthenticationBuilder AddBasicAuthentication(this AuthenticationBuilder builder, Action configureOptions) + { + return builder.AddBasicAuthentication(BasicAuthenticationDefaults.AuthenticationScheme, configureOptions); + } + + /// + /// Adds basic authentication. + /// + /// + /// The builder. + /// + /// + /// The authentication scheme. + /// + /// + /// The configure options. + /// + public static AuthenticationBuilder AddBasicAuthentication( + this AuthenticationBuilder builder, + string authenticationScheme, + Action configureOptions) + { + return builder.AddScheme(authenticationScheme, configureOptions); + } + + #endregion + } +} \ No newline at end of file diff --git a/src/ZNetCS.AspNetCore.Authentication.Basic/BasicAuthenticationHandler.cs b/src/ZNetCS.AspNetCore.Authentication.Basic/BasicAuthenticationHandler.cs index 61a42c2..f1cfc99 100644 --- a/src/ZNetCS.AspNetCore.Authentication.Basic/BasicAuthenticationHandler.cs +++ b/src/ZNetCS.AspNetCore.Authentication.Basic/BasicAuthenticationHandler.cs @@ -14,12 +14,13 @@ namespace ZNetCS.AspNetCore.Authentication.Basic using System; using System.Linq; using System.Text; + using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.Http.Features.Authentication; using Microsoft.Extensions.Logging; + using Microsoft.Extensions.Options; using Microsoft.Net.Http.Headers; using ZNetCS.AspNetCore.Authentication.Basic.Events; @@ -41,14 +42,45 @@ namespace ZNetCS.AspNetCore.Authentication.Basic /// public class BasicAuthenticationHandler : AuthenticationHandler { + #region Constants + /// /// The scheme name is "Basic". /// - private const string Scheme = "Basic"; + private const string Basic = "Basic"; + + #endregion + + #region Constructors and Destructors + + /// + /// Initializes a new instance of the class. + /// + /// + /// The options. + /// + /// + /// The logger. + /// + /// + /// The encoder. + /// + /// + /// The clock. + /// + public BasicAuthenticationHandler(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base( + options, + logger, + encoder, + clock) + { + } + + #endregion #region Methods - /// + /// protected override async Task HandleAuthenticateAsync() { // RFC 7230 section 3.2.2 @@ -58,19 +90,19 @@ protected override async Task HandleAuthenticateAsync() if ((authorizationHeaderValues == null) || (authorizationHeaderValues.Length == 0)) { this.Logger.LogDebug("'Authorization' header is not present in the request."); - return AuthenticateResult.Skip(); + return AuthenticateResult.NoResult(); } - var basicAuthorizationHeader = authorizationHeaderValues.FirstOrDefault(s => s.StartsWith(Scheme + ' ', StringComparison.OrdinalIgnoreCase)); + string basicAuthorizationHeader = authorizationHeaderValues.FirstOrDefault(s => s.StartsWith(Basic + ' ', StringComparison.OrdinalIgnoreCase)); // Authorization header is not 'Basic' so there is nothing to do by this middleware if (string.IsNullOrEmpty(basicAuthorizationHeader)) { this.Logger.LogDebug("'Authorization' header is not in 'Basic' scheme in the request."); - return AuthenticateResult.Skip(); + return AuthenticateResult.NoResult(); } - var credentials = basicAuthorizationHeader.Replace($"{Scheme} ", string.Empty).Trim(); + string credentials = basicAuthorizationHeader.Replace($"{Basic} ", string.Empty).Trim(); if (string.IsNullOrEmpty(credentials)) { @@ -95,35 +127,21 @@ protected override async Task HandleAuthenticateAsync() return AuthenticateResult.Fail("The credentials delimiter is not present in 'Basic' scheme."); } - var userName = decodedCredentials.Substring(0, delimiterIndex); - var password = decodedCredentials.Substring(delimiterIndex + 1); + string userName = decodedCredentials.Substring(0, delimiterIndex); + string password = decodedCredentials.Substring(delimiterIndex + 1); - var context = new ValidatePrincipalContext(this.Context, this.Options, userName, password); + var context = new ValidatePrincipalContext(this.Context, this.Scheme, this.Options, userName, password); return await this.Options.Events.ValidatePrincipal(context); } - /// - protected override Task HandleSignInAsync(SignInContext context) - { - // Basic authentication have to be resolved on every request. - throw new NotSupportedException(); - } - - /// - protected override Task HandleSignOutAsync(SignOutContext context) - { - // Basic authentication have to be resolved on every request. - throw new NotSupportedException(); - } - - /// - protected override Task HandleUnauthorizedAsync(ChallengeContext context) + /// + protected override Task HandleChallengeAsync(AuthenticationProperties context) { var realmHeader = new NameValueHeaderValue("realm", $"\"{this.Options.Realm}\""); this.Response.StatusCode = StatusCodes.Status401Unauthorized; - this.Response.Headers.Append(HeaderNames.WWWAuthenticate, $"{Scheme} {realmHeader}"); + this.Response.Headers.Append(HeaderNames.WWWAuthenticate, $"{Basic} {realmHeader}"); - return Task.FromResult(true); + return Task.CompletedTask; } #endregion diff --git a/src/ZNetCS.AspNetCore.Authentication.Basic/BasicAuthenticationMiddleware.cs b/src/ZNetCS.AspNetCore.Authentication.Basic/BasicAuthenticationMiddleware.cs deleted file mode 100644 index d86dfec..0000000 --- a/src/ZNetCS.AspNetCore.Authentication.Basic/BasicAuthenticationMiddleware.cs +++ /dev/null @@ -1,62 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) Marcin Smółka zNET Computer Solutions. All rights reserved. -// -// -// The basic authentication middleware. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ZNetCS.AspNetCore.Authentication.Basic -{ - #region Usings - - using System.Text.Encodings.Web; - - using Microsoft.AspNetCore.Authentication; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Logging; - using Microsoft.Extensions.Options; - - #endregion - - /// - /// The basic authentication middleware. - /// - public class BasicAuthenticationMiddleware : AuthenticationMiddleware - { - #region Constructors and Destructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// The next request delegate. - /// - /// - /// The logger factory. - /// - /// - /// The encoder. - /// - /// - /// The options. - /// - public BasicAuthenticationMiddleware(RequestDelegate next, ILoggerFactory loggerFactory, UrlEncoder encoder, IOptions options) - : base(next, options, loggerFactory, encoder) - { - } - - #endregion - - #region Methods - - /// - protected override AuthenticationHandler CreateHandler() - { - return new BasicAuthenticationHandler(); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/ZNetCS.AspNetCore.Authentication.Basic/BasicAuthenticationOptions.cs b/src/ZNetCS.AspNetCore.Authentication.Basic/BasicAuthenticationOptions.cs index 06c17c2..7f15b1c 100644 --- a/src/ZNetCS.AspNetCore.Authentication.Basic/BasicAuthenticationOptions.cs +++ b/src/ZNetCS.AspNetCore.Authentication.Basic/BasicAuthenticationOptions.cs @@ -3,7 +3,7 @@ // Copyright (c) Marcin Smółka zNET Computer Solutions. All rights reserved. // // -// Configuration options for . +// Configuration options for basic authentication. // // -------------------------------------------------------------------------------------------------------------------- @@ -13,17 +13,16 @@ namespace ZNetCS.AspNetCore.Authentication.Basic using System.Diagnostics.CodeAnalysis; - using Microsoft.AspNetCore.Builder; - using Microsoft.Extensions.Options; + using Microsoft.AspNetCore.Authentication; using ZNetCS.AspNetCore.Authentication.Basic.Events; #endregion /// - /// Configuration options for . + /// Configuration options for basic authentication. /// - public class BasicAuthenticationOptions : AuthenticationOptions, IOptions + public class BasicAuthenticationOptions : AuthenticationSchemeOptions { #region Constructors and Destructors @@ -32,10 +31,7 @@ public class BasicAuthenticationOptions : AuthenticationOptions, IOptions public BasicAuthenticationOptions() { - this.AuthenticationScheme = BasicAuthenticationDefaults.AuthenticationScheme; this.Realm = BasicAuthenticationDefaults.Realm; - this.AutomaticAuthenticate = true; - this.AutomaticChallenge = true; this.Events = new BasicAuthenticationEvents(); } @@ -44,10 +40,16 @@ public BasicAuthenticationOptions() #region Public Properties /// - /// Gets or sets the events that may be assigned to an instance of an object created by the application at startup time. - /// The middleware calls methods on the provider which give the application control at final authentication level. + /// Gets or sets basic authentication events. The Provider may be assigned to an instance of an object created + /// by the application at startup time. The handler calls methods on the provider which give the application + /// control at certain points where processing is occurring. If it is not provided a default instance is + /// supplied which does nothing when the methods are called. /// - public IBasicAuthenticationEvents Events { get; set; } + public new BasicAuthenticationEvents Events + { + get => (BasicAuthenticationEvents)base.Events; + set => base.Events = value; + } /// /// Gets or sets the realm. @@ -71,18 +73,5 @@ public BasicAuthenticationOptions() public string Realm { get; set; } #endregion - - #region Explicit Interface Properties - - #region IOptions - - /// - /// Gets the basic authentication options. - /// - BasicAuthenticationOptions IOptions.Value => this; - - #endregion - - #endregion } } \ No newline at end of file diff --git a/src/ZNetCS.AspNetCore.Authentication.Basic/DependecyInjection/ApplicationBuilderExtensions.cs b/src/ZNetCS.AspNetCore.Authentication.Basic/DependecyInjection/ApplicationBuilderExtensions.cs deleted file mode 100644 index 909843f..0000000 --- a/src/ZNetCS.AspNetCore.Authentication.Basic/DependecyInjection/ApplicationBuilderExtensions.cs +++ /dev/null @@ -1,59 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) Marcin Smółka zNET Computer Solutions. All rights reserved. -// -// -// Extension methods to add cookie authentication capabilities to an HTTP application pipeline. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ZNetCS.AspNetCore.Authentication.Basic.DependecyInjection -{ - #region Usings - - using System; - - using Microsoft.AspNetCore.Builder; - using Microsoft.Extensions.Options; - - #endregion - - /// - /// Extension methods to add cookie authentication capabilities to an HTTP application pipeline. - /// - public static class ApplicationBuilderExtensions - { - #region Public Methods - - /// - /// Adds the to manually configure basic authentication. - /// - /// - /// The to use basic authentication on. - /// - /// - /// The to configure the middleware with. - /// - /// - /// The so that additional calls can be chained. - /// - public static IApplicationBuilder UseBasicAuthentication( - this IApplicationBuilder app, - BasicAuthenticationOptions options) - { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - return app.UseMiddleware(Options.Create(options)); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/ZNetCS.AspNetCore.Authentication.Basic/Events/BasicAuthenticationEvents.cs b/src/ZNetCS.AspNetCore.Authentication.Basic/Events/BasicAuthenticationEvents.cs index 063eb42..273cea5 100644 --- a/src/ZNetCS.AspNetCore.Authentication.Basic/Events/BasicAuthenticationEvents.cs +++ b/src/ZNetCS.AspNetCore.Authentication.Basic/Events/BasicAuthenticationEvents.cs @@ -21,7 +21,7 @@ namespace ZNetCS.AspNetCore.Authentication.Basic.Events /// /// The basic authentication events. /// - public class BasicAuthenticationEvents : IBasicAuthenticationEvents + public class BasicAuthenticationEvents { #region Public Properties @@ -37,7 +37,16 @@ public class BasicAuthenticationEvents : IBasicAuthenticationEvents #region IBasicAuthenticationEvents - /// + /// + /// Called each time a request principal has been validated by the middleware. By implementing this method the + /// application have alter or reject the principal which has arrived with the request. + /// + /// + /// Contains information about the login session as well as the user name and provide password. + /// + /// + /// A representing the completed operation. + /// public virtual Task ValidatePrincipal(ValidatePrincipalContext context) => this.OnValidatePrincipal(context); #endregion diff --git a/src/ZNetCS.AspNetCore.Authentication.Basic/Events/IBasicAuthenticationEvents.cs b/src/ZNetCS.AspNetCore.Authentication.Basic/Events/IBasicAuthenticationEvents.cs deleted file mode 100644 index 5927f2b..0000000 --- a/src/ZNetCS.AspNetCore.Authentication.Basic/Events/IBasicAuthenticationEvents.cs +++ /dev/null @@ -1,43 +0,0 @@ -// -------------------------------------------------------------------------------------------------------------------- -// -// Copyright (c) Marcin Smółka zNET Computer Solutions. All rights reserved. -// -// -// Specifies callback methods which the invokes to enable developer -// control over the authentication process. -// -// -------------------------------------------------------------------------------------------------------------------- - -namespace ZNetCS.AspNetCore.Authentication.Basic.Events -{ - #region Usings - - using System.Threading.Tasks; - - using Microsoft.AspNetCore.Authentication; - - #endregion - - /// - /// Specifies callback methods which the invokes to enable application - /// control over the authentication process. - /// - public interface IBasicAuthenticationEvents - { - #region Public Methods - - /// - /// Called each time a request principal has been validated by the middleware. By implementing this method the - /// application have alter or reject the principal which has arrived with the request. - /// - /// - /// Contains information about the login session as well as the user name and provide password. - /// - /// - /// A representing the completed operation. - /// - Task ValidatePrincipal(ValidatePrincipalContext context); - - #endregion - } -} \ No newline at end of file diff --git a/src/ZNetCS.AspNetCore.Authentication.Basic/Events/ValidatePrincipalContext.cs b/src/ZNetCS.AspNetCore.Authentication.Basic/Events/ValidatePrincipalContext.cs index 9697d99..ebd4477 100644 --- a/src/ZNetCS.AspNetCore.Authentication.Basic/Events/ValidatePrincipalContext.cs +++ b/src/ZNetCS.AspNetCore.Authentication.Basic/Events/ValidatePrincipalContext.cs @@ -11,8 +11,6 @@ namespace ZNetCS.AspNetCore.Authentication.Basic.Events { #region Usings - using System; - using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; @@ -21,7 +19,7 @@ namespace ZNetCS.AspNetCore.Authentication.Basic.Events /// /// The validate principal context. /// - public class ValidatePrincipalContext : BaseContext + public class ValidatePrincipalContext : PrincipalContext { #region Constructors and Destructors @@ -31,6 +29,9 @@ public class ValidatePrincipalContext : BaseContext /// /// The context. /// + /// + /// The scheme. + /// /// /// The options. /// @@ -40,14 +41,12 @@ public class ValidatePrincipalContext : BaseContext /// /// The password. /// - public ValidatePrincipalContext(HttpContext context, BasicAuthenticationOptions options, string userName, string password) : base(context) + public ValidatePrincipalContext(HttpContext context, AuthenticationScheme scheme, BasicAuthenticationOptions options, string userName, string password) : base( + context, + scheme, + options, + null) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - this.Options = options; this.UserName = userName; this.Password = password; } @@ -56,11 +55,6 @@ public ValidatePrincipalContext(HttpContext context, BasicAuthenticationOptions #region Public Properties - /// - /// Gets the options. - /// - public BasicAuthenticationOptions Options { get; } - /// /// Gets the password. /// diff --git a/src/ZNetCS.AspNetCore.Authentication.Basic/ZNetCS.AspNetCore.Authentication.Basic.csproj b/src/ZNetCS.AspNetCore.Authentication.Basic/ZNetCS.AspNetCore.Authentication.Basic.csproj index 5c06b69..b0ed579 100644 --- a/src/ZNetCS.AspNetCore.Authentication.Basic/ZNetCS.AspNetCore.Authentication.Basic.csproj +++ b/src/ZNetCS.AspNetCore.Authentication.Basic/ZNetCS.AspNetCore.Authentication.Basic.csproj @@ -4,7 +4,7 @@ A simple basic authentication middleware. Marcin Smółka zNET Computer Solutions Marcin Smółka - net452;netstandard1.6 + net461;netstandard2.0 true ZNetCS.AspNetCore.Authentication.Basic ZNetCS.AspNetCore.Authentication.Basic @@ -13,6 +13,7 @@ https://raw.githubusercontent.com/msmolka/ZNetCS.AspNetCore.Authentication.Basic/master/LICENSE git https://github.com/msmolka/ZNetCS.AspNetCore.Authentication.Basic + 2.0.0 false false false @@ -28,26 +29,26 @@ ..\..\CommonRuleSet.ruleset - + - + - - - - - - - + + + + + + + All - + diff --git a/test/ZNetCS.AspNetCore.Authentication.BasicTests/AuthorizationTest.cs b/test/ZNetCS.AspNetCore.Authentication.BasicTests/AuthorizationTest.cs index a2f594e..b22132c 100644 --- a/test/ZNetCS.AspNetCore.Authentication.BasicTests/AuthorizationTest.cs +++ b/test/ZNetCS.AspNetCore.Authentication.BasicTests/AuthorizationTest.cs @@ -41,7 +41,7 @@ public class AuthorizationTest [TestMethod] public async Task UnauthorizedBasicRealmTest() { - using (var server = new TestServer(WebHostBuilderHelper.CreateBuilder(new BasicAuthenticationOptions()))) + using (var server = new TestServer(WebHostBuilderHelper.CreateBuilder(o => { }))) { using (HttpClient client = server.CreateClient()) { @@ -66,7 +66,7 @@ public async Task UnauthorizedBasicRealmTest() [TestMethod] public async Task UnauthorizedBasicTest() { - using (var server = new TestServer(WebHostBuilderHelper.CreateBuilder(new BasicAuthenticationOptions()))) + using (var server = new TestServer(WebHostBuilderHelper.CreateBuilder(o => { }))) { using (HttpClient client = server.CreateClient()) { @@ -85,12 +85,7 @@ public async Task UnauthorizedBasicTest() [TestMethod] public async Task UnauthorizedMyRealmTest() { - using (var server = new TestServer( - WebHostBuilderHelper.CreateBuilder( - new BasicAuthenticationOptions - { - Realm = "My realm" - }))) + using (var server = new TestServer(WebHostBuilderHelper.CreateBuilder(o => { o.Realm = "My realm"; }))) { using (HttpClient client = server.CreateClient()) { @@ -115,7 +110,7 @@ public async Task UnauthorizedMyRealmTest() [TestMethod] public async Task UnauthorizedValidCredentialsTest() { - using (var server = new TestServer(WebHostBuilderHelper.CreateBuilder(new BasicAuthenticationOptions()))) + using (var server = new TestServer(WebHostBuilderHelper.CreateBuilder(o => { }))) { using (HttpClient client = server.CreateClient()) { diff --git a/test/ZNetCS.AspNetCore.Authentication.BasicTests/Startup.cs b/test/ZNetCS.AspNetCore.Authentication.BasicTests/Startup.cs index 2ce9763..634c5e4 100644 --- a/test/ZNetCS.AspNetCore.Authentication.BasicTests/Startup.cs +++ b/test/ZNetCS.AspNetCore.Authentication.BasicTests/Startup.cs @@ -13,11 +13,8 @@ namespace ZNetCS.AspNetCore.Authentication.BasicTests using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; - using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Logging; - - using ZNetCS.AspNetCore.Authentication.Basic.DependecyInjection; + using ZNetCS.AspNetCore.Authentication.Basic; #endregion @@ -26,60 +23,20 @@ namespace ZNetCS.AspNetCore.Authentication.BasicTests /// public class Startup { - #region Constructors and Destructors - - /// - /// Initializes a new instance of the class. - /// - /// - /// The hosting environment. - /// - public Startup(IHostingEnvironment env) - { - IConfigurationBuilder builder = new ConfigurationBuilder() - .SetBasePath(env.ContentRootPath) - .AddEnvironmentVariables(); - this.Configuration = builder.Build(); - } - - #endregion - - #region Public Properties - - /// - /// Gets the configuration. - /// - public IConfigurationRoot Configuration { get; } - - #endregion - #region Public Methods /// /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. /// /// - /// The app. + /// The app builder. /// /// - /// The env. - /// - /// - /// The logger factory. + /// The hosting environment. /// - public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) + public void Configure(IApplicationBuilder app, IHostingEnvironment env) { - loggerFactory - .WithFilter( - new FilterLoggerSettings - { - { "Default", LogLevel.Debug } - }) - .AddDebug(); - - var options = WebHostBuilderHelper.CreateOptions(); - - app.UseBasicAuthentication(options); + app.UseAuthentication(); app.UseMvc(); } @@ -92,6 +49,10 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF public void ConfigureServices(IServiceCollection services) { // Add framework services. + services + .AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme) + .AddBasicAuthentication(WebHostBuilderHelper.ConfigureOptions()); + services.AddMvc(); } diff --git a/test/ZNetCS.AspNetCore.Authentication.BasicTests/WebHostBuilderHelper.cs b/test/ZNetCS.AspNetCore.Authentication.BasicTests/WebHostBuilderHelper.cs index 2b92715..847011c 100644 --- a/test/ZNetCS.AspNetCore.Authentication.BasicTests/WebHostBuilderHelper.cs +++ b/test/ZNetCS.AspNetCore.Authentication.BasicTests/WebHostBuilderHelper.cs @@ -11,6 +11,7 @@ namespace ZNetCS.AspNetCore.Authentication.BasicTests { #region Usings + using System; using System.Collections.Generic; using System.IO; using System.Security.Claims; @@ -21,9 +22,9 @@ namespace ZNetCS.AspNetCore.Authentication.BasicTests using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http.Authentication; using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.Logging; using ZNetCS.AspNetCore.Authentication.Basic; - using ZNetCS.AspNetCore.Authentication.Basic.DependecyInjection; using ZNetCS.AspNetCore.Authentication.Basic.Events; #endregion @@ -38,24 +39,35 @@ public class WebHostBuilderHelper /// /// Creates code builder. /// - /// - /// The options. + /// + /// The configure options action. /// - public static IWebHostBuilder CreateBuilder(BasicAuthenticationOptions options = null) + public static IWebHostBuilder CreateBuilder(Action configureOptions = null) { - if (options == null) + if (configureOptions == null) { - options = CreateOptions(); + configureOptions = ConfigureOptions(); } IWebHostBuilder builder = new WebHostBuilder() .ConfigureServices( - s => { s.AddMvc(); }) + s => + { + s.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme).AddBasicAuthentication(configureOptions); + s.AddMvc(); + }) .Configure( app => { - app.UseBasicAuthentication(options); + app.UseAuthentication(); app.UseMvc(); + }) + .ConfigureLogging( + (context, logging) => + { + logging + .AddFilter("Default", LogLevel.Debug) + .AddDebug(); }); return builder; @@ -64,12 +76,12 @@ public static IWebHostBuilder CreateBuilder(BasicAuthenticationOptions options = /// /// Creates options. /// - public static BasicAuthenticationOptions CreateOptions() + public static Action ConfigureOptions() { - return new BasicAuthenticationOptions + return options => { - Realm = "My realm", - Events = new BasicAuthenticationEvents + options.Realm = "My realm"; + options.Events = new BasicAuthenticationEvents { OnValidatePrincipal = context => { @@ -81,17 +93,16 @@ public static BasicAuthenticationOptions CreateOptions() }; var ticket = new AuthenticationTicket( - new ClaimsPrincipal( - new ClaimsIdentity(claims, context.Options.AuthenticationScheme)), - new AuthenticationProperties(), - context.Options.AuthenticationScheme); + new ClaimsPrincipal(new ClaimsIdentity(claims, BasicAuthenticationDefaults.AuthenticationScheme)), + new Microsoft.AspNetCore.Authentication.AuthenticationProperties(), + BasicAuthenticationDefaults.AuthenticationScheme); return Task.FromResult(AuthenticateResult.Success(ticket)); } return Task.FromResult(AuthenticateResult.Fail("Authentication failed.")); } - } + }; }; } @@ -101,8 +112,15 @@ public static BasicAuthenticationOptions CreateOptions() public static IWebHostBuilder CreateStartupBuilder() { return new WebHostBuilder() + .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup() - .UseContentRoot(Directory.GetCurrentDirectory()); + .ConfigureLogging( + (context, logging) => + { + logging + .AddFilter("Default", LogLevel.Debug) + .AddDebug(); + }); } #endregion diff --git a/test/ZNetCS.AspNetCore.Authentication.BasicTests/ZNetCS.AspNetCore.Authentication.BasicTests.csproj b/test/ZNetCS.AspNetCore.Authentication.BasicTests/ZNetCS.AspNetCore.Authentication.BasicTests.csproj index 824dbe5..a155b69 100644 --- a/test/ZNetCS.AspNetCore.Authentication.BasicTests/ZNetCS.AspNetCore.Authentication.BasicTests.csproj +++ b/test/ZNetCS.AspNetCore.Authentication.BasicTests/ZNetCS.AspNetCore.Authentication.BasicTests.csproj @@ -2,13 +2,12 @@ Marcin Smółka - netcoreapp1.1 + netcoreapp2.0 true ZNetCS.AspNetCore.Authentication.BasicTests ZNetCS.AspNetCore.Authentication.BasicTests true - $(PackageTargetFallback);dnxcore50;portable-net45+win8 - 1.1.1 + $(AssetTargetFallback);dnxcore50;portable-net45+win8 false false false @@ -23,18 +22,20 @@ - - - + + + + + + + + + + All - - - - - - - + +