Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@

<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="9.0.0" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.15.3" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.15.3" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.12.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.12.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.12.0" />
</ItemGroup>

</Project>
24 changes: 24 additions & 0 deletions Authorization.API.Tests/Authorization.API.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Authorization.API\Authorization.API.csproj" />
</ItemGroup>

</Project>
39 changes: 39 additions & 0 deletions Authorization.API.Tests/EncryptionServiceTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using Authorization.API.Services;

namespace Authorization.API.Tests;

public class EncryptionServiceTests
{
private const string DevKey = "TG9jYWxEZXYtQUVTMjU2LUVuY3J5cHRpb24tS2V5cyE=";

[Fact]
public void EncryptDecrypt_RoundTrips()
{
var service = new EncryptionService(DevKey);
const string original = "authorization-code";

var encrypted = service.Encrypt(original);
var decrypted = service.Decrypt(encrypted);

Assert.NotEqual(original, encrypted);
Assert.Equal(original, decrypted);
}

[Fact]
public void Encrypt_UsesUniqueCipherText()
{
var service = new EncryptionService(DevKey);

var first = service.Encrypt("same-value");
var second = service.Encrypt("same-value");

Assert.NotEqual(first, second);
}

[Fact]
public void Constructor_RejectsInvalidKeyLength()
{
var shortKey = Convert.ToBase64String("tooshort"u8.ToArray());
Assert.Throws<ArgumentException>(() => new EncryptionService(shortKey));
}
}
1 change: 1 addition & 0 deletions Authorization.API.Tests/GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
global using Xunit;
31 changes: 31 additions & 0 deletions Authorization.API.Tests/PkceHelperTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using Authorization.API.Helpers;

namespace Authorization.API.Tests;

public class PkceHelperTests
{
[Fact]
public void ComputeCodeChallenge_UsesS256()
{
const string verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
var challenge = PkceHelper.ComputeCodeChallenge(verifier, PkceHelper.S256);

Assert.Equal("E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", challenge);
Assert.True(PkceHelper.Validate(verifier, challenge, PkceHelper.S256));
}

[Fact]
public void ComputeCodeChallenge_RejectsPlainMethod()
{
Assert.Throws<ArgumentException>(() => PkceHelper.ComputeCodeChallenge("verifier", "plain"));
Assert.False(PkceHelper.Validate("verifier", "verifier", "plain"));
}

[Fact]
public void Validate_AllowsMissingChallengeWhenVerifierMissing()
{
Assert.True(PkceHelper.Validate(null, null, null));
Assert.False(PkceHelper.Validate("verifier", null, PkceHelper.S256));
Assert.False(PkceHelper.Validate(null, "challenge", PkceHelper.S256));
}
}
39 changes: 39 additions & 0 deletions Authorization.API.Tests/TokenHelperTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using Authorization.API.Helpers;

namespace Authorization.API.Tests;

