Still working on getting client credential flow complete, most of the request works but still working on generating the JWT.
This commit is contained in:
parent
1a8c63808a
commit
8782ef39c6
80 changed files with 1331 additions and 414 deletions
|
|
@ -1,16 +1,26 @@
|
|||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using IdentityShroud.Core;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using FluentResults;
|
||||
using IdentityShroud.Core.Contracts;
|
||||
using IdentityShroud.Core.EFCore;
|
||||
using IdentityShroud.Core.Model;
|
||||
using IdentityShroud.Core.Tests;
|
||||
using IdentityShroud.Core.Tests.Fixtures;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Shouldly;
|
||||
|
||||
namespace IdentityShroud.Api.Tests.Apis;
|
||||
|
||||
public class ClientApiTests : IClassFixture<ApplicationFactory>
|
||||
{
|
||||
private readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web)
|
||||
{
|
||||
TypeInfoResolver = AppJsonSerializerContext.Default,
|
||||
};
|
||||
private readonly ApplicationFactory _factory;
|
||||
|
||||
public ClientApiTests(ApplicationFactory factory)
|
||||
|
|
@ -32,7 +42,7 @@ public class ClientApiTests : IClassFixture<ApplicationFactory>
|
|||
public async Task Create_Validation(string? clientId, bool succeeds, string fieldName)
|
||||
{
|
||||
// setup
|
||||
Realm realm = await CreateRealmAsync("test-realm", "Test Realm");
|
||||
var realm = await CreateRealmAsync("test-realm", "Test Realm");
|
||||
|
||||
var client = _factory.CreateClient();
|
||||
|
||||
|
|
@ -64,32 +74,56 @@ public class ClientApiTests : IClassFixture<ApplicationFactory>
|
|||
[Fact]
|
||||
public async Task Create_Success_ReturnsCreatedWithLocation()
|
||||
{
|
||||
// setup
|
||||
Realm realm = await CreateRealmAsync("create-realm", "Create Realm");
|
||||
|
||||
var client = _factory.CreateClient();
|
||||
|
||||
// act
|
||||
var response = await client.PostAsync(
|
||||
$"/api/v1/realms/{realm.Id}/clients",
|
||||
JsonContent.Create(new { ClientId = "new-client", Name = "New Client" }),
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
#if DEBUG
|
||||
string contents = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
|
||||
#endif
|
||||
var body = await DoCreateRequest("""
|
||||
{
|
||||
"clientId": "new-client",
|
||||
"name": "New Client"
|
||||
}
|
||||
""");
|
||||
|
||||
// verify
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
|
||||
var body = await response.Content.ReadFromJsonAsync<ClientCreateReponse>(
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.NotNull(body);
|
||||
Assert.Equal("new-client", body.ClientId);
|
||||
Assert.True(body.Id > 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_Success_CreatesSecret()
|
||||
{
|
||||
// act
|
||||
var body = await DoCreateRequest("""
|
||||
{
|
||||
"clientId": "new-client",
|
||||
"name": "New Client",
|
||||
"confidential": true,
|
||||
"generateSecret": true
|
||||
}
|
||||
""");
|
||||
|
||||
// verify
|
||||
body.ShouldNotBeNull();
|
||||
body.Secret.ShouldNotBeNullOrWhiteSpace();
|
||||
}
|
||||
|
||||
private async Task<ClientRepresentation?> DoCreateRequest(
|
||||
string request)
|
||||
{
|
||||
var realm = await CreateRealmAsync("create-realm", "Create Realm");
|
||||
|
||||
var client = _factory.CreateClient();
|
||||
var response = await client.PostAsync(
|
||||
$"/api/v1/realms/{realm.Id}/clients",
|
||||
//JsonContent.Create(request),
|
||||
new StringContent(request, Encoding.UTF8, "application/json"),
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
string contents = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
|
||||
Assert.True(HttpStatusCode.Created == response.StatusCode, contents);
|
||||
|
||||
return JsonSerializer.Deserialize<ClientRepresentation>(contents, _jsonOptions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_UnknownRealm_ReturnsNotFound()
|
||||
{
|
||||
|
|
@ -107,7 +141,7 @@ public class ClientApiTests : IClassFixture<ApplicationFactory>
|
|||
public async Task Get_Success()
|
||||
{
|
||||
// setup
|
||||
Realm realm = await CreateRealmAsync("get-realm", "Get Realm");
|
||||
var realm = await CreateRealmAsync("get-realm", "Get Realm");
|
||||
Client dbClient = await CreateClientAsync(realm, "get-client", "Get Client");
|
||||
|
||||
var httpClient = _factory.CreateClient();
|
||||
|
|
@ -138,7 +172,7 @@ public class ClientApiTests : IClassFixture<ApplicationFactory>
|
|||
public async Task Get_UnknownClient_ReturnsNotFound()
|
||||
{
|
||||
// setup
|
||||
Realm realm = await CreateRealmAsync("notfound-realm", "NotFound Realm");
|
||||
var realm = await CreateRealmAsync("notfound-realm", "NotFound Realm");
|
||||
|
||||
var httpClient = _factory.CreateClient();
|
||||
|
||||
|
|
@ -154,11 +188,11 @@ public class ClientApiTests : IClassFixture<ApplicationFactory>
|
|||
private async Task<Realm> CreateRealmAsync(string slug, string name)
|
||||
{
|
||||
using var scope = _factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<Db>();
|
||||
var realm = new Realm { Slug = slug, Name = name };
|
||||
db.Realms.Add(realm);
|
||||
await db.SaveChangesAsync(TestContext.Current.CancellationToken);
|
||||
return realm;
|
||||
var realmService = scope.ServiceProvider.GetRequiredService<IRealmService>();
|
||||
Result<Realm> result = await realmService.Create(
|
||||
new(null, slug, name),
|
||||
TestContext.Current.CancellationToken);
|
||||
return ResultAssert.Success(result);
|
||||
}
|
||||
|
||||
private async Task<Client> CreateClientAsync(Realm realm, string clientId, string? name = null)
|
||||
|
|
|
|||
123
IdentityShroud.Api.Tests/Apis/OpenIdApiTests.cs
Normal file
123
IdentityShroud.Api.Tests/Apis/OpenIdApiTests.cs
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using IdentityShroud.Api.Apis;
|
||||
using IdentityShroud.Core.EFCore;
|
||||
using IdentityShroud.Core.Tests.Fixtures;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Shouldly;
|
||||
|
||||
namespace IdentityShroud.Api.Tests.Apis;
|
||||
|
||||
public class OpenIdApiTests : IClassFixture<ApplicationFactory>
|
||||
{
|
||||
private readonly ApplicationFactory _factory;
|
||||
|
||||
public OpenIdApiTests(ApplicationFactory factory)
|
||||
{
|
||||
_factory = factory;
|
||||
|
||||
using var scope = _factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<Db>();
|
||||
if (!db.Database.EnsureCreated())
|
||||
{
|
||||
db.Database.ExecuteSqlRaw("TRUNCATE realm CASCADE;");
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public async Task ClientCredentialsFlow(bool useAuthenticationHeader)
|
||||
{
|
||||
var client = _factory.CreateClient();
|
||||
|
||||
var createRealmResponse = await client.PostAsync("/api/v1/realms", JsonContent.Create(new
|
||||
{
|
||||
Slug = "foo",
|
||||
Name = "Test'",
|
||||
}),
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
createRealmResponse.StatusCode.ShouldBe(HttpStatusCode.Created);
|
||||
|
||||
var realm = await createRealmResponse.Content.ReadFromJsonAsync<RealmRepresentation>(
|
||||
cancellationToken: TestContext.Current.CancellationToken);
|
||||
realm.ShouldNotBeNull();
|
||||
realm.Id.ShouldNotBe(Guid.Empty);
|
||||
|
||||
var createClientResponse = await client.PostAsync(
|
||||
$"/api/v1/realms/{realm.Id}/clients",
|
||||
JsonContent.Create(new
|
||||
{
|
||||
ClientId = "myclient",
|
||||
Name = "New Client",
|
||||
Confidential = true,
|
||||
AllowClientCredentialsFlow = true,
|
||||
GenerateSecret = true,
|
||||
}),
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
createClientResponse.StatusCode.ShouldBe(HttpStatusCode.Created);
|
||||
|
||||
// Act
|
||||
const string clientId = "myclient";
|
||||
|
||||
var data = new[]
|
||||
{
|
||||
new KeyValuePair<string, string>("client_id", clientId),
|
||||
new KeyValuePair<string, string>("client_secret", "secret"),
|
||||
new KeyValuePair<string, string>("response_type", "token"),
|
||||
new KeyValuePair<string, string>("grant_type", "client_credentials"),
|
||||
};
|
||||
|
||||
if (useAuthenticationHeader)
|
||||
{
|
||||
// client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("basic",
|
||||
// Convert.ToBase64String($"{clientId}:{clientSecret}"))
|
||||
}
|
||||
|
||||
var content = new FormUrlEncodedContent(data);
|
||||
var response = await client.PostAsync(
|
||||
"/auth/realms/foo/openid-connect/token",
|
||||
content,
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
// Verify
|
||||
// var responseJson = await response.Content.ReadAsStringAsync(
|
||||
// TestContext.Current.CancellationToken);
|
||||
// Console.WriteLine($"Response: {responseJson}");
|
||||
|
||||
response.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
|
||||
// Cache-Control: no-store
|
||||
response.Headers.CacheControl.ShouldNotBeNull()
|
||||
.NoStore.ShouldBe(true);
|
||||
// Pragma: no-cache
|
||||
response.Headers.Pragma.ShouldNotBeNull()
|
||||
.ShouldContain(new NameValueHeaderValue("no-cache"));
|
||||
|
||||
var payload = await response.Content.ReadFromJsonAsync<TokenResponse>();
|
||||
payload.ShouldNotBeNull();
|
||||
Assert.Multiple(
|
||||
() => payload.AccessToken.ShouldNotBeNull(),
|
||||
() => payload.TokenType.ShouldBe("bearer"),
|
||||
() => payload.ExpiresIn.ShouldBe(3600));
|
||||
|
||||
// - refresh_token OPTIONAL
|
||||
// - scope OPTIONAL when identical to request otherwise REQUIRED
|
||||
}
|
||||
|
||||
internal class TokenResponse
|
||||
{
|
||||
[JsonPropertyName("access_token")]
|
||||
public string? AccessToken { get; set; }
|
||||
[JsonPropertyName("token_type")]
|
||||
public string? TokenType { get; set; }
|
||||
[JsonPropertyName("expires_in")]
|
||||
public int? ExpiresIn { get; set; }
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,14 +1,13 @@
|
|||
using System.Buffers.Text;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json.Nodes;
|
||||
using IdentityShroud.Core;
|
||||
using IdentityShroud.Core.Contracts;
|
||||
using IdentityShroud.Core.EFCore;
|
||||
using IdentityShroud.Core.Model;
|
||||
using IdentityShroud.Core.Tests.Fixtures;
|
||||
using IdentityShroud.TestUtils.Asserts;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.WebUtilities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
|
|
@ -124,28 +123,16 @@ public class RealmApisTests : IClassFixture<ApplicationFactory>
|
|||
[Fact]
|
||||
public async Task GetJwks()
|
||||
{
|
||||
// setup
|
||||
IDekEncryptionService dekEncryptionService = _factory.Services.GetRequiredService<IDekEncryptionService>();
|
||||
|
||||
using var rsa = RSA.Create(2048);
|
||||
RSAParameters parameters = rsa.ExportParameters(includePrivateParameters: false);
|
||||
|
||||
RealmKey realmKey = new()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
KeyType = "RSA",
|
||||
Key = dekEncryptionService.Encrypt(rsa.ExportPkcs8PrivateKey()),
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
};
|
||||
|
||||
await ScopedContextAsync(async db =>
|
||||
{
|
||||
db.Realms.Add(new Realm() { Slug = "foo", Name = "Foo", Keys = [ realmKey ]});
|
||||
await db.SaveChangesAsync(TestContext.Current.CancellationToken);
|
||||
});
|
||||
|
||||
// act
|
||||
var client = _factory.CreateClient();
|
||||
var createResponse = await client.PostAsync("/api/v1/realms", JsonContent.Create(new
|
||||
{
|
||||
Slug = "foo",
|
||||
Name = "Test'",
|
||||
}),
|
||||
TestContext.Current.CancellationToken);
|
||||
Assert.Equal(HttpStatusCode.Created, createResponse.StatusCode);
|
||||
|
||||
// act
|
||||
var response = await client.GetAsync("/auth/realms/foo/openid-connect/jwks",
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
|
|
@ -153,9 +140,16 @@ public class RealmApisTests : IClassFixture<ApplicationFactory>
|
|||
JsonObject? payload = await response.Content.ReadFromJsonAsync<JsonObject>(TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.NotNull(payload);
|
||||
JsonObjectAssert.Equal(realmKey.Id.ToString(), payload, "keys[0].kid");
|
||||
JsonObjectAssert.Equal(WebEncoders.Base64UrlEncode(parameters.Modulus!), payload, "keys[0].n");
|
||||
JsonObjectAssert.Equal(WebEncoders.Base64UrlEncode(parameters.Exponent!), payload, "keys[0].e");
|
||||
string? kid = JsonObjectAssert.NavigateToPath(payload, "keys[0].kid")?.AsValue().ToString();
|
||||
Assert.NotNull(kid);
|
||||
Assert.True(kid.Length >= 16);
|
||||
|
||||
//if (JsonObjectAssert.NavigateToPath(payload, "keys[0].kty")?.AsValue().ToString() == "RSA")
|
||||
|
||||
JsonObjectAssert.Equal("RSA", payload, "keys[0].kty");
|
||||
string? n = payload["keys"]?[0]?["n"]?.AsValue().ToString();
|
||||
string? e = payload["keys"]?[0]?["e"]?.AsValue().ToString();
|
||||
AssertRsaParams(n, e);
|
||||
}
|
||||
|
||||
private async Task ScopedContextAsync(
|
||||
|
|
@ -166,4 +160,22 @@ public class RealmApisTests : IClassFixture<ApplicationFactory>
|
|||
var db = scope.ServiceProvider.GetRequiredService<Db>();
|
||||
await action(db);
|
||||
}
|
||||
|
||||
private static void AssertRsaParams(string? n, string? e)
|
||||
{
|
||||
Assert.NotNull(n);
|
||||
Assert.NotNull(e);
|
||||
|
||||
var rsa = RSA.Create();
|
||||
rsa.ImportParameters(new RSAParameters
|
||||
{
|
||||
Modulus = Base64Url.DecodeFromChars(n),
|
||||
Exponent = Base64Url.DecodeFromChars(e)
|
||||
});
|
||||
|
||||
// If n and e are complete nonsense, this will throw
|
||||
var encrypted = rsa.Encrypt(new byte[] { 1, 2, 3 }, RSAEncryptionPadding.OaepSHA256);
|
||||
Assert.NotNull(encrypted);
|
||||
Assert.NotEmpty(encrypted);
|
||||
}
|
||||
}
|
||||
20
IdentityShroud.Api.Tests/HeaderHelpersTests.cs
Normal file
20
IdentityShroud.Api.Tests/HeaderHelpersTests.cs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
using IdentityShroud.Api.Helpers;
|
||||
|
||||
namespace IdentityShroud.Api.Tests;
|
||||
|
||||
public class HeaderHelpersTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("Basic dXNlcjpzZWNyZXQ=", true, "user", "secret")]
|
||||
[InlineData("baSIC dXNlcjpzZWNyZXQ=", true, "user", "secret")]
|
||||
[InlineData("Basic dXNlcnNlY3JldA==", false, null, null)] // no colon to seperate user and password
|
||||
[InlineData("Bearer dXNlcjpzZWNyZXQ=", false, null, null)]
|
||||
public void TryDecodeBasicAuth(string input, bool expectedResult, string? expectedUser, string? expectedPassword)
|
||||
{
|
||||
var result = HeaderHelpers.TryDecodeBasicAuth(input, out string? user, out string? password);
|
||||
|
||||
Assert.Equal(expectedResult, result);
|
||||
Assert.Equal(expectedUser, user);
|
||||
Assert.Equal(expectedPassword, password);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
using System.Buffers.Text;
|
||||
using System.Security.Cryptography;
|
||||
using IdentityShroud.Core.Contracts;
|
||||
using IdentityShroud.Core.Model;
|
||||
using IdentityShroud.Core.Security;
|
||||
using IdentityShroud.Core.Security.Keys;
|
||||
using IdentityShroud.Core.Services;
|
||||
using IdentityShroud.TestUtils.Substitutes;
|
||||
|
||||
namespace IdentityShroud.Api.Tests.Mappers;
|
||||
|
||||
public class KeyServiceTests
|
||||
{
|
||||
private readonly NullDekEncryptionService _dekEncryptionService = new();
|
||||
|
||||
[Fact]
|
||||
public void Test()
|
||||
{
|
||||
// Setup
|
||||
using RSA rsa = RSA.Create(2048);
|
||||
|
||||
RSAParameters parameters = rsa.ExportParameters(includePrivateParameters: false);
|
||||
|
||||
DekId kid = DekId.NewId();
|
||||
|
||||
RealmKey realmKey = new()
|
||||
{
|
||||
Id = new("60bb79cf-4bac-4521-87f2-ac87cc15541f"),
|
||||
KeyType = "RSA",
|
||||
Key = new(_dekEncryptionService.KeyId, rsa.ExportPkcs8PrivateKey()),
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
Priority = 10,
|
||||
};
|
||||
|
||||
// Act
|
||||
KeyService sut = new(_dekEncryptionService, new KeyProviderFactory(), new ClockService());
|
||||
var jwk = sut.CreateJsonWebKey(realmKey);
|
||||
|
||||
Assert.NotNull(jwk);
|
||||
Assert.Equal("RSA", jwk.KeyType);
|
||||
Assert.Equal(realmKey.Id.ToString(), jwk.KeyId);
|
||||
Assert.Equal("sig", jwk.Use);
|
||||
Assert.Equal(parameters.Exponent, Base64Url.DecodeFromChars(jwk.Exponent));
|
||||
Assert.Equal(parameters.Modulus, Base64Url.DecodeFromChars(jwk.Modulus));
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue