Skip to content

Commit 1b06d9a

Browse files
Merge pull request #10 from elsupergomez/update-asp-net-core-to-2.0
Update asp net core to 2.0
2 parents 881b6df + 6ee2ba3 commit 1b06d9a

12 files changed

+187
-152
lines changed

MakingSense.AspNetCore.Authentication.SimpleToken.sln

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11

22
Microsoft Visual Studio Solution File, Format Version 12.00
3-
# Visual Studio 15
4-
VisualStudioVersion = 15.0.26228.4
3+
# Visual Studio Version 16
4+
VisualStudioVersion = 16.0.28917.181
55
MinimumVisualStudioVersion = 10.0.40219.1
66
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{1A4906E1-3779-42B3-BE5D-2079B4D0C0C9}"
77
EndProject
@@ -12,6 +12,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
1212
.gitignore = .gitignore
1313
appveyor.yml = appveyor.yml
1414
LICENSE = LICENSE
15+
NuGet.Config = NuGet.Config
1516
README.md = README.md
1617
EndProjectSection
1718
EndProject
@@ -34,4 +35,7 @@ Global
3435
GlobalSection(NestedProjects) = preSolution
3536
{209CD8C9-0545-4A2E-826D-5B83044261AF} = {1A4906E1-3779-42B3-BE5D-2079B4D0C0C9}
3637
EndGlobalSection
38+
GlobalSection(ExtensibilityGlobals) = postSolution
39+
SolutionGuid = {B2C5D2C9-1449-47DC-80D9-FD90D490015A}
40+
EndGlobalSection
3741
EndGlobal

NuGet.Config

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,12 @@
44
<!--To inherit the global NuGet package sources remove the <clear/> line below -->
55
<clear />
66
<add key="api.nuget.org" value="https://api.nuget.org/v3/index.json" />
7+
<add key="makingsense-aspnet" value="https://ci.appveyor.com/nuget/makingsense-aspnet" />
78
</packageSources>
9+
<packageSourceCredentials>
10+
<makingsense-aspnet>
11+
<add key="Username" value="[email protected]" />
12+
<add key="ClearTextPassword" value="4@pdw@BlfpQn" />
13+
</makingsense-aspnet>
14+
</packageSourceCredentials>
815
</configuration>

README.md

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
# SimpleToken Authentication Middleware
1+
# SimpleToken Authentication
22

33
This package allows to extract token from authenticated requests and delegate it to an appropriated ISecurityTokenValidator and generate and AuthenticationTicket.
44

55
## Behavior
66

77
### Token extraction details
88

9-
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).
9+
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).
1010

1111
There are three methods of sending tokens:
1212

@@ -76,7 +76,30 @@ For example:
7676
WWW-Authenticate: Bearer
7777
```
7878
79-
## Usage
79+
## Usage v2
80+
81+
It is necessary to register all valid `ISecurityTokenValidator` classes and configure the Authentication service using the `AddSimpleTokenAuthentication` extension method.
82+
83+
Example:
84+
85+
```csharp
86+
public class Startup
87+
{
88+
public void ConfigureServices(IServiceCollection services)
89+
{
90+
services.AddTransient<ISecurityTokenValidator, MyCustomTokenValidator>();
91+
services.AddAuthentication()
92+
.AddSimpleTokenAuthentication();
93+
}
94+
95+
public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory) {
96+
app.UseAuthentication();
97+
app.UseMvc();
98+
}
99+
}
100+
```
101+
102+
## Usage v1
80103

81104
It is necessary to register all valid `ISecurityTokenValidator` classes and add the middleware to ApplicationBuilder using `UseSimpleTokenAuthentication`.
82105

appveyor.yml

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
11
os: Visual Studio 2017
22

3-
version: 1.1.3-alpha-{build}
3+
version: 2.0.0-alpha-{build}
44

55
nuget:
66
project_feed: true
77

8-
install:
9-
- cmd: nuget sources add -Name makingsense-aspnet -Source https://ci.appveyor.com/nuget/makingsense-aspnet -UserName [email protected] -Password 4@pdw@BlfpQn
10-
118
before_build:
129
- cmd: set DOTNET_ASSEMBLY_FILE_VERSION=%APPVEYOR_BUILD_NUMBER%
1310
- cmd: set DOTNET_BUILD_VERSION=%APPVEYOR_BUILD_NUMBER%

src/MakingSense.AspNetCore.Authentication.SimpleToken/MakingSense.AspNetCore.Authentication.SimpleToken.csproj

Lines changed: 8 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,33 +3,26 @@
33
<PropertyGroup>
44
<Description>MakingSense.AspNetCore.Authentication.SimpleToken Class Library</Description>
55
<Authors>MakingSense</Authors>
6-
<TargetFrameworks>net451;netcoreapp1.1</TargetFrameworks>
6+
<TargetFramework>netstandard2.0</TargetFramework>
77
<AssemblyName>MakingSense.AspNetCore.Authentication.SimpleToken</AssemblyName>
88
<PackageId>MakingSense.AspNetCore.Authentication.SimpleToken</PackageId>
99
<PackageTags>ASP.NET 5;vnext;authentication;token;bearer</PackageTags>
1010
<PackageProjectUrl>https://github.com/MakingSense/aspnet-authentication-simpletoken</PackageProjectUrl>
1111
<PackageLicenseUrl>http://www.gnu.org/licenses/lgpl.html</PackageLicenseUrl>
1212
<RepositoryType>git</RepositoryType>
1313
<RepositoryUrl>git://github.com/MakingSense/aspnet-authentication-simpletoken</RepositoryUrl>
14-
<RuntimeFrameworkVersion Condition=" '$(TargetFramework)' == 'netcoreapp1.1' ">1.1.1</RuntimeFrameworkVersion>
15-
<VersionPrefix>1.1.3-alpha</VersionPrefix>
14+
<VersionPrefix>2.0.0-alpha</VersionPrefix>
1615
</PropertyGroup>
1716

1817
<ItemGroup>
19-
<PackageReference Include="MakingSense.AspNetCore.Abstractions" Version="1.1.3-alpha-*" />
20-
<PackageReference Include="Microsoft.AspNetCore.Authentication" Version="1.1.1" />
21-
<PackageReference Include="Microsoft.CSharp" Version="4.3.0" />
22-
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="5.1.3" />
23-
<PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
18+
<PackageReference Include="MakingSense.AspNetCore.Abstractions" Version="2.0.0-alpha-173" />
19+
<PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.0.0" />
20+
<PackageReference Include="Microsoft.CSharp" Version="4.5.0" />
21+
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.0.0" />
22+
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="5.4.0" />
23+
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
2424
<PackageReference Include="System.Linq" Version="4.3.0" />
2525
<PackageReference Include="System.Threading" Version="4.3.0" />
2626
</ItemGroup>
2727

28-
<ItemGroup Condition=" '$(TargetFramework)' == 'net451' ">
29-
<PackageReference Include="System.Collections" Version="4.3.0" />
30-
<PackageReference Include="System.Runtime" Version="4.3.0" />
31-
<Reference Include="System" />
32-
<Reference Include="Microsoft.CSharp" />
33-
</ItemGroup>
34-
3528
</Project>

src/MakingSense.AspNetCore.Authentication.SimpleToken/README.md

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
# SimpleToken Authentication Middleware
1+
# SimpleToken Authentication
22

33
This package allows to extract token from authenticated requests and delegate it to an appropriated ISecurityTokenValidator and generate and AuthenticationTicket.
44

55
## Behavior
66

77
### Token extraction details
88

9-
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).
9+
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).
1010

1111
There are three methods of sending tokens:
1212

@@ -76,7 +76,30 @@ For example:
7676
WWW-Authenticate: Bearer
7777
```
7878
79-
## Usage
79+
## Usage v2
80+
81+
It is necessary to register all valid `ISecurityTokenValidator` classes and configure the Authentication service using the `AddSimpleTokenAuthentication` extension method.
82+
83+
Example:
84+
85+
```csharp
86+
public class Startup
87+
{
88+
public void ConfigureServices(IServiceCollection services)
89+
{
90+
services.AddTransient<ISecurityTokenValidator, MyCustomTokenValidator>();
91+
services.AddAuthentication()
92+
.AddSimpleTokenAuthentication();
93+
}
94+
95+
public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory) {
96+
app.UseAuthentication();
97+
app.UseMvc();
98+
}
99+
}
100+
```
101+
102+
## Usage v1
80103

81104
It is necessary to register all valid `ISecurityTokenValidator` classes and add the middleware to ApplicationBuilder using `UseSimpleTokenAuthentication`.
82105

