From a68fe11f9b42fc60d22fc7c52b6ab5eb9a98b314 Mon Sep 17 00:00:00 2001 From: Claudio Rodrigo Pereyra Diaz Date: Fri, 24 May 2019 11:52:09 -0300 Subject: [PATCH 01/18] Update NuGet.Config Add MakingSense appvyor nuget repository --- MakingSense.AspNetCore.Authentication.SimpleToken.sln | 1 + NuGet.Config | 7 +++++++ 2 files changed, 8 insertions(+) diff --git a/MakingSense.AspNetCore.Authentication.SimpleToken.sln b/MakingSense.AspNetCore.Authentication.SimpleToken.sln index cbbf4b7..5aad7e9 100644 --- a/MakingSense.AspNetCore.Authentication.SimpleToken.sln +++ b/MakingSense.AspNetCore.Authentication.SimpleToken.sln @@ -12,6 +12,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution .gitignore = .gitignore appveyor.yml = appveyor.yml LICENSE = LICENSE + NuGet.Config = NuGet.Config README.md = README.md EndProjectSection EndProject diff --git a/NuGet.Config b/NuGet.Config index 66ea8c7..cb70cc6 100644 --- a/NuGet.Config +++ b/NuGet.Config @@ -4,5 +4,12 @@ + + + + + + + From 10a3199bc486f2b688eb83d59cb1b6b0558e0f85 Mon Sep 17 00:00:00 2001 From: Claudio Rodrigo Pereyra Diaz Date: Fri, 24 May 2019 11:52:43 -0300 Subject: [PATCH 02/18] Update MakingSense.AspNetCore.Authentication.SimpleToken.sln --- MakingSense.AspNetCore.Authentication.SimpleToken.sln | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/MakingSense.AspNetCore.Authentication.SimpleToken.sln b/MakingSense.AspNetCore.Authentication.SimpleToken.sln index 5aad7e9..679a4b3 100644 --- a/MakingSense.AspNetCore.Authentication.SimpleToken.sln +++ b/MakingSense.AspNetCore.Authentication.SimpleToken.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.26228.4 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28917.181 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{1A4906E1-3779-42B3-BE5D-2079B4D0C0C9}" EndProject @@ -35,4 +35,7 @@ Global GlobalSection(NestedProjects) = preSolution {209CD8C9-0545-4A2E-826D-5B83044261AF} = {1A4906E1-3779-42B3-BE5D-2079B4D0C0C9} EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {B2C5D2C9-1449-47DC-80D9-FD90D490015A} + EndGlobalSection EndGlobal From e603ce32b6d5c8bbb70b7fee4894c6acbe5f8ad2 Mon Sep 17 00:00:00 2001 From: Claudio Rodrigo Pereyra Diaz Date: Fri, 24 May 2019 11:53:04 -0300 Subject: [PATCH 03/18] Set netstandard 2.0 as target framework --- ...gSense.AspNetCore.Authentication.SimpleToken.csproj | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj b/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj index 420564f..63a2a88 100644 --- a/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj +++ b/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj @@ -3,7 +3,7 @@ MakingSense.AspNetCore.Authentication.SimpleToken Class Library MakingSense - net451;netcoreapp1.1 + netstandard2.0 MakingSense.AspNetCore.Authentication.SimpleToken MakingSense.AspNetCore.Authentication.SimpleToken ASP.NET 5;vnext;authentication;token;bearer @@ -11,7 +11,6 @@ http://www.gnu.org/licenses/lgpl.html git git://github.com/MakingSense/aspnet-authentication-simpletoken - 1.1.1 1.1.3-alpha @@ -25,11 +24,4 @@ - - - - - - - From cd2907b1b4a8776ab03df4f81d347cb5d71191ea Mon Sep 17 00:00:00 2001 From: Claudio Rodrigo Pereyra Diaz Date: Fri, 24 May 2019 11:56:08 -0300 Subject: [PATCH 04/18] Update nuget Newtonsoft.Json --- .../MakingSense.AspNetCore.Authentication.SimpleToken.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj b/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj index 63a2a88..8ed8618 100644 --- a/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj +++ b/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj @@ -19,7 +19,7 @@ - + From f348a55f68dedd2ee74029f23f5510adc6c5618e Mon Sep 17 00:00:00 2001 From: Claudio Rodrigo Pereyra Diaz Date: Fri, 24 May 2019 11:56:21 -0300 Subject: [PATCH 05/18] Update nuget Microsoft.IdentityModel.Tokens --- .../MakingSense.AspNetCore.Authentication.SimpleToken.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj b/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj index 8ed8618..4798492 100644 --- a/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj +++ b/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj @@ -18,7 +18,7 @@ - + From a738737018183f9803b69d4cab4bde4282d5f6ac Mon Sep 17 00:00:00 2001 From: Claudio Rodrigo Pereyra Diaz Date: Fri, 24 May 2019 11:56:32 -0300 Subject: [PATCH 06/18] Update nuget Microsoft.CSharp --- .../MakingSense.AspNetCore.Authentication.SimpleToken.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj b/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj index 4798492..ebbea9a 100644 --- a/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj +++ b/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj @@ -17,7 +17,7 @@ - + From d0ddcf339a39511e34d01f53b0c89cf2725d6ac7 Mon Sep 17 00:00:00 2001 From: Claudio Rodrigo Pereyra Diaz Date: Fri, 24 May 2019 12:01:14 -0300 Subject: [PATCH 07/18] Update AspNetCore 2.0 Update version to follow AspNetCore number --- appveyor.yml | 2 +- ...MakingSense.AspNetCore.Authentication.SimpleToken.csproj | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index c14390c..3c53f47 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,6 +1,6 @@ os: Visual Studio 2017 -version: 1.1.3-alpha-{build} +version: 2.0.0-alpha-{build} nuget: project_feed: true diff --git a/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj b/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj index ebbea9a..6d171d0 100644 --- a/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj +++ b/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj @@ -11,12 +11,12 @@ http://www.gnu.org/licenses/lgpl.html git git://github.com/MakingSense/aspnet-authentication-simpletoken - 1.1.3-alpha + 2.0.0-alpha - - + + From c16afbd2decceea9865e4f674c28efef55600d88 Mon Sep 17 00:00:00 2001 From: Claudio Rodrigo Pereyra Diaz Date: Fri, 24 May 2019 13:22:57 -0300 Subject: [PATCH 08/18] Update appveyor.yml Now this nuget source is defined in solution Nuget.Config file --- appveyor.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 3c53f47..3f27caa 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -5,9 +5,6 @@ version: 2.0.0-alpha-{build} nuget: project_feed: true -install: - - cmd: nuget sources add -Name makingsense-aspnet -Source https://ci.appveyor.com/nuget/makingsense-aspnet -UserName dtru+read@makingsense.com -Password 4@pdw@BlfpQn - before_build: - cmd: set DOTNET_ASSEMBLY_FILE_VERSION=%APPVEYOR_BUILD_NUMBER% - cmd: set DOTNET_BUILD_VERSION=%APPVEYOR_BUILD_NUMBER% From 786c786543bae0d7516649194bc276c709dd3154 Mon Sep 17 00:00:00 2001 From: Claudio Rodrigo Pereyra Diaz Date: Mon, 27 May 2019 17:54:07 -0300 Subject: [PATCH 09/18] Obsolete UseSimpleTokenAuthentication The UseSimpleTokenAuthentication extension method for IApplicationBuilder is obsolete the new way to add autentication is by Configuration. See https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x?view=aspnetcore-2.0 for more details --- .../SimpleTokenAppBuilderExtensions.cs | 39 ++-------- .../SimpleTokenAuthenticationMiddleware.cs | 72 ------------------- 2 files changed, 4 insertions(+), 107 deletions(-) delete mode 100644 src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationMiddleware.cs diff --git a/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAppBuilderExtensions.cs b/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAppBuilderExtensions.cs index 890f394..04986ee 100644 --- a/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAppBuilderExtensions.cs +++ b/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAppBuilderExtensions.cs @@ -1,14 +1,11 @@ -using System; +using System; using MakingSense.AspNetCore.Authentication.SimpleToken; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Framework.Internal; -using Microsoft.IdentityModel.Tokens; -using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.Builder { public static class SimpleTokenAppBuilderExtensions { + [Obsolete("UseSimpleTokenAuthentication is obsolete. Configure SimpleTokenAuthentication authentication with AddAuthentication().AddSimpleTokenAuthentication in ConfigureServices. See https://go.microsoft.com/fwlink/?linkid=845470 for more details.", error: true)] public static IApplicationBuilder UseSimpleTokenAuthentication(this IApplicationBuilder app) { if (app == null) @@ -19,38 +16,10 @@ public static IApplicationBuilder UseSimpleTokenAuthentication(this IApplication return UseSimpleTokenAuthentication(app, new SimpleTokenAuthenticationOptions()); } + [Obsolete("UseSimpleTokenAuthentication is obsolete. Configure SimpleTokenAuthentication authentication with AddAuthentication().AddSimpleTokenAuthentication in ConfigureServices. See https://go.microsoft.com/fwlink/?linkid=845470 for more details.", error: true)] public static IApplicationBuilder UseSimpleTokenAuthentication(this IApplicationBuilder app, SimpleTokenAuthenticationOptions options) { - if (app == null) - { - throw new ArgumentNullException(nameof(app)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - if (string.IsNullOrEmpty(options.AuthenticationScheme)) - { - options.AuthenticationScheme = "Bearer"; - } - - if (options.SecurityTokenValidatorsFactory == null) - { - // TODO: fix it because it is using app services, and it should use scope services, - // a work around could be: - // ``` - // SecurityTokenValidatorsFactory = () => - // { - // var context = app.ApplicationServices.GetService().HttpContext; - // return context.RequestServices.GetServices(); - // } - // ``` - options.SecurityTokenValidatorsFactory = () => app.ApplicationServices.GetServices(); - } - - return app.UseMiddleware(Options.Create(options)); + throw new NotSupportedException("This method is no longer supported, see https://go.microsoft.com/fwlink/?linkid=845470"); } } } diff --git a/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationMiddleware.cs b/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationMiddleware.cs deleted file mode 100644 index 1542dcc..0000000 --- a/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationMiddleware.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.Text.Encodings.Web; -using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using Microsoft.Framework.Internal; - -namespace MakingSense.AspNetCore.Authentication.SimpleToken -{ - /// - /// SimpleToken authentication middleware component which is added to an HTTP pipeline. This class is not - /// created by application code directly, instead it is added by calling the the IAppBuilder UseSimpleTokenAuthentication - /// extension method. - /// - public class SimpleTokenAuthenticationMiddleware : AuthenticationMiddleware - { - /// - /// SimpleToken authentication component which is added to an HTTP pipeline. This constructor is not - /// called by application code directly, instead it is added by calling the the IAppBuilder UseSimpleTokenAuthentication - /// extension method. - /// - public SimpleTokenAuthenticationMiddleware( - [NotNull] RequestDelegate next, - [NotNull] ILoggerFactory loggerFactory, - [NotNull] UrlEncoder encoder, - [NotNull] IOptions options) - : 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 (string.IsNullOrEmpty(Options.AuthenticationScheme)) - { - throw new ArgumentException(nameof(Options.AuthenticationScheme)); - } - - if (Options.SecurityTokenValidatorsFactory == null) - { - throw new ArgumentException(nameof(Options.SecurityTokenValidatorsFactory)); - } - } - - /// - /// Called by the AuthenticationMiddleware base class to create a per-request handler. - /// - /// A new instance of the request handler - protected override AuthenticationHandler CreateHandler() - { - return new SimpleTokenAuthenticationHandler(); - } - } -} From 2b61971198f44e0736ca0d8823731543095166f3 Mon Sep 17 00:00:00 2001 From: Claudio Rodrigo Pereyra Diaz Date: Mon, 27 May 2019 17:56:50 -0300 Subject: [PATCH 10/18] Adapt SimpleTokenAuthenticationHandler and SimpleTokenAuthenticationOptions The new AuthenticationHandler allow to return a Fail message and have a constructor with parameters --- .../SimpleTokenAuthenticationHandler.cs | 63 ++++++++++++------- .../SimpleTokenAuthenticationOptions.cs | 21 ++++++- 2 files changed, 57 insertions(+), 27 deletions(-) diff --git a/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationHandler.cs b/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationHandler.cs index d79e5e9..c201622 100644 --- a/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationHandler.cs +++ b/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationHandler.cs @@ -1,11 +1,12 @@ -using System; +using System; using System.Text; +using System.Text.Encodings.Web; using System.Threading.Tasks; using MakingSense.AspNetCore.Authentication.Abstractions; using Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Authentication; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using Microsoft.Net.Http.Headers; @@ -13,6 +14,15 @@ namespace MakingSense.AspNetCore.Authentication.SimpleToken { public class SimpleTokenAuthenticationHandler : AuthenticationHandler { + public SimpleTokenAuthenticationHandler( + IOptionsMonitor options, + ILoggerFactory logger, + UrlEncoder encoder, + ISystemClock clock) + : base(options, logger, encoder, clock) + { + } + /// /// Overrides the standard AuthenticationHandler to be more robust supporting [RFC 6750](http://tools.ietf.org/html/rfc6750) and /// some licenses based on [GitHub behavior](https://developer.github.com/v3/oauth/#use-the-access-token-to-access-the-api). @@ -53,7 +63,6 @@ public static string ExtractToken(HttpRequest request) return pair.Substring(ix + 1).Trim(); } } - // Not so nice, but AuthenticateResult.Fail does not allow us to show the error throw new AuthenticationException("Authorization header exists but does not contains valid information."); } @@ -75,33 +84,39 @@ public static string ExtractToken(HttpRequest request) /// protected override async Task HandleAuthenticateAsync() { - var token = ExtractToken(Request); - - // If no token found, no further work possible - if (string.IsNullOrEmpty(token)) + try { - return AuthenticateResult.Skip(); - } + var token = ExtractToken(Request); - var validationParameters = Options.TokenValidationParameters.Clone(); + // If no token found, no further work possible + if (string.IsNullOrEmpty(token)) + { + return AuthenticateResult.NoResult(); + } - SecurityToken validatedToken; - var validators = Options.SecurityTokenValidatorsFactory(); - foreach (var validator in validators) - { - if (validator.CanReadToken(token)) + var validationParameters = Options.TokenValidationParameters.Clone(); + + var validators = Options.SecurityTokenValidatorsFactory(); + foreach (var validator in validators) { - var principal = validator.ValidateToken(token, validationParameters, out validatedToken); - var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), Options.AuthenticationScheme); - return AuthenticateResult.Success(ticket); + if (validator.CanReadToken(token)) + { + var principal = validator.ValidateToken(token, validationParameters, out SecurityToken validatedToken); + var ticket = new AuthenticationTicket(principal, Scheme.Name); + return AuthenticateResult.Success(ticket); + } } - } - // Ugly patch to make this method should to be async in order to allow result caching by caller - await DoneTask; + // Ugly patch to make this method should to be async in order to allow result caching by caller + await DoneTask; - // Not so nice, but AuthenticateResult.Fail does not allow us to show the error - throw new AuthenticationException("Authorization token has been detected but it cannot be read."); + // Not so nice, but AuthenticateResult.Fail does not allow us to show the error + throw new AuthenticationException("Authorization token has been detected but it cannot be read."); + } + catch (AuthenticationException ex) + { + return AuthenticateResult.Fail(ex.Message); + } } } } diff --git a/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationOptions.cs b/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationOptions.cs index 9005cfc..8eb7675 100644 --- a/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationOptions.cs +++ b/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationOptions.cs @@ -1,14 +1,15 @@ -using System; +using System; using System.Collections.Generic; +using Microsoft.AspNetCore.Authentication; using Microsoft.Framework.Internal; using Microsoft.IdentityModel.Tokens; -namespace Microsoft.AspNetCore.Builder +namespace MakingSense.AspNetCore.Authentication.SimpleToken { /// /// Options class provides information needed to control SimpleToken middleware behavior /// - public class SimpleTokenAuthenticationOptions : AuthenticationOptions + public class SimpleTokenAuthenticationOptions : AuthenticationSchemeOptions { /// /// Gets or sets the for creating validators for validating tokens. @@ -30,5 +31,19 @@ public SimpleTokenAuthenticationOptions() : base() { } + public override void Validate() + { + base.Validate(); + + if (SecurityTokenValidatorsFactory == null) + { + throw new ArgumentException(nameof(SecurityTokenValidatorsFactory)); + } + + if (TokenValidationParameters == null) + { + throw new ArgumentException(nameof(TokenValidationParameters)); + } + } } } From 1e7c20c0cc553ff0e9be7c6ef14a64c17795b11c Mon Sep 17 00:00:00 2001 From: Claudio Rodrigo Pereyra Diaz Date: Mon, 27 May 2019 17:57:01 -0300 Subject: [PATCH 11/18] Create SimpleTokenDefaults.cs --- .../SimpleTokenDefaults.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenDefaults.cs diff --git a/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenDefaults.cs b/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenDefaults.cs new file mode 100644 index 0000000..ff4c944 --- /dev/null +++ b/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenDefaults.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace MakingSense.AspNetCore.Authentication.SimpleToken +{ + public static class SimpleTokenDefaults + { + public const string AuthenticationScheme = "SimpleToken"; + + public static readonly string DisplayName = "Simple Token"; + } +} From 9ff58f9b281bae54433b7811af24fd7b2dd6f7f8 Mon Sep 17 00:00:00 2001 From: Claudio Rodrigo Pereyra Diaz Date: Mon, 27 May 2019 17:57:31 -0300 Subject: [PATCH 12/18] Create SimpleTokenAuthenticationExtensions.cs This allow configure the SimpleTokenAuthentication by extension methods for AuthenticationBuilder --- .../SimpleTokenAuthenticationExtensions.cs | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationExtensions.cs diff --git a/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationExtensions.cs b/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationExtensions.cs new file mode 100644 index 0000000..c19def3 --- /dev/null +++ b/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationExtensions.cs @@ -0,0 +1,28 @@ +using Microsoft.AspNetCore.Authentication; +using System; + +namespace MakingSense.AspNetCore.Authentication.SimpleToken +{ + public static class SimpleTokenAuthenticationExtensions + { + public static AuthenticationBuilder AddSimpleTokenAuthentication(this AuthenticationBuilder builder) + => builder.AddSimpleTokenAuthentication(SimpleTokenDefaults.AuthenticationScheme, _ => { }); + + public static AuthenticationBuilder AddSimpleTokenAuthentication(this AuthenticationBuilder builder, + Action configureOptions) + => builder.AddSimpleTokenAuthentication(SimpleTokenDefaults.AuthenticationScheme, configureOptions); + + public static AuthenticationBuilder AddSimpleTokenAuthentication(this AuthenticationBuilder builder, + string authenticationScheme, + Action configureOptions) + => builder.AddSimpleTokenAuthentication(authenticationScheme, SimpleTokenDefaults.DisplayName, configureOptions: configureOptions); + + public static AuthenticationBuilder AddSimpleTokenAuthentication(this AuthenticationBuilder builder, + string authenticationScheme, + string displayName, + Action configureOptions) + { + return builder.AddScheme(authenticationScheme, displayName, configureOptions); + } + } +} From 63824cc10e6607a788eb7f6664950095c46f91dd Mon Sep 17 00:00:00 2001 From: Claudio Rodrigo Pereyra Diaz Date: Mon, 27 May 2019 17:57:48 -0300 Subject: [PATCH 13/18] Adapt README for the new version --- README.md | 36 +++++++++++++++++-- .../README.md | 36 +++++++++++++++++-- 2 files changed, 66 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index af4201c..0302ecb 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# SimpleToken Authentication Middleware +# SimpleToken Authentication This package allows to extract token from authenticated requests and delegate it to an appropriated ISecurityTokenValidator and generate and AuthenticationTicket. @@ -6,7 +6,7 @@ This package allows to extract token from authenticated requests and delegate it ### Token extraction details -This middleware tries to support almost [RFC 6750](http://tools.ietf.org/html/rfc6750) and some licenses based on [GitHub behavior](https://developer.github.com/v3/oauth/#use-the-access-token-to-access-the-api). But does not support Form-Encoded Body Parameter (http://tools.ietf.org/html/rfc6750#section-2.2). +This tries to support almost [RFC 6750](http://tools.ietf.org/html/rfc6750) and some licenses based on [GitHub behavior](https://developer.github.com/v3/oauth/#use-the-access-token-to-access-the-api). But does not support Form-Encoded Body Parameter (http://tools.ietf.org/html/rfc6750#section-2.2). There are three methods of sending tokens: @@ -76,7 +76,37 @@ For example: WWW-Authenticate: Bearer ``` -## Usage +## Usage v2 + +It is necessary to register all valid `ISecurityTokenValidator` classes and configure the Authentication service using the `AddSimpleTokenAuthentication` extension method. + +Example: + +```csharp +public class Startup +{ + public void ConfigureServices(IServiceCollection services) + { + services.AddTransient(); + services.AddAuthentication() + .AddSimpleTokenAuthentication(options => + { + options.SecurityTokenValidatorsFactory = () => + { + var context = services.BuildServiceProvider().GetService().HttpContext; + return context.RequestServices.GetServices(); + }; + }); + } + + public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory) { + app.UseAuthentication(); + app.UseMvc(); + } +} +``` + +## Usage v1 It is necessary to register all valid `ISecurityTokenValidator` classes and add the middleware to ApplicationBuilder using `UseSimpleTokenAuthentication`. diff --git a/src/MakingSense.AspNetCore.Authentication.SimpleToken/README.md b/src/MakingSense.AspNetCore.Authentication.SimpleToken/README.md index af4201c..0302ecb 100644 --- a/src/MakingSense.AspNetCore.Authentication.SimpleToken/README.md +++ b/src/MakingSense.AspNetCore.Authentication.SimpleToken/README.md @@ -1,4 +1,4 @@ -# SimpleToken Authentication Middleware +# SimpleToken Authentication This package allows to extract token from authenticated requests and delegate it to an appropriated ISecurityTokenValidator and generate and AuthenticationTicket. @@ -6,7 +6,7 @@ This package allows to extract token from authenticated requests and delegate it ### Token extraction details -This middleware tries to support almost [RFC 6750](http://tools.ietf.org/html/rfc6750) and some licenses based on [GitHub behavior](https://developer.github.com/v3/oauth/#use-the-access-token-to-access-the-api). But does not support Form-Encoded Body Parameter (http://tools.ietf.org/html/rfc6750#section-2.2). +This tries to support almost [RFC 6750](http://tools.ietf.org/html/rfc6750) and some licenses based on [GitHub behavior](https://developer.github.com/v3/oauth/#use-the-access-token-to-access-the-api). But does not support Form-Encoded Body Parameter (http://tools.ietf.org/html/rfc6750#section-2.2). There are three methods of sending tokens: @@ -76,7 +76,37 @@ For example: WWW-Authenticate: Bearer ``` -## Usage +## Usage v2 + +It is necessary to register all valid `ISecurityTokenValidator` classes and configure the Authentication service using the `AddSimpleTokenAuthentication` extension method. + +Example: + +```csharp +public class Startup +{ + public void ConfigureServices(IServiceCollection services) + { + services.AddTransient(); + services.AddAuthentication() + .AddSimpleTokenAuthentication(options => + { + options.SecurityTokenValidatorsFactory = () => + { + var context = services.BuildServiceProvider().GetService().HttpContext; + return context.RequestServices.GetServices(); + }; + }); + } + + public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory) { + app.UseAuthentication(); + app.UseMvc(); + } +} +``` + +## Usage v1 It is necessary to register all valid `ISecurityTokenValidator` classes and add the middleware to ApplicationBuilder using `UseSimpleTokenAuthentication`. From 9d476941bce0546ceb941be9591bcff9186c387c Mon Sep 17 00:00:00 2001 From: Claudio Rodrigo Pereyra Diaz Date: Tue, 25 Jun 2019 18:08:12 -0300 Subject: [PATCH 14/18] Change try catch scope --- .../SimpleTokenAuthenticationHandler.cs | 45 +++++++++---------- 1 file changed, 22 insertions(+), 23 deletions(-) diff --git a/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationHandler.cs b/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationHandler.cs index c201622..33348ea 100644 --- a/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationHandler.cs +++ b/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationHandler.cs @@ -84,39 +84,38 @@ public static string ExtractToken(HttpRequest request) /// protected override async Task HandleAuthenticateAsync() { + string token; try { - var token = ExtractToken(Request); - - // If no token found, no further work possible - if (string.IsNullOrEmpty(token)) - { - return AuthenticateResult.NoResult(); - } + token = ExtractToken(Request); + } + catch (AuthenticationException ex) + { + return AuthenticateResult.Fail(ex.Message); + } + // If no token found, no further work possible + if (string.IsNullOrEmpty(token)) + { + return AuthenticateResult.NoResult(); + } - var validationParameters = Options.TokenValidationParameters.Clone(); + var validationParameters = Options.TokenValidationParameters.Clone(); - var validators = Options.SecurityTokenValidatorsFactory(); - foreach (var validator in validators) + var validators = Options.SecurityTokenValidatorsFactory(); + foreach (var validator in validators) + { + if (validator.CanReadToken(token)) { - if (validator.CanReadToken(token)) - { - var principal = validator.ValidateToken(token, validationParameters, out SecurityToken validatedToken); - var ticket = new AuthenticationTicket(principal, Scheme.Name); - return AuthenticateResult.Success(ticket); - } + var principal = validator.ValidateToken(token, validationParameters, out SecurityToken validatedToken); + var ticket = new AuthenticationTicket(principal, Scheme.Name); + return AuthenticateResult.Success(ticket); } + } // Ugly patch to make this method should to be async in order to allow result caching by caller await DoneTask; - // Not so nice, but AuthenticateResult.Fail does not allow us to show the error - throw new AuthenticationException("Authorization token has been detected but it cannot be read."); - } - catch (AuthenticationException ex) - { - return AuthenticateResult.Fail(ex.Message); - } + return AuthenticateResult.Fail("Authorization token has been detected but it cannot be read."); } } } From ce03aa9e82e375156000b8d2ef0221ffef2b3eb0 Mon Sep 17 00:00:00 2001 From: Claudio Rodrigo Pereyra Diaz Date: Tue, 25 Jun 2019 18:08:58 -0300 Subject: [PATCH 15/18] Use Task.CompletedTask --- .../SimpleTokenAuthenticationHandler.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationHandler.cs b/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationHandler.cs index 33348ea..d951fb0 100644 --- a/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationHandler.cs +++ b/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationHandler.cs @@ -76,8 +76,6 @@ public static string ExtractToken(HttpRequest request) return null; } - static readonly Task DoneTask = Task.FromResult(0); - /// /// Searches the 'Authorization' header for a 'Bearer' token. If the 'Bearer' token is found, it is validated using set in the options. /// @@ -112,8 +110,8 @@ protected override async Task HandleAuthenticateAsync() } } - // Ugly patch to make this method should to be async in order to allow result caching by caller - await DoneTask; + // Ugly patch to make this method should to be async in order to allow result caching by caller + await Task.CompletedTask; return AuthenticateResult.Fail("Authorization token has been detected but it cannot be read."); } From e1a54e36bb3ccb2aad7f431da34db650d562edc1 Mon Sep 17 00:00:00 2001 From: Claudio Rodrigo Pereyra Diaz Date: Tue, 25 Jun 2019 18:09:17 -0300 Subject: [PATCH 16/18] Use Bearer AuthenticationScheme as default --- .../SimpleTokenDefaults.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenDefaults.cs b/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenDefaults.cs index ff4c944..be68b75 100644 --- a/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenDefaults.cs +++ b/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenDefaults.cs @@ -6,7 +6,7 @@ namespace MakingSense.AspNetCore.Authentication.SimpleToken { public static class SimpleTokenDefaults { - public const string AuthenticationScheme = "SimpleToken"; + public const string AuthenticationScheme = "Bearer"; public static readonly string DisplayName = "Simple Token"; } From c5be41745511fd0a0835c5297546a2242431499d Mon Sep 17 00:00:00 2001 From: Claudio Rodrigo Pereyra Diaz Date: Tue, 25 Jun 2019 18:29:30 -0300 Subject: [PATCH 17/18] Simplify the example --- README.md | 3 +-- .../README.md | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 0302ecb..296ef3e 100644 --- a/README.md +++ b/README.md @@ -93,8 +93,7 @@ public class Startup { options.SecurityTokenValidatorsFactory = () => { - var context = services.BuildServiceProvider().GetService().HttpContext; - return context.RequestServices.GetServices(); + return services.BuildServiceProvider().GetServices(); }; }); } diff --git a/src/MakingSense.AspNetCore.Authentication.SimpleToken/README.md b/src/MakingSense.AspNetCore.Authentication.SimpleToken/README.md index 0302ecb..296ef3e 100644 --- a/src/MakingSense.AspNetCore.Authentication.SimpleToken/README.md +++ b/src/MakingSense.AspNetCore.Authentication.SimpleToken/README.md @@ -93,8 +93,7 @@ public class Startup { options.SecurityTokenValidatorsFactory = () => { - var context = services.BuildServiceProvider().GetService().HttpContext; - return context.RequestServices.GetServices(); + return services.BuildServiceProvider().GetServices(); }; }); } From 6ee2ba3b29e6a9ed55b24a443587585455a0c610 Mon Sep 17 00:00:00 2001 From: Claudio Rodrigo Pereyra Diaz Date: Wed, 26 Jun 2019 15:43:15 -0300 Subject: [PATCH 18/18] Set options.SecurityTokenValidatorsFactory if not set --- README.md | 8 +----- ...pNetCore.Authentication.SimpleToken.csproj | 1 + .../README.md | 8 +----- .../SimpleTokenAuthenticationExtensions.cs | 27 +++++++++++++++++-- 4 files changed, 28 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 296ef3e..c55f6db 100644 --- a/README.md +++ b/README.md @@ -89,13 +89,7 @@ public class Startup { services.AddTransient(); services.AddAuthentication() - .AddSimpleTokenAuthentication(options => - { - options.SecurityTokenValidatorsFactory = () => - { - return services.BuildServiceProvider().GetServices(); - }; - }); + .AddSimpleTokenAuthentication(); } public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory) { diff --git a/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj b/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj index 6d171d0..9017b90 100644 --- a/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj +++ b/src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj @@ -18,6 +18,7 @@ + diff --git a/src/MakingSense.AspNetCore.Authentication.SimpleToken/README.md b/src/MakingSense.AspNetCore.Authentication.SimpleToken/README.md index 296ef3e..c55f6db 100644 --- a/src/MakingSense.AspNetCore.Authentication.SimpleToken/README.md +++ b/src/MakingSense.AspNetCore.Authentication.SimpleToken/README.md @@ -89,13 +89,7 @@ public class Startup { services.AddTransient(); services.AddAuthentication() - .AddSimpleTokenAuthentication(options => - { - options.SecurityTokenValidatorsFactory = () => - { - return services.BuildServiceProvider().GetServices(); - }; - }); + .AddSimpleTokenAuthentication(); } public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory) { diff --git a/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationExtensions.cs b/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationExtensions.cs index c19def3..e7aeccd 100644 --- a/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationExtensions.cs +++ b/src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationExtensions.cs @@ -1,4 +1,6 @@ using Microsoft.AspNetCore.Authentication; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.IdentityModel.Tokens; using System; namespace MakingSense.AspNetCore.Authentication.SimpleToken @@ -6,7 +8,7 @@ namespace MakingSense.AspNetCore.Authentication.SimpleToken public static class SimpleTokenAuthenticationExtensions { public static AuthenticationBuilder AddSimpleTokenAuthentication(this AuthenticationBuilder builder) - => builder.AddSimpleTokenAuthentication(SimpleTokenDefaults.AuthenticationScheme, _ => { }); + => builder.AddSimpleTokenAuthentication(SimpleTokenDefaults.AuthenticationScheme, null); public static AuthenticationBuilder AddSimpleTokenAuthentication(this AuthenticationBuilder builder, Action configureOptions) @@ -22,7 +24,28 @@ public static AuthenticationBuilder AddSimpleTokenAuthentication(this Authentica string displayName, Action configureOptions) { - return builder.AddScheme(authenticationScheme, displayName, configureOptions); + return builder.AddScheme(authenticationScheme, displayName, + (SimpleTokenAuthenticationOptions options) => { + configureOptions?.Invoke(options); + + if (options.SecurityTokenValidatorsFactory == null) + { + options.SecurityTokenValidatorsFactory = () => + { + // TODO: fix it because it is using app services, and it should use scope services, + // a work around could be: + // ``` + // SecurityTokenValidatorsFactory = () => + // { + // var context = builder.Services.BuildServiceProvider().GetService().HttpContext; + // return context.RequestServices.GetServices(); + // } + // ``` + var serviceProvider = builder.Services.BuildServiceProvider(); + return serviceProvider.GetServices(); + }; + } + }); } } }