Initial version
This commit is contained in:
+6
-21
@@ -2,7 +2,7 @@
|
|||||||
## Ignore Visual Studio temporary files, build results, and
|
## Ignore Visual Studio temporary files, build results, and
|
||||||
## files generated by popular Visual Studio add-ons.
|
## files generated by popular Visual Studio add-ons.
|
||||||
##
|
##
|
||||||
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
|
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
|
||||||
|
|
||||||
# User-specific files
|
# User-specific files
|
||||||
*.rsuser
|
*.rsuser
|
||||||
@@ -83,8 +83,6 @@ StyleCopReport.xml
|
|||||||
*.pgc
|
*.pgc
|
||||||
*.pgd
|
*.pgd
|
||||||
*.rsp
|
*.rsp
|
||||||
# but not Directory.Build.rsp, as it configures directory-level build defaults
|
|
||||||
!Directory.Build.rsp
|
|
||||||
*.sbr
|
*.sbr
|
||||||
*.tlb
|
*.tlb
|
||||||
*.tli
|
*.tli
|
||||||
@@ -209,6 +207,9 @@ PublishScripts/
|
|||||||
*.nuget.props
|
*.nuget.props
|
||||||
*.nuget.targets
|
*.nuget.targets
|
||||||
|
|
||||||
|
# Nuget personal access tokens and Credentials
|
||||||
|
nuget.config
|
||||||
|
|
||||||
# Microsoft Azure Build Output
|
# Microsoft Azure Build Output
|
||||||
csx/
|
csx/
|
||||||
*.build.csdef
|
*.build.csdef
|
||||||
@@ -297,17 +298,6 @@ node_modules/
|
|||||||
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
||||||
*.vbw
|
*.vbw
|
||||||
|
|
||||||
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
|
|
||||||
*.vbp
|
|
||||||
|
|
||||||
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
|
|
||||||
*.dsw
|
|
||||||
*.dsp
|
|
||||||
|
|
||||||
# Visual Studio 6 technical files
|
|
||||||
*.ncb
|
|
||||||
*.aps
|
|
||||||
|
|
||||||
# Visual Studio LightSwitch build output
|
# Visual Studio LightSwitch build output
|
||||||
**/*.HTMLClient/GeneratedArtifacts
|
**/*.HTMLClient/GeneratedArtifacts
|
||||||
**/*.DesktopClient/GeneratedArtifacts
|
**/*.DesktopClient/GeneratedArtifacts
|
||||||
@@ -364,9 +354,6 @@ ASALocalRun/
|
|||||||
# Local History for Visual Studio
|
# Local History for Visual Studio
|
||||||
.localhistory/
|
.localhistory/
|
||||||
|
|
||||||
# Visual Studio History (VSHistory) files
|
|
||||||
.vshistory/
|
|
||||||
|
|
||||||
# BeatPulse healthcheck temp database
|
# BeatPulse healthcheck temp database
|
||||||
healthchecksdb
|
healthchecksdb
|
||||||
|
|
||||||
@@ -398,6 +385,7 @@ FodyWeavers.xsd
|
|||||||
*.msp
|
*.msp
|
||||||
|
|
||||||
# JetBrains Rider
|
# JetBrains Rider
|
||||||
|
.idea/
|
||||||
*.sln.iml
|
*.sln.iml
|
||||||
|
|
||||||
# ---> VisualStudioCode
|
# ---> VisualStudioCode
|
||||||
@@ -406,11 +394,8 @@ FodyWeavers.xsd
|
|||||||
!.vscode/tasks.json
|
!.vscode/tasks.json
|
||||||
!.vscode/launch.json
|
!.vscode/launch.json
|
||||||
!.vscode/extensions.json
|
!.vscode/extensions.json
|
||||||
!.vscode/*.code-snippets
|
*.code-workspace
|
||||||
|
|
||||||
# Local History for Visual Studio Code
|
# Local History for Visual Studio Code
|
||||||
.history/
|
.history/
|
||||||
|
|
||||||
# Built Visual Studio Code Extensions
|
|
||||||
*.vsix
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<IsPackable>false</IsPackable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0" />
|
||||||
|
<PackageReference Include="xunit" Version="2.7.0" />
|
||||||
|
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.7" />
|
||||||
|
<PackageReference Include="FluentAssertions" Version="6.12.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\EonaCat.SecureToken\EonaCat.SecureToken.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,261 @@
|
|||||||
|
using FluentAssertions;
|
||||||
|
using SecureToken.Core;
|
||||||
|
using SecureToken.Cryptography;
|
||||||
|
using SecureToken.Validation;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace SecureToken.Tests
|
||||||
|
{
|
||||||
|
public sealed class TokenServiceTests
|
||||||
|
{
|
||||||
|
private static ITokenService CreateService(SigningKeyStore? store = null) =>
|
||||||
|
new TokenService(store ?? SigningKeyStore.CreateNew());
|
||||||
|
|
||||||
|
// ── Issue & Validate ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Issue_And_Validate_ReturnsSuccess()
|
||||||
|
{
|
||||||
|
var svc = CreateService();
|
||||||
|
var token = svc.Issue(TokenDescriptor.Create()
|
||||||
|
.ForSubject("user-123")
|
||||||
|
.IssuedBy("my-app")
|
||||||
|
.ForAudience("api")
|
||||||
|
.WithRole("admin")
|
||||||
|
.WithClaim("email", "user@example.com"));
|
||||||
|
|
||||||
|
var result = svc.Validate(token, TokenValidationOptions.AccessToken("my-app", "api"));
|
||||||
|
|
||||||
|
result.IsSuccess.Should().BeTrue();
|
||||||
|
var claims = result.UnwrapClaims();
|
||||||
|
claims.Subject.Should().Be("user-123");
|
||||||
|
claims.Roles.Should().Contain("admin");
|
||||||
|
claims.Custom["email"].Should().Be("user@example.com");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Validate_TamperedToken_ReturnsInvalidSignature()
|
||||||
|
{
|
||||||
|
var svc = CreateService();
|
||||||
|
var token = svc.Issue(TokenDescriptor.Create().ForSubject("user-1").IssuedBy("app").ForAudience("api"));
|
||||||
|
|
||||||
|
// Flip one character in the payload section
|
||||||
|
var parts = token.Split('.');
|
||||||
|
var corrupted = parts[0] + "." + parts[1].Substring(0, parts[1].Length - 1) + "X" + "." + parts[2];
|
||||||
|
|
||||||
|
var result = svc.Validate(corrupted, TokenValidationOptions.AccessToken("app", "api"));
|
||||||
|
|
||||||
|
result.Should().BeOfType<TokenResult.InvalidSignature>();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Validate_ExpiredToken_ReturnsExpired()
|
||||||
|
{
|
||||||
|
var svc = CreateService();
|
||||||
|
var token = svc.Issue(TokenDescriptor.Create()
|
||||||
|
.ForSubject("user-1")
|
||||||
|
.IssuedBy("app")
|
||||||
|
.ForAudience("api")
|
||||||
|
.WithLifetime(TimeSpan.FromMilliseconds(1)));
|
||||||
|
|
||||||
|
Thread.Sleep(50); // let it expire
|
||||||
|
|
||||||
|
var result = svc.Validate(token, new TokenValidationOptions
|
||||||
|
{
|
||||||
|
ValidIssuer = "app",
|
||||||
|
ValidAudience = "api",
|
||||||
|
RequiredTokenType = TokenTypeConstants.Access,
|
||||||
|
ClockSkew = TimeSpan.Zero,
|
||||||
|
});
|
||||||
|
|
||||||
|
result.Should().BeOfType<TokenResult.Expired>();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Validate_WrongAudience_ReturnsWrongAudience()
|
||||||
|
{
|
||||||
|
var svc = CreateService();
|
||||||
|
var token = svc.Issue(TokenDescriptor.Create()
|
||||||
|
.ForSubject("user-1")
|
||||||
|
.IssuedBy("app")
|
||||||
|
.ForAudience("service-a"));
|
||||||
|
|
||||||
|
var result = svc.Validate(token, TokenValidationOptions.AccessToken("app", "service-b"));
|
||||||
|
|
||||||
|
result.Should().BeOfType<TokenResult.WrongAudience>();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Validate_WrongTokenType_ReturnsWrongTokenType()
|
||||||
|
{
|
||||||
|
var svc = CreateService();
|
||||||
|
var refreshToken = svc.Issue(TokenDescriptor.Create()
|
||||||
|
.ForSubject("user-1")
|
||||||
|
.IssuedBy("app")
|
||||||
|
.AsRefreshToken());
|
||||||
|
|
||||||
|
// Try to use refresh token where access token is expected
|
||||||
|
var result = svc.Validate(refreshToken, TokenValidationOptions.AccessToken("app", "api"));
|
||||||
|
|
||||||
|
result.Should().BeOfType<TokenResult.WrongTokenType>();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Validate_BindingContextMismatch_ReturnsBindingMismatch()
|
||||||
|
{
|
||||||
|
var svc = CreateService();
|
||||||
|
var token = svc.Issue(TokenDescriptor.Create()
|
||||||
|
.ForSubject("user-1")
|
||||||
|
.IssuedBy("app")
|
||||||
|
.ForAudience("api")
|
||||||
|
.BoundTo("192.168.1.1"));
|
||||||
|
|
||||||
|
var result = svc.Validate(token, new TokenValidationOptions
|
||||||
|
{
|
||||||
|
ValidIssuer = "app",
|
||||||
|
ValidAudience = "api",
|
||||||
|
RequiredTokenType = TokenTypeConstants.Access,
|
||||||
|
BindingContext = "10.0.0.1", // different IP
|
||||||
|
});
|
||||||
|
|
||||||
|
result.Should().BeOfType<TokenResult.BindingMismatch>();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Validate_CorrectBindingContext_ReturnsSuccess()
|
||||||
|
{
|
||||||
|
var svc = CreateService();
|
||||||
|
var token = svc.Issue(TokenDescriptor.Create()
|
||||||
|
.ForSubject("user-1")
|
||||||
|
.IssuedBy("app")
|
||||||
|
.ForAudience("api")
|
||||||
|
.BoundTo("192.168.1.1"));
|
||||||
|
|
||||||
|
var result = svc.Validate(token, new TokenValidationOptions
|
||||||
|
{
|
||||||
|
ValidIssuer = "app",
|
||||||
|
ValidAudience = "api",
|
||||||
|
RequiredTokenType = TokenTypeConstants.Access,
|
||||||
|
BindingContext = "192.168.1.1",
|
||||||
|
});
|
||||||
|
|
||||||
|
result.IsSuccess.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Key Rotation ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void KeyRotation_OldTokensRemainValid()
|
||||||
|
{
|
||||||
|
var store = SigningKeyStore.CreateNew();
|
||||||
|
var svc = CreateService(store);
|
||||||
|
|
||||||
|
var oldToken = svc.Issue(TokenDescriptor.Create()
|
||||||
|
.ForSubject("user-1").IssuedBy("app").ForAudience("api"));
|
||||||
|
|
||||||
|
// Rotate the signing key
|
||||||
|
store.Rotate();
|
||||||
|
|
||||||
|
// Old token must still validate
|
||||||
|
var result = svc.Validate(oldToken, TokenValidationOptions.AccessToken("app", "api"));
|
||||||
|
result.IsSuccess.Should().BeTrue();
|
||||||
|
|
||||||
|
// New tokens use the new key
|
||||||
|
var newToken = svc.Issue(TokenDescriptor.Create()
|
||||||
|
.ForSubject("user-2").IssuedBy("app").ForAudience("api"));
|
||||||
|
var claims = svc.Inspect(newToken);
|
||||||
|
claims!.KeyGeneration.Should().Be(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void KeyRotation_NewTokensUseNewKey()
|
||||||
|
{
|
||||||
|
var store = SigningKeyStore.CreateNew();
|
||||||
|
var svc = CreateService(store);
|
||||||
|
|
||||||
|
store.Rotate();
|
||||||
|
store.Rotate();
|
||||||
|
|
||||||
|
var token = svc.Issue(TokenDescriptor.Create()
|
||||||
|
.ForSubject("user-1").IssuedBy("app").ForAudience("api"));
|
||||||
|
|
||||||
|
var claims = svc.Inspect(token);
|
||||||
|
claims!.KeyGeneration.Should().Be(3);
|
||||||
|
|
||||||
|
var result = svc.Validate(token, TokenValidationOptions.AccessToken("app", "api"));
|
||||||
|
result.IsSuccess.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Token Pair ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IssueTokenPair_ProducesValidPair()
|
||||||
|
{
|
||||||
|
var svc = CreateService();
|
||||||
|
var pair = svc.IssueTokenPair("user-1", "app", "api", roles: new[] { "user" });
|
||||||
|
|
||||||
|
var accessResult = svc.Validate(pair.AccessToken, TokenValidationOptions.AccessToken("app", "api"));
|
||||||
|
var refreshResult = svc.Validate(pair.RefreshToken, TokenValidationOptions.RefreshToken("app"));
|
||||||
|
|
||||||
|
accessResult.IsSuccess.Should().BeTrue();
|
||||||
|
refreshResult.IsSuccess.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IssueTokenPair_RefreshToken_CannotBeUsedAsAccessToken()
|
||||||
|
{
|
||||||
|
var svc = CreateService();
|
||||||
|
var pair = svc.IssueTokenPair("user-1", "app", "api");
|
||||||
|
|
||||||
|
// Try to validate refresh token as access token
|
||||||
|
var result = svc.Validate(pair.RefreshToken, TokenValidationOptions.AccessToken("app", "api"));
|
||||||
|
|
||||||
|
result.Should().BeOfType<TokenResult.WrongTokenType>();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Revocation ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task RevocationCheck_RevokedToken_ReturnsRevoked()
|
||||||
|
{
|
||||||
|
var svc = CreateService();
|
||||||
|
var token = svc.Issue(TokenDescriptor.Create()
|
||||||
|
.ForSubject("user-1").IssuedBy("app").ForAudience("api"));
|
||||||
|
|
||||||
|
var claims = svc.Inspect(token)!;
|
||||||
|
var revokedIds = new HashSet<string> { claims.TokenId };
|
||||||
|
|
||||||
|
var options = new TokenValidationOptions
|
||||||
|
{
|
||||||
|
ValidIssuer = "app",
|
||||||
|
ValidAudience = "api",
|
||||||
|
RequiredTokenType = TokenTypeConstants.Access,
|
||||||
|
RevocationCheck = (id, _) => Task.FromResult(revokedIds.Contains(id)),
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = await svc.ValidateAsync(token, options);
|
||||||
|
result.Should().BeOfType<TokenResult.Revoked>();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Inspect (no signature check) ─────────────────────────────────────────
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Inspect_MalformedToken_ReturnsNull()
|
||||||
|
{
|
||||||
|
var svc = CreateService();
|
||||||
|
svc.Inspect("not.a.valid.token").Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Inspect_ValidToken_ReturnsClaims()
|
||||||
|
{
|
||||||
|
var svc = CreateService();
|
||||||
|
var token = svc.Issue(TokenDescriptor.Create()
|
||||||
|
.ForSubject("user-42").IssuedBy("app").ForAudience("api"));
|
||||||
|
|
||||||
|
var claims = svc.Inspect(token);
|
||||||
|
claims.Should().NotBeNull();
|
||||||
|
claims!.Subject.Should().Be("user-42");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<Solution>
|
||||||
|
<Folder Name="/Solution Items/">
|
||||||
|
<File Path="readme.md" />
|
||||||
|
</Folder>
|
||||||
|
<Project Path="EonaCat.SecureToken.Tests/EonaCat.SecureToken.Tests.csproj" />
|
||||||
|
<Project Path="EonaCat.SecureToken/EonaCat.SecureToken.csproj" />
|
||||||
|
</Solution>
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
|
<ApplicationIcon>icon.ico</ApplicationIcon>
|
||||||
|
<LangVersion>latest</LangVersion>
|
||||||
|
<Authors>EonaCat (Jeroen Saey)</Authors>
|
||||||
|
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
||||||
|
<Company>EonaCat (Jeroen Saey)</Company>
|
||||||
|
<PackageIcon>icon.png</PackageIcon>
|
||||||
|
<PackageProjectUrl>https://www.nuget.org/packages/EonaCat.SecureToken/</PackageProjectUrl>
|
||||||
|
<Description>A modern, cryptographically superior alternative to JWT. SecureToken,
|
||||||
|
structured binding, built-in rotation, and opaque reference tokens with zero parsing vulnerabilities.</Description>
|
||||||
|
<PackageReleaseNotes>Public release version</PackageReleaseNotes>
|
||||||
|
<Copyright>EonaCat (Jeroen Saey)</Copyright>
|
||||||
|
<PackageTags>EonaCat;authentication;token;paseto;security;auth;jwt-alternative;Jeroen;Saey</PackageTags>
|
||||||
|
<PackageIconUrl />
|
||||||
|
<FileVersion>0.1.1</FileVersion>
|
||||||
|
<PackageReadmeFile>README.md</PackageReadmeFile>
|
||||||
|
<GenerateDocumentationFile>True</GenerateDocumentationFile>
|
||||||
|
<PackageLicenseFile>LICENSE</PackageLicenseFile>
|
||||||
|
|
||||||
|
<PackageRequireLicenseAcceptance>True</PackageRequireLicenseAcceptance>
|
||||||
|
<Title>EonaCat.SecureToken</Title>
|
||||||
|
<RepositoryType>git</RepositoryType>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<EVRevisionFormat>0.0.1+{chash:10}.{c:ymd}</EVRevisionFormat>
|
||||||
|
<EVDefault>true</EVDefault>
|
||||||
|
<EVInfo>true</EVInfo>
|
||||||
|
<EVTagMatch>v[0-9]*</EVTagMatch>
|
||||||
|
<EVRemoveTagV>true</EVRemoveTagV>
|
||||||
|
<EVVcs>git</EVVcs>
|
||||||
|
<EVCheckAllAttributes>true</EVCheckAllAttributes>
|
||||||
|
<EVShowRevision>true</EVShowRevision>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<Version>0.0.1</Version>
|
||||||
|
<PackageId>EonaCat.SecureToken</PackageId>
|
||||||
|
<Product>EonaCat.SecureToken</Product>
|
||||||
|
<RepositoryUrl>https://git.saey.me/EonaCat/EonaCat.SecureToken</RepositoryUrl>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<Target Name="EVPack" BeforeTargets="Pack">
|
||||||
|
<Message Text="EVPack: Forcing NuGet Version = $(GeneratedVersion)" Importance="High" />
|
||||||
|
<PropertyGroup>
|
||||||
|
<Version>$(GeneratedVersion)</Version>
|
||||||
|
</PropertyGroup>
|
||||||
|
</Target>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Remove="icon.png" />
|
||||||
|
<Content Include="icon.ico" />
|
||||||
|
<None Include="..\LICENSE">
|
||||||
|
<Pack>True</Pack>
|
||||||
|
<PackagePath>\</PackagePath>
|
||||||
|
</None>
|
||||||
|
<None Include="..\README.md">
|
||||||
|
<Pack>True</Pack>
|
||||||
|
<PackagePath>\</PackagePath>
|
||||||
|
</None>
|
||||||
|
<None Include="..\icon.png">
|
||||||
|
<Pack>True</Pack>
|
||||||
|
<PackagePath>
|
||||||
|
</PackagePath>
|
||||||
|
</None>
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="EonaCat.Versioning" Version="1.5.8">
|
||||||
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
</PackageReference>
|
||||||
|
<PackageReference Include="EonaCat.Versioning.Helpers" Version="1.5.1" />
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Net.Http.Headers" Version="2.3.11" />
|
||||||
|
<PackageReference Include="System.Memory" Version="4.5.5" />
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<None Update="LICENSE.md">
|
||||||
|
<Pack>True</Pack>
|
||||||
|
<PackagePath>\</PackagePath>
|
||||||
|
</None>
|
||||||
|
<None Update="README.md">
|
||||||
|
<Pack>True</Pack>
|
||||||
|
<PackagePath>\</PackagePath>
|
||||||
|
</None>
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using SecureToken.Cryptography;
|
||||||
|
using System;
|
||||||
|
|
||||||
|
|
||||||
|
namespace SecureToken.Extensions
|
||||||
|
{
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extension methods for registering SecureToken services with the DI container.
|
||||||
|
/// </summary>
|
||||||
|
public static class ServiceCollectionExtensions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Adds SecureToken services using a randomly generated ephemeral key.
|
||||||
|
/// Use <see cref="AddSecureTokens(IServiceCollection, SigningKeyStore)"/> in production
|
||||||
|
/// to supply a persistent, managed key store.
|
||||||
|
/// </summary>
|
||||||
|
public static IServiceCollection AddSecureTokens(this IServiceCollection services)
|
||||||
|
{
|
||||||
|
var keyStore = SigningKeyStore.CreateNew();
|
||||||
|
return services.AddSecureTokens(keyStore);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Adds SecureToken services with a supplied key store.
|
||||||
|
/// </summary>
|
||||||
|
public static IServiceCollection AddSecureTokens(
|
||||||
|
this IServiceCollection services,
|
||||||
|
SigningKeyStore keyStore)
|
||||||
|
{
|
||||||
|
services.AddSingleton(keyStore);
|
||||||
|
services.AddSingleton<ITokenService, TokenService>();
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Adds SecureToken services with a factory function to configure the key store.
|
||||||
|
/// Useful when loading keys from environment variables or a secret manager.
|
||||||
|
/// </summary>
|
||||||
|
public static IServiceCollection AddSecureTokens(
|
||||||
|
this IServiceCollection services,
|
||||||
|
Func<IServiceProvider, SigningKeyStore> keyStoreFactory)
|
||||||
|
{
|
||||||
|
services.AddSingleton(keyStoreFactory);
|
||||||
|
services.AddSingleton<ITokenService, TokenService>();
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Net.Http.Headers;
|
||||||
|
using SecureToken.Validation;
|
||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace SecureToken.Extensions
|
||||||
|
{
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Middleware that validates a SecureToken from the Authorization header
|
||||||
|
/// and makes the claims available on <see cref="HttpContext.Items"/>.
|
||||||
|
/// This is a lightweight alternative to full ASP.NET Core authentication middleware.
|
||||||
|
/// For full integration, use the authentication handler instead.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class SecureTokenMiddleware
|
||||||
|
{
|
||||||
|
private readonly RequestDelegate _next;
|
||||||
|
private readonly TokenValidationOptions _options;
|
||||||
|
private readonly ILogger<SecureTokenMiddleware> _logger;
|
||||||
|
|
||||||
|
/// <summary>HttpContext.Items key where validated claims are stored.</summary>
|
||||||
|
public const string ClaimsItemKey = "SecureToken.Claims";
|
||||||
|
|
||||||
|
public SecureTokenMiddleware(
|
||||||
|
RequestDelegate next,
|
||||||
|
TokenValidationOptions options,
|
||||||
|
ILogger<SecureTokenMiddleware> logger)
|
||||||
|
{
|
||||||
|
_next = next;
|
||||||
|
_options = options;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task InvokeAsync(HttpContext context, ITokenService tokenService)
|
||||||
|
{
|
||||||
|
var authHeader = context.Request.Headers[HeaderNames.Authorization]
|
||||||
|
.FirstOrDefault();
|
||||||
|
|
||||||
|
if (authHeader?.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) == true)
|
||||||
|
{
|
||||||
|
var token = authHeader.Substring("Bearer ".Length).Trim();
|
||||||
|
|
||||||
|
var result = await tokenService.ValidateAsync(token, _options, context.RequestAborted);
|
||||||
|
|
||||||
|
if (result.IsSuccess)
|
||||||
|
{
|
||||||
|
context.Items[ClaimsItemKey] = result.UnwrapClaims();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_logger.LogDebug("Token validation failed: {Result}", result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await _next(context);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Provides extension methods to extract SecureToken claims from <see cref="HttpContext"/>.
|
||||||
|
/// </summary>
|
||||||
|
public static class HttpContextExtensions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Returns the validated token claims from the current request, or null if
|
||||||
|
/// no valid token was presented.
|
||||||
|
/// </summary>
|
||||||
|
public static Core.TokenClaims? GetTokenClaims(this HttpContext context) =>
|
||||||
|
context.Items.TryGetValue(SecureTokenMiddleware.ClaimsItemKey, out var claims)
|
||||||
|
? claims as Core.TokenClaims
|
||||||
|
: null;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Returns true if the current request has a validated token with the given role.
|
||||||
|
/// </summary>
|
||||||
|
public static bool HasRole(this HttpContext context, string role)
|
||||||
|
{
|
||||||
|
var claims = context.GetTokenClaims();
|
||||||
|
return claims?.Roles.Contains(role) == true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
|
||||||
|
namespace SecureToken.Cryptography
|
||||||
|
{
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Manages a versioned set of signing keys, enabling seamless key rotation.
|
||||||
|
/// Old tokens remain verifiable while new tokens always use the latest key.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class SigningKeyStore
|
||||||
|
{
|
||||||
|
private readonly SortedDictionary<int, byte[]> _keys = new SortedDictionary<int, byte[]>();
|
||||||
|
private int _currentGeneration;
|
||||||
|
|
||||||
|
private SigningKeyStore() { }
|
||||||
|
|
||||||
|
/// <summary>Creates a new key store with a single randomly generated key.</summary>
|
||||||
|
public static SigningKeyStore CreateNew()
|
||||||
|
{
|
||||||
|
var store = new SigningKeyStore();
|
||||||
|
store.AddNewKey(RandomNumberGenerator.GetBytes(64));
|
||||||
|
return store;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Creates a key store from an existing set of versioned keys.</summary>
|
||||||
|
public static SigningKeyStore FromKeys(IEnumerable<(int generation, byte[] keyMaterial)> keys)
|
||||||
|
{
|
||||||
|
var store = new SigningKeyStore();
|
||||||
|
foreach (var (gen, key) in keys)
|
||||||
|
{
|
||||||
|
if (key.Length < 32)
|
||||||
|
{
|
||||||
|
throw new ArgumentException($"Key generation {gen} must be at least 32 bytes.");
|
||||||
|
}
|
||||||
|
|
||||||
|
store._keys[gen] = key;
|
||||||
|
if (gen > store._currentGeneration)
|
||||||
|
{
|
||||||
|
store._currentGeneration = gen;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return store;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Rotates to a new key. Old tokens remain verifiable until they expire.
|
||||||
|
/// New tokens are signed with the new key.
|
||||||
|
/// </summary>
|
||||||
|
public int Rotate(byte[]? newKeyMaterial = null)
|
||||||
|
{
|
||||||
|
var material = newKeyMaterial ?? RandomNumberGenerator.GetBytes(64);
|
||||||
|
return AddNewKey(material);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Removes expired key generations to free memory. Only remove if all tokens from that generation are expired.</summary>
|
||||||
|
public void PruneGeneration(int generation) => _keys.Remove(generation);
|
||||||
|
|
||||||
|
public int CurrentGeneration => _currentGeneration;
|
||||||
|
|
||||||
|
internal byte[] GetCurrentKey() => _keys[_currentGeneration];
|
||||||
|
|
||||||
|
internal bool TryGetKey(int generation, out byte[] key)
|
||||||
|
{
|
||||||
|
if (_keys.TryGetValue(generation, out var k))
|
||||||
|
{
|
||||||
|
key = k;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
key = new byte[32];
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int AddNewKey(byte[] material)
|
||||||
|
{
|
||||||
|
var gen = _currentGeneration + 1;
|
||||||
|
_keys[gen] = material;
|
||||||
|
_currentGeneration = gen;
|
||||||
|
return gen;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Low-level HMAC-SHA256 signer. All signing is deterministic and uses a separate
|
||||||
|
/// per-field HKDF-derived sub-key to prevent cross-context attacks.
|
||||||
|
/// </summary>
|
||||||
|
internal static class TokenSigner
|
||||||
|
{
|
||||||
|
private const string SigningInfo = "SecureToken-v1-Signing";
|
||||||
|
private const string EncryptionInfo = "SecureToken-v1-Encryption";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Derives a context-specific signing sub-key using HKDF to prevent
|
||||||
|
/// the same key material being misused across different contexts.
|
||||||
|
/// </summary>
|
||||||
|
public static byte[] DeriveSigningKey(byte[] masterKey, string context)
|
||||||
|
{
|
||||||
|
// HKDF-Extract + HKDF-Expand
|
||||||
|
var prk = HMACSHA256.HashData(masterKey, System.Text.Encoding.UTF8.GetBytes(context));
|
||||||
|
var info = System.Text.Encoding.UTF8.GetBytes(SigningInfo + "|" + context);
|
||||||
|
return HKDF.Expand(HashAlgorithmName.SHA256, prk, 32, info);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] Sign(byte[] signingKey, byte[] payload) =>
|
||||||
|
HMACSHA256.HashData(signingKey, payload);
|
||||||
|
|
||||||
|
public static bool Verify(byte[] signingKey, byte[] payload, byte[] signature)
|
||||||
|
{
|
||||||
|
var expected = Sign(signingKey, payload);
|
||||||
|
// Constant-time comparison to prevent timing attacks
|
||||||
|
return CryptographicOperations.FixedTimeEquals(expected, signature);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace SecureToken.Core
|
||||||
|
{
|
||||||
|
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Represents the claims payload of a SecureToken.
|
||||||
|
/// Strongly-typed and tamper-evident - no algorithm confusion possible.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class TokenClaims
|
||||||
|
{
|
||||||
|
/// <summary>Unique token identifier (prevents replay attacks).</summary>
|
||||||
|
public string TokenId { get; set; } = Guid.NewGuid().ToString("N");
|
||||||
|
|
||||||
|
/// <summary>Subject identifier (user ID, service account, etc.).</summary>
|
||||||
|
public string Subject { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>Issuer of the token.</summary>
|
||||||
|
public string Issuer { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>Intended audience(s) for the token.</summary>
|
||||||
|
public IReadOnlyList<string> Audiences { get; set; } = new List<string>();
|
||||||
|
|
||||||
|
/// <summary>Roles assigned to the subject.</summary>
|
||||||
|
public IReadOnlyList<string> Roles { get; set; } = new List<string>();
|
||||||
|
|
||||||
|
/// <summary>Arbitrary key-value claims.</summary>
|
||||||
|
public IReadOnlyDictionary<string, string> Custom { get; set; } = new Dictionary<string, string>();
|
||||||
|
|
||||||
|
/// <summary>UTC time when the token was issued.</summary>
|
||||||
|
public DateTimeOffset IssuedAt { get; set; } = DateTimeOffset.UtcNow;
|
||||||
|
|
||||||
|
/// <summary>UTC time after which the token is valid.</summary>
|
||||||
|
public DateTimeOffset NotBefore { get; set; } = DateTimeOffset.UtcNow;
|
||||||
|
|
||||||
|
/// <summary>UTC time when the token expires.</summary>
|
||||||
|
public DateTimeOffset ExpiresAt { get; set; } = DateTimeOffset.UtcNow.AddHours(1);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Optional context binding - token is only valid for a specific IP / device fingerprint / etc.
|
||||||
|
/// Prevents token theft across contexts.
|
||||||
|
/// </summary>
|
||||||
|
public string? BindingContext { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The generation of the signing key used. Enables seamless key rotation.
|
||||||
|
/// </summary>
|
||||||
|
public int KeyGeneration { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Token type tag - prevents cross-purpose token misuse.</summary>
|
||||||
|
public string TokenType { get; set; } = TokenTypeConstants.Access;
|
||||||
|
|
||||||
|
public bool IsExpired(DateTimeOffset? now = null) =>
|
||||||
|
(now ?? DateTimeOffset.UtcNow) >= ExpiresAt;
|
||||||
|
|
||||||
|
public bool IsActive(DateTimeOffset? now = null)
|
||||||
|
{
|
||||||
|
var utcNow = now ?? DateTimeOffset.UtcNow;
|
||||||
|
return utcNow >= NotBefore && utcNow < ExpiresAt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Well-known token type constants to prevent cross-type confusion attacks.</summary>
|
||||||
|
public static class TokenTypeConstants
|
||||||
|
{
|
||||||
|
public const string Access = "at+secure";
|
||||||
|
public const string Refresh = "rt+secure";
|
||||||
|
public const string ServiceAccount = "sa+secure";
|
||||||
|
public const string Invitation = "inv+secure";
|
||||||
|
public const string PasswordReset = "pwr+secure";
|
||||||
|
public const string EmailVerification = "ev+secure";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace SecureToken.Core
|
||||||
|
{
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Fluent builder for constructing token claims before issuing.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class TokenDescriptor
|
||||||
|
{
|
||||||
|
private string _subject = string.Empty;
|
||||||
|
private string _issuer = string.Empty;
|
||||||
|
private readonly List<string> _audiences = new List<string>();
|
||||||
|
private readonly List<string> _roles = new List<string>();
|
||||||
|
private readonly Dictionary<string, string> _custom = new Dictionary<string, string>();
|
||||||
|
private TimeSpan _lifetime = TimeSpan.FromHours(1);
|
||||||
|
private TimeSpan _notBeforeDelay = TimeSpan.Zero;
|
||||||
|
private string? _bindingContext;
|
||||||
|
private string _tokenType = TokenTypeConstants.Access;
|
||||||
|
|
||||||
|
public static TokenDescriptor Create() => new TokenDescriptor();
|
||||||
|
|
||||||
|
public TokenDescriptor ForSubject(string subject)
|
||||||
|
{
|
||||||
|
_subject = subject;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public TokenDescriptor IssuedBy(string issuer)
|
||||||
|
{
|
||||||
|
_issuer = issuer;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public TokenDescriptor ForAudience(string audience)
|
||||||
|
{
|
||||||
|
_audiences.Add(audience);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public TokenDescriptor ForAudiences(IEnumerable<string> audiences)
|
||||||
|
{
|
||||||
|
_audiences.AddRange(audiences);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public TokenDescriptor WithRole(string role)
|
||||||
|
{
|
||||||
|
_roles.Add(role);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public TokenDescriptor WithRoles(IEnumerable<string> roles)
|
||||||
|
{
|
||||||
|
_roles.AddRange(roles);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public TokenDescriptor WithClaim(string key, string value)
|
||||||
|
{
|
||||||
|
_custom[key] = value;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public TokenDescriptor WithLifetime(TimeSpan lifetime)
|
||||||
|
{
|
||||||
|
if (lifetime <= TimeSpan.Zero)
|
||||||
|
{
|
||||||
|
throw new ArgumentOutOfRangeException(nameof(lifetime), "Lifetime must be positive.");
|
||||||
|
}
|
||||||
|
|
||||||
|
_lifetime = lifetime;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public TokenDescriptor ExpiresIn(int minutes) =>
|
||||||
|
WithLifetime(TimeSpan.FromMinutes(minutes));
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Bind this token to a specific context (IP address, device fingerprint, etc.).
|
||||||
|
/// The same binding must be provided during validation.
|
||||||
|
/// </summary>
|
||||||
|
public TokenDescriptor BoundTo(string context)
|
||||||
|
{
|
||||||
|
_bindingContext = context;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Tag the token type to prevent cross-purpose usage.
|
||||||
|
/// Use <see cref="TokenTypeConstants"/> for well-known values.
|
||||||
|
/// </summary>
|
||||||
|
public TokenDescriptor OfType(string tokenType)
|
||||||
|
{
|
||||||
|
_tokenType = tokenType;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public TokenDescriptor AsRefreshToken() => OfType(TokenTypeConstants.Refresh);
|
||||||
|
public TokenDescriptor AsServiceAccount() => OfType(TokenTypeConstants.ServiceAccount);
|
||||||
|
|
||||||
|
public TokenDescriptor NotValidBefore(TimeSpan delay)
|
||||||
|
{
|
||||||
|
_notBeforeDelay = delay;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal TokenClaims Build(int keyGeneration = 0)
|
||||||
|
{
|
||||||
|
var now = DateTimeOffset.UtcNow;
|
||||||
|
return new TokenClaims
|
||||||
|
{
|
||||||
|
Subject = _subject,
|
||||||
|
Issuer = _issuer,
|
||||||
|
Audiences = _audiences.AsReadOnly(),
|
||||||
|
Roles = _roles.AsReadOnly(),
|
||||||
|
Custom = _custom,
|
||||||
|
IssuedAt = now,
|
||||||
|
NotBefore = now + _notBeforeDelay,
|
||||||
|
ExpiresAt = now + _lifetime,
|
||||||
|
BindingContext = _bindingContext,
|
||||||
|
TokenType = _tokenType,
|
||||||
|
KeyGeneration = keyGeneration,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
using SecureToken.Core;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace SecureToken
|
||||||
|
{
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A paired access + refresh token, typically issued at login.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class TokenPair
|
||||||
|
{
|
||||||
|
public string AccessToken { get; set; }
|
||||||
|
public string RefreshToken { get; set; }
|
||||||
|
public DateTimeOffset AccessTokenExpiry { get; set; }
|
||||||
|
public DateTimeOffset RefreshTokenExpiry { get; set; }
|
||||||
|
|
||||||
|
public TokenPair(string accessToken, string refreshToken, DateTimeOffset accessTokenExpiry, DateTimeOffset refreshTokenExpiry)
|
||||||
|
{
|
||||||
|
AccessToken = accessToken;
|
||||||
|
RefreshToken = refreshToken;
|
||||||
|
AccessTokenExpiry = accessTokenExpiry;
|
||||||
|
RefreshTokenExpiry = refreshTokenExpiry;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Extension methods on <see cref="ITokenService"/> for common scenarios.
|
||||||
|
/// </summary>
|
||||||
|
public static class TokenServiceExtensions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Issues a standard access + refresh token pair.
|
||||||
|
/// Access token is short-lived; refresh token is long-lived but type-tagged.
|
||||||
|
/// </summary>
|
||||||
|
public static TokenPair IssueTokenPair(
|
||||||
|
this ITokenService service,
|
||||||
|
string subject,
|
||||||
|
string issuer,
|
||||||
|
string audience,
|
||||||
|
IEnumerable<string>? roles = null,
|
||||||
|
IEnumerable<KeyValuePair<string, string>>? claims = null,
|
||||||
|
TimeSpan? accessTokenLifetime = null,
|
||||||
|
TimeSpan? refreshTokenLifetime = null,
|
||||||
|
string? bindingContext = null)
|
||||||
|
{
|
||||||
|
var accessLifetime = accessTokenLifetime ?? TimeSpan.FromMinutes(15);
|
||||||
|
var refreshLifetime = refreshTokenLifetime ?? TimeSpan.FromDays(30);
|
||||||
|
|
||||||
|
var accessDescriptor = TokenDescriptor.Create()
|
||||||
|
.ForSubject(subject)
|
||||||
|
.IssuedBy(issuer)
|
||||||
|
.ForAudience(audience)
|
||||||
|
.WithLifetime(accessLifetime)
|
||||||
|
.OfType(TokenTypeConstants.Access);
|
||||||
|
|
||||||
|
var refreshDescriptor = TokenDescriptor.Create()
|
||||||
|
.ForSubject(subject)
|
||||||
|
.IssuedBy(issuer)
|
||||||
|
.WithLifetime(refreshLifetime)
|
||||||
|
.AsRefreshToken();
|
||||||
|
|
||||||
|
if (roles != null)
|
||||||
|
{
|
||||||
|
foreach (var role in roles)
|
||||||
|
{
|
||||||
|
accessDescriptor.WithRole(role);
|
||||||
|
refreshDescriptor.WithRole(role);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (claims != null)
|
||||||
|
{
|
||||||
|
foreach (var claim in claims)
|
||||||
|
{
|
||||||
|
accessDescriptor.WithClaim(claim.Key, claim.Value);
|
||||||
|
refreshDescriptor.WithClaim(claim.Key, claim.Value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bindingContext != null)
|
||||||
|
{
|
||||||
|
accessDescriptor.BoundTo(bindingContext);
|
||||||
|
refreshDescriptor.BoundTo(bindingContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
var now = DateTimeOffset.UtcNow;
|
||||||
|
var accessToken = service.Issue(accessDescriptor);
|
||||||
|
var refreshToken = service.Issue(refreshDescriptor);
|
||||||
|
|
||||||
|
return new TokenPair(
|
||||||
|
accessToken,
|
||||||
|
refreshToken,
|
||||||
|
now + accessLifetime,
|
||||||
|
now + refreshLifetime
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace SecureToken.Core
|
||||||
|
{
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
public abstract class TokenResult
|
||||||
|
{
|
||||||
|
private TokenResult() { }
|
||||||
|
public sealed class Success : TokenResult { public string Token; public TokenClaims Claims; public Success(string token, TokenClaims claims) { Token = token; Claims = claims; } }
|
||||||
|
public sealed class Expired : TokenResult { public DateTimeOffset ExpiredAt; public Expired(DateTimeOffset v) { ExpiredAt = v; } }
|
||||||
|
public sealed class InvalidSignature : TokenResult { }
|
||||||
|
public sealed class NotYetValid : TokenResult { public DateTimeOffset ValidFrom; public NotYetValid(DateTimeOffset v) { ValidFrom = v; } }
|
||||||
|
public sealed class WrongAudience : TokenResult { public string Expected; public IReadOnlyList<string> Actual; public WrongAudience(string e, IReadOnlyList<string> a) { Expected = e; Actual = a; } }
|
||||||
|
public sealed class WrongTokenType : TokenResult { public string Expected; public string Actual; public WrongTokenType(string e, string a) { Expected = e; Actual = a; } }
|
||||||
|
public sealed class UntrustedIssuer : TokenResult { public string Issuer; public UntrustedIssuer(string i) { Issuer = i; } }
|
||||||
|
public sealed class BindingMismatch : TokenResult { public string Reason; public BindingMismatch(string r) { Reason = r; } }
|
||||||
|
public sealed class Revoked : TokenResult { public string TokenId; public Revoked(string t) { TokenId = t; } }
|
||||||
|
public sealed class Malformed : TokenResult { public string Reason; public Malformed(string r) { Reason = r; } }
|
||||||
|
public bool IsSuccess => this is Success;
|
||||||
|
public TokenClaims UnwrapClaims() { var s = this as Success; if (s != null) { return s.Claims; } throw new InvalidOperationException(); }
|
||||||
|
public T Match<T>(Func<Success, T> onSuccess, Func<TokenResult, T> onFailure) { var s = this as Success; return s != null ? onSuccess(s) : onFailure(this); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
using SecureToken.Core;
|
||||||
|
using SecureToken.Cryptography;
|
||||||
|
using SecureToken.Tokens;
|
||||||
|
using SecureToken.Validation;
|
||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace SecureToken
|
||||||
|
{
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Core service for issuing and validating SecureTokens.
|
||||||
|
/// </summary>
|
||||||
|
public interface ITokenService
|
||||||
|
{
|
||||||
|
/// <summary>Issues a new signed token from the descriptor.</summary>
|
||||||
|
string Issue(TokenDescriptor descriptor);
|
||||||
|
|
||||||
|
/// <summary>Validates a token string and returns a typed result.</summary>
|
||||||
|
Task<TokenResult> ValidateAsync(string token, TokenValidationOptions options, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>Validates synchronously (no revocation check).</summary>
|
||||||
|
TokenResult Validate(string token, TokenValidationOptions options);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Parses the token claims without verifying the signature.
|
||||||
|
/// Use only for diagnostic purposes - never for authorization.
|
||||||
|
/// </summary>
|
||||||
|
TokenClaims? Inspect(string token);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Default implementation of <see cref="ITokenService"/>.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class TokenService : ITokenService
|
||||||
|
{
|
||||||
|
private readonly SigningKeyStore _keyStore;
|
||||||
|
|
||||||
|
public TokenService(SigningKeyStore keyStore)
|
||||||
|
{
|
||||||
|
_keyStore = keyStore;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public string Issue(TokenDescriptor descriptor)
|
||||||
|
{
|
||||||
|
var generation = _keyStore.CurrentGeneration;
|
||||||
|
var claims = descriptor.Build(generation);
|
||||||
|
|
||||||
|
if (!_keyStore.TryGetKey(generation, out var masterKey))
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("No signing key available.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var signingKey = TokenSigner.DeriveSigningKey(masterKey, claims.TokenType);
|
||||||
|
var payload = TokenSerializer.Serialize(claims);
|
||||||
|
var signature = TokenSigner.Sign(signingKey, payload);
|
||||||
|
|
||||||
|
return TokenSerializer.Encode(payload, signature);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public async Task<TokenResult> ValidateAsync(
|
||||||
|
string token,
|
||||||
|
TokenValidationOptions options,
|
||||||
|
CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var result = Validate(token, options);
|
||||||
|
|
||||||
|
if (result is TokenResult.Success success && options.RevocationCheck != null)
|
||||||
|
{
|
||||||
|
var isRevoked = await options.RevocationCheck(success.Claims.TokenId, ct);
|
||||||
|
if (isRevoked)
|
||||||
|
{
|
||||||
|
return new TokenResult.Revoked(success.Claims.TokenId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public TokenResult Validate(string token, TokenValidationOptions options)
|
||||||
|
{
|
||||||
|
if (!TokenSerializer.TryDecode(token, out var payload, out var signature))
|
||||||
|
{
|
||||||
|
return new TokenResult.Malformed("Token format is invalid.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var claims = TokenSerializer.Deserialize(payload);
|
||||||
|
if (claims is null)
|
||||||
|
{
|
||||||
|
return new TokenResult.Malformed("Token payload could not be decoded.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Retrieve the signing key for this token's generation
|
||||||
|
if (!_keyStore.TryGetKey(claims.KeyGeneration, out var masterKey))
|
||||||
|
{
|
||||||
|
return new TokenResult.InvalidSignature();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Always verify with the token's embedded type-derived key first.
|
||||||
|
// This prevents valid refresh tokens from being reported as invalid
|
||||||
|
// signatures when an access token is expected.
|
||||||
|
var signingKey = TokenSigner.DeriveSigningKey(masterKey, claims.TokenType);
|
||||||
|
|
||||||
|
if (!TokenSigner.Verify(signingKey, payload, signature))
|
||||||
|
{
|
||||||
|
return new TokenResult.InvalidSignature();
|
||||||
|
}
|
||||||
|
|
||||||
|
var now = DateTimeOffset.UtcNow;
|
||||||
|
var skew = options.ClockSkew;
|
||||||
|
|
||||||
|
// Token type check
|
||||||
|
if (options.RequiredTokenType != null && claims.TokenType != options.RequiredTokenType)
|
||||||
|
{
|
||||||
|
return new TokenResult.WrongTokenType(options.RequiredTokenType, claims.TokenType);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Expiry check
|
||||||
|
if (options.ValidateExpiry && now > claims.ExpiresAt + skew)
|
||||||
|
{
|
||||||
|
return new TokenResult.Expired(claims.ExpiresAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Not-before check
|
||||||
|
if (options.ValidateNotBefore && now < claims.NotBefore - skew)
|
||||||
|
{
|
||||||
|
return new TokenResult.NotYetValid(claims.NotBefore);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Issuer check
|
||||||
|
if (options.ValidIssuer != null && claims.Issuer != options.ValidIssuer)
|
||||||
|
{
|
||||||
|
return new TokenResult.UntrustedIssuer(claims.Issuer);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Audience check
|
||||||
|
if (options.ValidAudience != null && !claims.Audiences.Contains(options.ValidAudience))
|
||||||
|
{
|
||||||
|
return new TokenResult.WrongAudience(options.ValidAudience, claims.Audiences);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Binding check
|
||||||
|
if (options.BindingContext != null)
|
||||||
|
{
|
||||||
|
if (claims.BindingContext is null)
|
||||||
|
{
|
||||||
|
return new TokenResult.BindingMismatch("Token has no binding context.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.Equals(claims.BindingContext, options.BindingContext, StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
return new TokenResult.BindingMismatch("Binding context mismatch.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new TokenResult.Success(token, claims);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public TokenClaims? Inspect(string token)
|
||||||
|
{
|
||||||
|
if (!TokenSerializer.TryDecode(token, out var payload, out _))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return TokenSerializer.Deserialize(payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
using System;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace SecureToken.Validation
|
||||||
|
{
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Options used when validating a token. Fine-grained control over each check.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class TokenValidationOptions
|
||||||
|
{
|
||||||
|
/// <summary>Expected issuer. Null skips issuer validation.</summary>
|
||||||
|
public string? ValidIssuer { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Expected audience. Null skips audience validation.</summary>
|
||||||
|
public string? ValidAudience { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Expected token type. Null skips type validation.</summary>
|
||||||
|
public string? RequiredTokenType { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Binding context - must match the value used when the token was issued.
|
||||||
|
/// Null skips binding validation (not recommended for high-security tokens).
|
||||||
|
/// </summary>
|
||||||
|
public string? BindingContext { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Clock skew tolerance. Defaults to 30 seconds.</summary>
|
||||||
|
public TimeSpan ClockSkew { get; set; } = TimeSpan.FromSeconds(30);
|
||||||
|
|
||||||
|
/// <summary>Whether to validate the not-before claim. Default: true.</summary>
|
||||||
|
public bool ValidateNotBefore { get; set; } = true;
|
||||||
|
|
||||||
|
/// <summary>Whether to validate expiry. Default: true.</summary>
|
||||||
|
public bool ValidateExpiry { get; set; } = true;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Pluggable revocation check. Return true if the token is revoked.
|
||||||
|
/// Hook this into your cache or database for real-time revocation.
|
||||||
|
/// </summary>
|
||||||
|
public Func<string, CancellationToken, Task<bool>>? RevocationCheck { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Convenience: validates as an access token for a given audience.</summary>
|
||||||
|
public static TokenValidationOptions AccessToken(string issuer, string audience, string? bindingContext = null) => new TokenValidationOptions()
|
||||||
|
{
|
||||||
|
ValidIssuer = issuer,
|
||||||
|
ValidAudience = audience,
|
||||||
|
RequiredTokenType = Core.TokenTypeConstants.Access,
|
||||||
|
BindingContext = bindingContext,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>Convenience: validates as a refresh token.</summary>
|
||||||
|
public static TokenValidationOptions RefreshToken(string issuer) => new TokenValidationOptions()
|
||||||
|
{
|
||||||
|
ValidIssuer = issuer,
|
||||||
|
RequiredTokenType = Core.TokenTypeConstants.Refresh,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
using SecureToken.Core;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace SecureToken.Tokens
|
||||||
|
{
|
||||||
|
// This file is part of the EonaCat project(s) which is released under the Apache License.
|
||||||
|
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Serializes and deserializes token payloads to a compact binary format.
|
||||||
|
///
|
||||||
|
/// Format: stv1.{base64url(payload)}.{base64url(signature)}
|
||||||
|
///
|
||||||
|
/// The "stv1" prefix is a version tag - unlike JWT, the algorithm is never
|
||||||
|
/// embedded in the token header, so algorithm-confusion attacks are impossible.
|
||||||
|
///
|
||||||
|
/// The payload is a structured binary encoding (not JSON), so there is no
|
||||||
|
/// parsing ambiguity, no prototype-pollution risk, and no need for a JSON library.
|
||||||
|
/// </summary>
|
||||||
|
internal static class TokenSerializer
|
||||||
|
{
|
||||||
|
private const string Prefix = "stv1";
|
||||||
|
|
||||||
|
// Field tags for the binary encoding
|
||||||
|
private const byte TagSubject = 0x01;
|
||||||
|
private const byte TagIssuer = 0x02;
|
||||||
|
private const byte TagAudience = 0x03;
|
||||||
|
private const byte TagRole = 0x04;
|
||||||
|
private const byte TagCustom = 0x05;
|
||||||
|
private const byte TagIssuedAt = 0x10;
|
||||||
|
private const byte TagNotBefore = 0x11;
|
||||||
|
private const byte TagExpiresAt = 0x12;
|
||||||
|
private const byte TagTokenId = 0x20;
|
||||||
|
private const byte TagTokenType = 0x21;
|
||||||
|
private const byte TagKeyGeneration = 0x22;
|
||||||
|
private const byte TagBindingContext = 0x30;
|
||||||
|
|
||||||
|
public static byte[] Serialize(TokenClaims claims)
|
||||||
|
{
|
||||||
|
using var ms = new System.IO.MemoryStream();
|
||||||
|
using var bw = new System.IO.BinaryWriter(ms, Encoding.UTF8, leaveOpen: true);
|
||||||
|
|
||||||
|
WriteString(bw, TagSubject, claims.Subject);
|
||||||
|
WriteString(bw, TagIssuer, claims.Issuer);
|
||||||
|
|
||||||
|
foreach (var aud in claims.Audiences)
|
||||||
|
{
|
||||||
|
WriteString(bw, TagAudience, aud);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var role in claims.Roles)
|
||||||
|
{
|
||||||
|
WriteString(bw, TagRole, role);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var kv in claims.Custom)
|
||||||
|
{
|
||||||
|
bw.Write(TagCustom);
|
||||||
|
WriteRawString(bw, kv.Key);
|
||||||
|
WriteRawString(bw, kv.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
WriteInt64(bw, TagIssuedAt, claims.IssuedAt.ToUnixTimeSeconds());
|
||||||
|
WriteInt64(bw, TagNotBefore, claims.NotBefore.ToUnixTimeSeconds());
|
||||||
|
WriteInt64(bw, TagExpiresAt, claims.ExpiresAt.ToUnixTimeSeconds());
|
||||||
|
|
||||||
|
WriteString(bw, TagTokenId, claims.TokenId);
|
||||||
|
WriteString(bw, TagTokenType, claims.TokenType);
|
||||||
|
|
||||||
|
bw.Write(TagKeyGeneration);
|
||||||
|
bw.Write(claims.KeyGeneration);
|
||||||
|
|
||||||
|
if (claims.BindingContext != null)
|
||||||
|
{
|
||||||
|
WriteString(bw, TagBindingContext, claims.BindingContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
bw.Flush();
|
||||||
|
return ms.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static TokenClaims? Deserialize(byte[] data)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var ms = new System.IO.MemoryStream(data);
|
||||||
|
using var br = new System.IO.BinaryReader(ms, Encoding.UTF8);
|
||||||
|
|
||||||
|
string subject = "", issuer = "", tokenId = "", tokenType = TokenTypeConstants.Access;
|
||||||
|
string? bindingContext = null;
|
||||||
|
int keyGeneration = 0;
|
||||||
|
long issuedAt = 0, notBefore = 0, expiresAt = 0;
|
||||||
|
var audiences = new List<string>();
|
||||||
|
var roles = new List<string>();
|
||||||
|
var custom = new Dictionary<string, string>();
|
||||||
|
|
||||||
|
while (ms.Position < ms.Length)
|
||||||
|
{
|
||||||
|
var tag = br.ReadByte();
|
||||||
|
switch (tag)
|
||||||
|
{
|
||||||
|
case TagSubject: subject = ReadRawString(br); break;
|
||||||
|
case TagIssuer: issuer = ReadRawString(br); break;
|
||||||
|
case TagAudience: audiences.Add(ReadRawString(br)); break;
|
||||||
|
case TagRole: roles.Add(ReadRawString(br)); break;
|
||||||
|
case TagCustom:
|
||||||
|
var k = ReadRawString(br);
|
||||||
|
var v = ReadRawString(br);
|
||||||
|
custom[k] = v;
|
||||||
|
break;
|
||||||
|
case TagIssuedAt: issuedAt = br.ReadInt64(); break;
|
||||||
|
case TagNotBefore: notBefore = br.ReadInt64(); break;
|
||||||
|
case TagExpiresAt: expiresAt = br.ReadInt64(); break;
|
||||||
|
case TagTokenId: tokenId = ReadRawString(br); break;
|
||||||
|
case TagTokenType: tokenType = ReadRawString(br); break;
|
||||||
|
case TagKeyGeneration: keyGeneration = br.ReadInt32(); break;
|
||||||
|
case TagBindingContext: bindingContext = ReadRawString(br); break;
|
||||||
|
default: return null; // Unknown tag - reject malformed tokens
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new TokenClaims
|
||||||
|
{
|
||||||
|
Subject = subject,
|
||||||
|
Issuer = issuer,
|
||||||
|
Audiences = audiences.AsReadOnly(),
|
||||||
|
Roles = roles.AsReadOnly(),
|
||||||
|
Custom = custom,
|
||||||
|
IssuedAt = DateTimeOffset.FromUnixTimeSeconds(issuedAt),
|
||||||
|
NotBefore = DateTimeOffset.FromUnixTimeSeconds(notBefore),
|
||||||
|
ExpiresAt = DateTimeOffset.FromUnixTimeSeconds(expiresAt),
|
||||||
|
TokenId = tokenId,
|
||||||
|
TokenType = tokenType,
|
||||||
|
KeyGeneration = keyGeneration,
|
||||||
|
BindingContext = bindingContext,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string Encode(byte[] payload, byte[] signature)
|
||||||
|
{
|
||||||
|
var p = Base64UrlEncode(payload);
|
||||||
|
var s = Base64UrlEncode(signature);
|
||||||
|
return $"{Prefix}.{p}.{s}";
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool TryDecode(string token, out byte[] payload, out byte[] signature)
|
||||||
|
{
|
||||||
|
payload = new byte[0];
|
||||||
|
signature = new byte[0];
|
||||||
|
|
||||||
|
var parts = token.Split('.');
|
||||||
|
if (parts.Length != 3 || parts[0] != Prefix)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
payload = Base64UrlDecode(parts[1]);
|
||||||
|
signature = Base64UrlDecode(parts[2]);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void WriteString(System.IO.BinaryWriter bw, byte tag, string value)
|
||||||
|
{
|
||||||
|
bw.Write(tag);
|
||||||
|
WriteRawString(bw, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void WriteRawString(System.IO.BinaryWriter bw, string value)
|
||||||
|
{
|
||||||
|
var bytes = Encoding.UTF8.GetBytes(value);
|
||||||
|
bw.Write((ushort)bytes.Length);
|
||||||
|
bw.Write(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ReadRawString(System.IO.BinaryReader br)
|
||||||
|
{
|
||||||
|
var len = br.ReadUInt16();
|
||||||
|
var bytes = br.ReadBytes(len);
|
||||||
|
return Encoding.UTF8.GetString(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void WriteInt64(System.IO.BinaryWriter bw, byte tag, long value)
|
||||||
|
{
|
||||||
|
bw.Write(tag);
|
||||||
|
bw.Write(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Base64UrlEncode(byte[] data) =>
|
||||||
|
Convert.ToBase64String(data)
|
||||||
|
.TrimEnd('=')
|
||||||
|
.Replace('+', '-')
|
||||||
|
.Replace('/', '_');
|
||||||
|
|
||||||
|
private static byte[] Base64UrlDecode(string s)
|
||||||
|
{
|
||||||
|
var padded = s.Replace('-', '+').Replace('_', '/');
|
||||||
|
padded = (padded.Length % 4) switch
|
||||||
|
{
|
||||||
|
2 => padded + "==",
|
||||||
|
3 => padded + "=",
|
||||||
|
_ => padded
|
||||||
|
};
|
||||||
|
return Convert.FromBase64String(padded);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 248 KiB |
@@ -1,73 +1,204 @@
|
|||||||
Apache License
|
|
||||||
Version 2.0, January 2004
|
Apache License
|
||||||
http://www.apache.org/licenses/
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
https://EonaCat.com/license/
|
||||||
|
|
||||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
OF SOFTWARE BY EONACAT (JEROEN SAEY)
|
||||||
|
|
||||||
1. Definitions.
|
1. Definitions.
|
||||||
|
|
||||||
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
APPENDIX: How to apply the Apache License to your work.
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
Copyright 2026 EonaCat
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
you may not use this file except in compliance with the License.
|
you may not use this file except in compliance with the License.
|
||||||
You may obtain a copy of the License at
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
Unless required by applicable law or agreed to in writing, software
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
See the License for the specific language governing permissions and
|
See the License for the specific language governing permissions and
|
||||||
limitations under the License.
|
limitations under the License.
|
||||||
|
|||||||
@@ -1,3 +1,343 @@
|
|||||||
# EonaCat.SecureToken
|
# EonaCat.SecureToken
|
||||||
|
|
||||||
EonaCat.SecureToken
|
**A cryptographically superior alternative to JWT for .NET 8+**
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
dotnet add package SecureToken
|
||||||
|
```
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
### 1. Register with DI (ASP.NET Core)
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
// Program.cs
|
||||||
|
using SecureToken.Extensions;
|
||||||
|
|
||||||
|
builder.Services.AddSecureTokens(sp =>
|
||||||
|
{
|
||||||
|
// Load your key material from environment / secrets manager
|
||||||
|
var keyBytes = Convert.FromBase64String(Environment.GetEnvironmentVariable("TOKEN_KEY")!);
|
||||||
|
return SigningKeyStore.FromKeys([(1, keyBytes)]);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
For development / testing, a random ephemeral key is fine:
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
builder.Services.AddSecureTokens(); // random key, resets on restart
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### 2. Issue a Token
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
public class AuthController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly ITokenService _tokens;
|
||||||
|
|
||||||
|
public AuthController(ITokenService tokens) => _tokens = tokens;
|
||||||
|
|
||||||
|
[HttpPost("login")]
|
||||||
|
public IActionResult Login([FromBody] LoginRequest req)
|
||||||
|
{
|
||||||
|
// ... verify credentials ...
|
||||||
|
|
||||||
|
var token = _tokens.Issue(
|
||||||
|
TokenDescriptor.Create()
|
||||||
|
.ForSubject(user.Id)
|
||||||
|
.IssuedBy("my-api")
|
||||||
|
.ForAudience("my-api")
|
||||||
|
.WithRole("user")
|
||||||
|
.WithClaim("email", user.Email)
|
||||||
|
.ExpiresIn(minutes: 15)
|
||||||
|
);
|
||||||
|
|
||||||
|
return Ok(new { token });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### 3. Validate a Token
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
var result = await _tokens.ValidateAsync(
|
||||||
|
rawToken,
|
||||||
|
TokenValidationOptions.AccessToken(issuer: "my-api", audience: "my-api")
|
||||||
|
);
|
||||||
|
|
||||||
|
// Pattern-match the result - no exceptions thrown
|
||||||
|
switch (result)
|
||||||
|
{
|
||||||
|
case TokenResult.Success s:
|
||||||
|
var userId = s.Claims.Subject;
|
||||||
|
var roles = s.Claims.Roles;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case TokenResult.Expired e:
|
||||||
|
return Unauthorized($"Token expired at {e.ExpiredAt}");
|
||||||
|
|
||||||
|
case TokenResult.InvalidSignature:
|
||||||
|
return Unauthorized("Token signature is invalid.");
|
||||||
|
|
||||||
|
case TokenResult.WrongTokenType w:
|
||||||
|
return Unauthorized($"Expected {w.Expected}, got {w.Actual}");
|
||||||
|
|
||||||
|
case TokenResult.Revoked r:
|
||||||
|
return Unauthorized($"Token {r.TokenId} has been revoked.");
|
||||||
|
|
||||||
|
default:
|
||||||
|
return Unauthorized("Token validation failed.");
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Or use the match helper:
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
return result.Match(
|
||||||
|
onSuccess: s => Ok(new { s.Claims.Subject }),
|
||||||
|
onFailure: err => Unauthorized(err.ToString())
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Token Pairs (Access + Refresh)
|
||||||
|
|
||||||
|
Issue a short-lived access token and a long-lived refresh token in one call:
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
var pair = _tokens.IssueTokenPair(
|
||||||
|
subject: user.Id,
|
||||||
|
issuer: "my-api",
|
||||||
|
audience: "my-api",
|
||||||
|
roles: ["admin"],
|
||||||
|
claims: [new("plan", "pro")],
|
||||||
|
accessTokenLifetime: TimeSpan.FromMinutes(15),
|
||||||
|
refreshTokenLifetime: TimeSpan.FromDays(30)
|
||||||
|
);
|
||||||
|
|
||||||
|
return Ok(new
|
||||||
|
{
|
||||||
|
accessToken: pair.AccessToken,
|
||||||
|
refreshToken: pair.RefreshToken,
|
||||||
|
expiresAt: pair.AccessTokenExpiry,
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Refresh tokens are **type-tagged** - they cannot be used where an access token is expected, and vice versa.
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
// Refreshing
|
||||||
|
var refreshResult = await _tokens.ValidateAsync(
|
||||||
|
refreshToken,
|
||||||
|
TokenValidationOptions.RefreshToken("my-api")
|
||||||
|
);
|
||||||
|
|
||||||
|
if (refreshResult is TokenResult.Success s)
|
||||||
|
{
|
||||||
|
var newPair = _tokens.IssueTokenPair(s.Claims.Subject, "my-api", "my-api");
|
||||||
|
return Ok(newPair);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Context Binding
|
||||||
|
|
||||||
|
Bind a token to a client context (IP address, device fingerprint, TLS channel hash, etc.).
|
||||||
|
A stolen token from another context will fail validation.
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
// Issue - bind to the client's IP
|
||||||
|
var token = _tokens.Issue(
|
||||||
|
TokenDescriptor.Create()
|
||||||
|
.ForSubject(user.Id)
|
||||||
|
.IssuedBy("my-api")
|
||||||
|
.ForAudience("my-api")
|
||||||
|
.BoundTo(clientIpAddress) // <-- context binding
|
||||||
|
);
|
||||||
|
|
||||||
|
// Validate - must supply the same context
|
||||||
|
var result = await _tokens.ValidateAsync(token, new TokenValidationOptions
|
||||||
|
{
|
||||||
|
ValidIssuer = "my-api",
|
||||||
|
ValidAudience = "my-api",
|
||||||
|
RequiredTokenType = TokenTypeConstants.Access,
|
||||||
|
BindingContext = Request.HttpContext.Connection.RemoteIpAddress?.ToString(),
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
If the IP doesn't match, validation returns `TokenResult.BindingMismatch`.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Key Rotation
|
||||||
|
|
||||||
|
Keys are versioned. Old tokens remain valid after rotation until they expire naturally.
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
// Inject SigningKeyStore and rotate
|
||||||
|
var newGeneration = _keyStore.Rotate();
|
||||||
|
|
||||||
|
// Or supply new key material from your KMS
|
||||||
|
var newGeneration = _keyStore.Rotate(myKmsBytes);
|
||||||
|
|
||||||
|
// Prune old generation once all tokens from it have expired
|
||||||
|
_keyStore.PruneGeneration(oldGeneration);
|
||||||
|
```
|
||||||
|
|
||||||
|
Each token embeds the key generation it was signed with. The verifier automatically picks the right key.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Revocation
|
||||||
|
|
||||||
|
Plug in any store - Redis, database, or in-memory:
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
// Example: Redis-backed revocation
|
||||||
|
var options = new TokenValidationOptions
|
||||||
|
{
|
||||||
|
ValidIssuer = "my-api",
|
||||||
|
ValidAudience = "my-api",
|
||||||
|
RequiredTokenType = TokenTypeConstants.Access,
|
||||||
|
RevocationCheck = async (tokenId, ct) =>
|
||||||
|
{
|
||||||
|
return await _redis.KeyExistsAsync($"revoked:{tokenId}");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// To revoke a token:
|
||||||
|
var claims = _tokens.Inspect(tokenString);
|
||||||
|
await _redis.StringSetAsync($"revoked:{claims!.TokenId}", "1", claims.ExpiresAt - DateTimeOffset.UtcNow);
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Custom Token Types
|
||||||
|
|
||||||
|
Prevent tokens from being used across different purposes:
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
// Issue an invitation token
|
||||||
|
var inviteToken = _tokens.Issue(
|
||||||
|
TokenDescriptor.Create()
|
||||||
|
.ForSubject(inviteeEmail)
|
||||||
|
.IssuedBy("my-api")
|
||||||
|
.OfType(TokenTypeConstants.Invitation) // or your own string, e.g. "workspace-invite+v1"
|
||||||
|
.WithClaim("workspaceId", workspaceId)
|
||||||
|
.ExpiresIn(minutes: 60 * 48) // 48 hours
|
||||||
|
);
|
||||||
|
|
||||||
|
// Validate - only accepts invitation tokens
|
||||||
|
var result = svc.Validate(token, new TokenValidationOptions
|
||||||
|
{
|
||||||
|
ValidIssuer = "my-api",
|
||||||
|
RequiredTokenType = TokenTypeConstants.Invitation,
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Built-in type constants in `TokenTypeConstants`:
|
||||||
|
|
||||||
|
| Constant | Value |
|
||||||
|
|||
|
||||||
|
| `Access` | `at+secure` |
|
||||||
|
| `Refresh` | `rt+secure` |
|
||||||
|
| `ServiceAccount` | `sa+secure` |
|
||||||
|
| `Invitation` | `inv+secure` |
|
||||||
|
| `PasswordReset` | `pwr+secure` |
|
||||||
|
| `EmailVerification` | `ev+secure` |
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Service Account Tokens
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
var saToken = _tokens.Issue(
|
||||||
|
TokenDescriptor.Create()
|
||||||
|
.ForSubject("svc-worker-1")
|
||||||
|
.IssuedBy("my-api")
|
||||||
|
.ForAudience("internal-queue")
|
||||||
|
.AsServiceAccount()
|
||||||
|
.WithRole("queue-publisher")
|
||||||
|
.WithLifetime(TimeSpan.FromDays(365))
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Full Validation Options Reference
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
var options = new TokenValidationOptions
|
||||||
|
{
|
||||||
|
// Issuer the token must have been issued by
|
||||||
|
ValidIssuer = "my-api",
|
||||||
|
|
||||||
|
// Audience the token must include
|
||||||
|
ValidAudience = "my-api",
|
||||||
|
|
||||||
|
// Token type that must match exactly
|
||||||
|
RequiredTokenType = TokenTypeConstants.Access,
|
||||||
|
|
||||||
|
// Context binding (IP, device hash, etc.)
|
||||||
|
BindingContext = clientIp,
|
||||||
|
|
||||||
|
// Clock skew tolerance (default: 30 seconds)
|
||||||
|
ClockSkew = TimeSpan.FromSeconds(30),
|
||||||
|
|
||||||
|
// Toggle individual checks
|
||||||
|
ValidateExpiry = true,
|
||||||
|
ValidateNotBefore = true,
|
||||||
|
|
||||||
|
// Async revocation check - skip for sync validation
|
||||||
|
RevocationCheck = async (tokenId, ct) =>
|
||||||
|
await _revokedIds.ContainsAsync(tokenId, ct),
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Inspecting Tokens (Debug Only)
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
// No signature check - for diagnostics, never for authorization
|
||||||
|
var claims = _tokens.Inspect(rawToken);
|
||||||
|
|
||||||
|
Console.WriteLine($"Subject: {claims?.Subject}");
|
||||||
|
Console.WriteLine($"Issued: {claims?.IssuedAt}");
|
||||||
|
Console.WriteLine($"Expires: {claims?.ExpiresAt}");
|
||||||
|
Console.WriteLine($"KeyGen: {claims?.KeyGeneration}");
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Token Format
|
||||||
|
|
||||||
|
```
|
||||||
|
stv1.{base64url(payload)}.{base64url(signature)}
|
||||||
|
```
|
||||||
|
|
||||||
|
- `stv1` - version prefix, never changes algorithm.
|
||||||
|
- `payload` - compact binary-encoded claims (not JSON).
|
||||||
|
- `signature` - HMAC-SHA256 over the payload using an HKDF-derived sub-key.
|
||||||
|
|
||||||
|
The sub-key is derived from the master key using HKDF with the **token type as context**, so a signing key used for access tokens cannot verify refresh tokens even if an attacker switches the type tag.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Security Properties
|
||||||
|
|
||||||
|
- **No algorithm field in token** - the verifier always decides the algorithm.
|
||||||
|
- **Binary payload** - no JSON parser, no prototype pollution, no ambiguous number types.
|
||||||
|
- **Type-segregated sub-keys** - HKDF derives a separate key per token type.
|
||||||
|
- **Constant-time comparison** - signature verification uses `CryptographicOperations.FixedTimeEquals`.
|
||||||
|
- **Typed results, no exceptions** - validation never throws; every failure is a named case.
|
||||||
|
- **Context binding** - tokens can be tied to an IP, device, or TLS channel binding.
|
||||||
|
- **Versioned key rotation** - rotate keys without invalidating unexpired tokens.
|
||||||
Reference in New Issue
Block a user