Lines changed: 4 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,11 @@
1-
using System;
1+
using System;
22
using MakingSense.AspNetCore.Authentication.SimpleToken;
3-
using Microsoft.Extensions.DependencyInjection;
4-
using Microsoft.Framework.Internal;
5-
using Microsoft.IdentityModel.Tokens;
6-
using Microsoft.Extensions.Options;
73

84
namespace Microsoft.AspNetCore.Builder
95
{
106
public static class SimpleTokenAppBuilderExtensions
117
{
8+
[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)]
129
public static IApplicationBuilder UseSimpleTokenAuthentication(this IApplicationBuilder app)
1310
{
1411
if (app == null)
@@ -19,38 +16,10 @@ public static IApplicationBuilder UseSimpleTokenAuthentication(this IApplication
1916
return UseSimpleTokenAuthentication(app, new SimpleTokenAuthenticationOptions());
2017
}
2118

19+
[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)]
2220
public static IApplicationBuilder UseSimpleTokenAuthentication(this IApplicationBuilder app, SimpleTokenAuthenticationOptions options)
2321
{
24-
if (app == null)
25-
{
26-
throw new ArgumentNullException(nameof(app));
27-
}
28-
29-
if (options == null)
30-
{
31-
throw new ArgumentNullException(nameof(options));
32-
}
33-
34-
if (string.IsNullOrEmpty(options.AuthenticationScheme))
35-
{
36-
options.AuthenticationScheme = "Bearer";
37-
}
38-
39-
if (options.SecurityTokenValidatorsFactory == null)
40-
{
41-
// TODO: fix it because it is using app services, and it should use scope services,
42-
// a work around could be:
43-
// ```
44-
// SecurityTokenValidatorsFactory = () =>
45-
// {
46-
// var context = app.ApplicationServices.GetService<IHttpContextAccessor>().HttpContext;
47-
// return context.RequestServices.GetServices<ISecurityTokenValidator>();
48-
// }
49-
// ```
50-
options.SecurityTokenValidatorsFactory = () => app.ApplicationServices.GetServices<ISecurityTokenValidator>();
51-
}
52-
53-
return app.UseMiddleware<SimpleTokenAuthenticationMiddleware>(Options.Create(options));
22+
throw new NotSupportedException("This method is no longer supported, see https://go.microsoft.com/fwlink/?linkid=845470");
5423
}
5524
}
5625
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
using Microsoft.AspNetCore.Authentication;
2+
using Microsoft.Extensions.DependencyInjection;
3+
using Microsoft.IdentityModel.Tokens;
4+
using System;
5+
6+
namespace MakingSense.AspNetCore.Authentication.SimpleToken
7+
{
8+
public static class SimpleTokenAuthenticationExtensions
9+
{
10+
public static AuthenticationBuilder AddSimpleTokenAuthentication(this AuthenticationBuilder builder)
11+
=> builder.AddSimpleTokenAuthentication(SimpleTokenDefaults.AuthenticationScheme, null);
12+
13+
public static AuthenticationBuilder AddSimpleTokenAuthentication(this AuthenticationBuilder builder,
14+
Action<SimpleTokenAuthenticationOptions> configureOptions)
15+
=> builder.AddSimpleTokenAuthentication(SimpleTokenDefaults.AuthenticationScheme, configureOptions);
16+
17+
public static AuthenticationBuilder AddSimpleTokenAuthentication(this AuthenticationBuilder builder,
18+
string authenticationScheme,
19+
Action<SimpleTokenAuthenticationOptions> configureOptions)
20+
=> builder.AddSimpleTokenAuthentication(authenticationScheme, SimpleTokenDefaults.DisplayName, configureOptions: configureOptions);
21+
22+
public static AuthenticationBuilder AddSimpleTokenAuthentication(this AuthenticationBuilder builder,
23+
string authenticationScheme,
24+
string displayName,
25+
Action<SimpleTokenAuthenticationOptions> configureOptions)
26+
{
27+
return builder.AddScheme<SimpleTokenAuthenticationOptions, SimpleTokenAuthenticationHandler>(authenticationScheme, displayName,
28+
(SimpleTokenAuthenticationOptions options) => {
29+
configureOptions?.Invoke(options);
30+
31+
if (options.SecurityTokenValidatorsFactory == null)
32+
{
33+
options.SecurityTokenValidatorsFactory = () =>
34+
{
35+
// TODO: fix it because it is using app services, and it should use scope services,
36+
// a work around could be:
37+
// ```
38+
// SecurityTokenValidatorsFactory = () =>
39+
// {
40+
// var context = builder.Services.BuildServiceProvider().GetService<IHttpContextAccessor>().HttpContext;
41+
// return context.RequestServices.GetServices<ISecurityTokenValidator>();
42+
// }
43+
// ```
44+
var serviceProvider = builder.Services.BuildServiceProvider();
45+
return serviceProvider.GetServices<ISecurityTokenValidator>();
46+
};
47+
}
48+
});
49+
}
50+
}
51+
}