public class TokenHelperTests
{
[Fact]
public void HashToken_IsDeterministicAndNotReversible()
{
var token = "refresh-token-value";

var first = TokenHelper.HashToken(token);
var second = TokenHelper.HashToken(token);

Assert.Equal(first, second);
Assert.NotEqual(token, first);
Assert.Equal(64, first.Length);
}

[Fact]
public void GenerateSecureCode_IsUrlSafe()
{
var code = TokenHelper.GenerateSecureCode();

Assert.False(string.IsNullOrWhiteSpace(code));
Assert.DoesNotContain("+", code);
Assert.DoesNotContain("/", code);
Assert.DoesNotContain("=", code);
}

[Fact]
public void SecretsEqual_ComparesExactValues()
{
Assert.True(TokenHelper.SecretsEqual("secret", "secret"));
Assert.False(TokenHelper.SecretsEqual("secret", "Secret"));
Assert.False(TokenHelper.SecretsEqual("secret", "other"));
Assert.False(TokenHelper.SecretsEqual(null, "secret"));
}
}
44 changes: 43 additions & 1 deletion Authorization.API.sln
Original file line number Diff line number Diff line change
@@ -1,32 +1,74 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.12.35506.116 d17.12
VisualStudioVersion = 17.12.35506.116
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Authorization.API", "Authorization.API\Authorization.API.csproj", "{B1FF94A3-76F2-456A-8718-DA49C5F99668}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Authorization.API.AppHost", "Authorization.API.AppHost\Authorization.API.AppHost.csproj", "{7837B4C0-FC78-4116-8727-A0BF147F459A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Authorization.API.ServiceDefaults", "Authorization.API.ServiceDefaults\Authorization.API.ServiceDefaults.csproj", "{C104DBFB-51D8-40D9-995B-2DE4A342E10A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Authorization.API.Tests", "Authorization.API.Tests\Authorization.API.Tests.csproj", "{C5B82DC1-C9A9-4805-A89C-491567728285}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{B1FF94A3-76F2-456A-8718-DA49C5F99668}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B1FF94A3-76F2-456A-8718-DA49C5F99668}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B1FF94A3-76F2-456A-8718-DA49C5F99668}.Debug|x64.ActiveCfg = Debug|Any CPU
{B1FF94A3-76F2-456A-8718-DA49C5F99668}.Debug|x64.Build.0 = Debug|Any CPU
{B1FF94A3-76F2-456A-8718-DA49C5F99668}.Debug|x86.ActiveCfg = Debug|Any CPU
{B1FF94A3-76F2-456A-8718-DA49C5F99668}.Debug|x86.Build.0 = Debug|Any CPU
{B1FF94A3-76F2-456A-8718-DA49C5F99668}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B1FF94A3-76F2-456A-8718-DA49C5F99668}.Release|Any CPU.Build.0 = Release|Any CPU
{B1FF94A3-76F2-456A-8718-DA49C5F99668}.Release|x64.ActiveCfg = Release|Any CPU
{B1FF94A3-76F2-456A-8718-DA49C5F99668}.Release|x64.Build.0 = Release|Any CPU
{B1FF94A3-76F2-456A-8718-DA49C5F99668}.Release|x86.ActiveCfg = Release|Any CPU
{B1FF94A3-76F2-456A-8718-DA49C5F99668}.Release|x86.Build.0 = Release|Any CPU
{7837B4C0-FC78-4116-8727-A0BF147F459A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7837B4C0-FC78-4116-8727-A0BF147F459A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7837B4C0-FC78-4116-8727-A0BF147F459A}.Debug|x64.ActiveCfg = Debug|Any CPU
{7837B4C0-FC78-4116-8727-A0BF147F459A}.Debug|x64.Build.0 = Debug|Any CPU
{7837B4C0-FC78-4116-8727-A0BF147F459A}.Debug|x86.ActiveCfg = Debug|Any CPU
{7837B4C0-FC78-4116-8727-A0BF147F459A}.Debug|x86.Build.0 = Debug|Any CPU
{7837B4C0-FC78-4116-8727-A0BF147F459A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7837B4C0-FC78-4116-8727-A0BF147F459A}.Release|Any CPU.Build.0 = Release|Any CPU
{7837B4C0-FC78-4116-8727-A0BF147F459A}.Release|x64.ActiveCfg = Release|Any CPU
{7837B4C0-FC78-4116-8727-A0BF147F459A}.Release|x64.Build.0 = Release|Any CPU
{7837B4C0-FC78-4116-8727-A0BF147F459A}.Release|x86.ActiveCfg = Release|Any CPU
{7837B4C0-FC78-4116-8727-A0BF147F459A}.Release|x86.Build.0 = Release|Any CPU
{C104DBFB-51D8-40D9-995B-2DE4A342E10A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C104DBFB-51D8-40D9-995B-2DE4A342E10A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C104DBFB-51D8-40D9-995B-2DE4A342E10A}.Debug|x64.ActiveCfg = Debug|Any CPU
{C104DBFB-51D8-40D9-995B-2DE4A342E10A}.Debug|x64.Build.0 = Debug|Any CPU
{C104DBFB-51D8-40D9-995B-2DE4A342E10A}.Debug|x86.ActiveCfg = Debug|Any CPU
{C104DBFB-51D8-40D9-995B-2DE4A342E10A}.Debug|x86.Build.0 = Debug|Any CPU
{C104DBFB-51D8-40D9-995B-2DE4A342E10A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C104DBFB-51D8-40D9-995B-2DE4A342E10A}.Release|Any CPU.Build.0 = Release|Any CPU
{C104DBFB-51D8-40D9-995B-2DE4A342E10A}.Release|x64.ActiveCfg = Release|Any CPU
{C104DBFB-51D8-40D9-995B-2DE4A342E10A}.Release|x64.Build.0 = Release|Any CPU
{C104DBFB-51D8-40D9-995B-2DE4A342E10A}.Release|x86.ActiveCfg = Release|Any CPU
{C104DBFB-51D8-40D9-995B-2DE4A342E10A}.Release|x86.Build.0 = Release|Any CPU
{C5B82DC1-C9A9-4805-A89C-491567728285}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C5B82DC1-C9A9-4805-A89C-491567728285}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C5B82DC1-C9A9-4805-A89C-491567728285}.Debug|x64.ActiveCfg = Debug|Any CPU
{C5B82DC1-C9A9-4805-A89C-491567728285}.Debug|x64.Build.0 = Debug|Any CPU
{C5B82DC1-C9A9-4805-A89C-491567728285}.Debug|x86.ActiveCfg = Debug|Any CPU
{C5B82DC1-C9A9-4805-A89C-491567728285}.Debug|x86.Build.0 = Debug|Any CPU
{C5B82DC1-C9A9-4805-A89C-491567728285}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C5B82DC1-C9A9-4805-A89C-491567728285}.Release|Any CPU.Build.0 = Release|Any CPU
{C5B82DC1-C9A9-4805-A89C-491567728285}.Release|x64.ActiveCfg = Release|Any CPU
{C5B82DC1-C9A9-4805-A89C-491567728285}.Release|x64.Build.0 = Release|Any CPU
{C5B82DC1-C9A9-4805-A89C-491567728285}.Release|x86.ActiveCfg = Release|Any CPU
{C5B82DC1-C9A9-4805-A89C-491567728285}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
2 changes: 1 addition & 1 deletion Authorization.API/Authorization.API.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="9.0.1" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.1" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
<PackageReference Include="Scalar.AspNetCore" Version="2.0.1" />
Expand Down
36 changes: 33 additions & 3 deletions Authorization.API/Authorization.API.http
Original file line number Diff line number Diff line change
@@ -1,6 +1,36 @@
@Authorization.API_HostAddress = http://localhost:5215

GET {{Authorization.API_HostAddress}}/weatherforecast/
Accept: application/json
### Register a user
POST {{Authorization.API_HostAddress}}/account/register
Content-Type: application/json

###
{
"username": "demo",
"email": "demo@example.com",
"password": "Password1!"
}

### Password login (returns access and refresh tokens)
POST {{Authorization.API_HostAddress}}/account/login/token
Content-Type: application/json

{
"email": "demo@example.com",
"password": "Password1!"
}

### Current user
GET {{Authorization.API_HostAddress}}/account/me
Authorization: Bearer {{access_token}}

### Client credentials
POST {{Authorization.API_HostAddress}}/token
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials&client_id=demo-client&client_secret=demo-secret&scope=api

### Authorization-code token exchange
POST {{Authorization.API_HostAddress}}/token
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code&client_id=demo-client&client_secret=demo-secret&code={{code}}&redirect_uri=https://localhost/callback&code_verifier={{code_verifier}}
26 changes: 12 additions & 14 deletions Authorization.API/Context/ApplicationDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,66 +4,64 @@
using Microsoft.EntityFrameworkCore;

namespace Authorization.API.Context;

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}

// OAuth Clients
public DbSet<Client> Clients { get; set; }

// OAuth Authorization Codes
public DbSet<AuthorizationCode> AuthorizationCodes { get; set; }

// OAuth Refresh Tokens
public DbSet<RefreshToken> RefreshTokens { get; set; }

// API Scopes
public DbSet<ApiScope> ApiScopes { get; set; }

// API Resources
public DbSet<ApiResource> ApiResources { get; set; }

protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);

// Configure Identity Tables
builder.Entity<ApplicationUser>()
.ToTable("Users");

builder.Entity<ApplicationRole>()
.ToTable("Roles");

// Configure OAuth Clients
builder.Entity<Client>()
.HasIndex(c => c.ClientId)
.IsUnique();

// Configure Authorization Codes
builder.Entity<AuthorizationCode>()
.HasIndex(ac => ac.Code)
.IsUnique(); // Ensures each code is unique
.IsUnique();

builder.Entity<AuthorizationCode>()
.HasIndex(ac => new { ac.ClientId, ac.UserId });

// Configure Refresh Tokens
builder.Entity<RefreshToken>()
.HasIndex(r => r.Token)
.IsUnique();

builder.Entity<RefreshToken>()
.HasOne(rt => rt.User)
.WithMany() // Each user can have many refresh tokens
.HasForeignKey(rt => rt.UserId);
.WithMany()
.HasForeignKey(rt => rt.UserId)
.OnDelete(DeleteBehavior.Cascade);

builder.Entity<RefreshToken>()
.HasOne(rt => rt.Client)
.WithMany()
.HasPrincipalKey(c => c.ClientId)
.HasForeignKey(rt => rt.ClientId)
.OnDelete(DeleteBehavior.Cascade);

// Configure API Scopes
builder.Entity<ApiScope>()
.HasIndex(s => s.Name)
.IsUnique();
}
}

Loading