src/MakingSense.AspNetCore.Authentication.SimpleToken/SimpleTokenAuthenticationHandler.cs

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,28 @@
1-
using System;
1+
using System;
22
using System.Text;
3+
using System.Text.Encodings.Web;
34
using System.Threading.Tasks;
45
using MakingSense.AspNetCore.Authentication.Abstractions;
56
using Microsoft.AspNetCore.Authentication;
6-
using Microsoft.AspNetCore.Builder;
77
using Microsoft.AspNetCore.Http;
8-
using Microsoft.AspNetCore.Http.Authentication;
8+
using Microsoft.Extensions.Logging;
9+
using Microsoft.Extensions.Options;
910
using Microsoft.IdentityModel.Tokens;
1011
using Microsoft.Net.Http.Headers;
1112

1213
namespace MakingSense.AspNetCore.Authentication.SimpleToken
1314
{
1415
public class SimpleTokenAuthenticationHandler : AuthenticationHandler<SimpleTokenAuthenticationOptions>
1516
{
17+
public SimpleTokenAuthenticationHandler(
18+
IOptionsMonitor<SimpleTokenAuthenticationOptions> options,
19+
ILoggerFactory logger,
20+
UrlEncoder encoder,
21+
ISystemClock clock)
22+
: base(options, logger, encoder, clock)
23+
{
24+
}
25+
1626
/// <summary>
1727
/// Overrides the standard AuthenticationHandler to be more robust supporting [RFC 6750](http://tools.ietf.org/html/rfc6750) and
1828
/// 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)
5363
return pair.Substring(ix + 1).Trim();
5464
}
5565
}
56-
5766
// Not so nice, but AuthenticateResult.Fail does not allow us to show the error
5867
throw new AuthenticationException("Authorization header exists but does not contains valid information.");
5968
}
@@ -67,41 +76,44 @@ public static string ExtractToken(HttpRequest request)
6776
return null;
6877
}
6978

70-
static readonly Task DoneTask = Task.FromResult(0);
71-
7279
/// <summary>
7380
/// Searches the 'Authorization' header for a 'Bearer' token. If the 'Bearer' token is found, it is validated using <see cref="TokenValidationParameters"/> set in the options.
7481
/// </summary>
7582
/// <returns></returns>
7683
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
7784
{
78-
var token = ExtractToken(Request);
79-
85+
string token;
86+
try
87+
{
88+
token = ExtractToken(Request);
89+
}
90+
catch (AuthenticationException ex)
91+
{
92+
return AuthenticateResult.Fail(ex.Message);
93+
}
8094
// If no token found, no further work possible
8195
if (string.IsNullOrEmpty(token))
8296
{
83-
return AuthenticateResult.Skip();
97+
return AuthenticateResult.NoResult();
8498
}
8599

86100
var validationParameters = Options.TokenValidationParameters.Clone();
87101

88-
SecurityToken validatedToken;
89102
var validators = Options.SecurityTokenValidatorsFactory();
90103
foreach (var validator in validators)
91104
{
92105
if (validator.CanReadToken(token))
93106
{
94-
var principal = validator.ValidateToken(token, validationParameters, out validatedToken);
95-
var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), Options.AuthenticationScheme);
107+
var principal = validator.ValidateToken(token, validationParameters, out SecurityToken validatedToken);
108+
var ticket = new AuthenticationTicket(principal, Scheme.Name);
96109
return AuthenticateResult.Success(ticket);
97110
}
98111
}
99112

100113
// Ugly patch to make this method should to be async in order to allow result caching by caller
101-
await DoneTask;
114+
await Task.CompletedTask;
102115

103-
// Not so nice, but AuthenticateResult.Fail does not allow us to show the error
104-
throw new AuthenticationException("Authorization token has been detected but it cannot be read.");
116+
return AuthenticateResult.Fail("Authorization token has been detected but it cannot be read.");
105117
}
106118
}
107119
}

0 commit comments

Comments
 (0)