Browse Source

Always populate the identifier properties from the claims to ensure validation checks are executed even if the token entry is not resolved

pull/2581/head
Kévin Chalet 5 days ago
parent
commit
12f00efddb
  1. 4
      src/OpenIddict.Client/OpenIddictClientHandlers.Protection.cs
  2. 1
      src/OpenIddict.Client/OpenIddictClientService.cs
  3. 6
      src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs
  4. 6
      src/OpenIddict.Validation/OpenIddictValidationHandlers.Protection.cs
  5. 185
      test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Protection.cs
  6. 178
      test/OpenIddict.Validation.IntegrationTests/OpenIddictValidationIntegrationTests.Protection.cs
  7. 6
      test/OpenIddict.Validation.IntegrationTests/OpenIddictValidationIntegrationTests.cs

4
src/OpenIddict.Client/OpenIddictClientHandlers.Protection.cs

@ -493,6 +493,10 @@ public static partial class OpenIddictClientHandlers
return ValueTask.CompletedTask;
}
// Always resolve the token identifier from the claim in case no
// token entry is available to restore it from the database.
context.TokenId = context.Principal.GetTokenId();
// In OpenIddict 3.0, the creation date of a token is stored in "oi_crt_dt".
// If the claim doesn't exist, try to infer it from the standard "iat" JWT claim.
if (!context.Principal.HasClaim(Claims.Private.CreationDate))

1
src/OpenIddict.Client/OpenIddictClientService.cs

@ -524,6 +524,7 @@ public class OpenIddictClientService
DisableUserInfoRetrieval = request.DisableUserInfo,
DisableUserInfoValidation = request.DisableUserInfo,
GrantType = request.GrantType,
Issuer = request.Issuer,
ProviderName = request.ProviderName,
RegistrationId = request.RegistrationId,
Request = new(),

6
src/OpenIddict.Server/OpenIddictServerHandlers.Protection.cs

@ -651,6 +651,12 @@ public static partial class OpenIddictServerHandlers
return ValueTask.CompletedTask;
}
// Always resolve the authorization/session/token identifiers from the claims
// in case no token entry is available to restore them from the database.
context.AuthorizationId = context.Principal.GetAuthorizationId();
context.SessionId = context.Principal.GetSessionId();
context.TokenId = context.Principal.GetTokenId();
// To reduce the size of tokens, some of the private claims used by OpenIddict
// are mapped to their standard equivalent before being removed from the token.
// This handler is responsible for adding back the private claims to the principal

6
src/OpenIddict.Validation/OpenIddictValidationHandlers.Protection.cs

@ -440,6 +440,12 @@ public static partial class OpenIddictValidationHandlers
return ValueTask.CompletedTask;
}
// Always resolve the authorization/session/token identifiers from the claims
// in case no token entry is available to restore them from the database.
context.AuthorizationId = context.Principal.GetAuthorizationId();
context.SessionId = context.Principal.GetSessionId();
context.TokenId = context.Principal.GetTokenId();
// To reduce the size of tokens, some of the private claims used by OpenIddict
// are mapped to their standard equivalent before being removed from the token.
// This handler is responsible for adding back the private claims to the principal

185
test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Protection.cs

@ -18,6 +18,183 @@ namespace OpenIddict.Server.IntegrationTests;
public abstract partial class OpenIddictServerIntegrationTests
{
[Fact]
public async Task ValidateToken_TokenIdentifiersAreRestoredFromClaims()
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
options.EnableDegradedMode();
options.SetUserInfoEndpointUris("/authenticate");
options.AddEventHandler<HandleUserInfoRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
context.SkipRequest();
return ValueTask.CompletedTask;
}));
options.AddEventHandler<ValidateTokenContext>(builder =>
{
builder.UseInlineHandler(context =>
{
Assert.Equal("access_token", context.Token);
Assert.Equal([TokenTypeIdentifiers.AccessToken], context.ValidTokenTypes);
context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer"))
.SetTokenType(TokenTypeIdentifiers.AccessToken)
.SetClaim(Claims.Subject, "Bob le Magnifique")
.SetAuthorizationId("18D15F73-BE2B-6867-DC01-B3C1E8AFDED0")
.SetSessionId("D61DB5C2-235F-4755-9B6F-7D31404A4771")
.SetTokenId("3E228451-1555-46F7-A471-951EFBA23A56");
return ValueTask.CompletedTask;
});
builder.SetOrder(ValidateIdentityModelToken.Descriptor.Order - 500);
});
options.AddEventHandler<ValidateTokenContext>(builder =>
{
builder.UseInlineHandler(context =>
{
Assert.Equal("18D15F73-BE2B-6867-DC01-B3C1E8AFDED0", context.Principal!.GetAuthorizationId());
Assert.Equal("D61DB5C2-235F-4755-9B6F-7D31404A4771", context.Principal!.GetSessionId());
Assert.Equal("3E228451-1555-46F7-A471-951EFBA23A56", context.Principal!.GetTokenId());
return ValueTask.CompletedTask;
});
builder.SetOrder(int.MaxValue);
});
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.GetAsync("/authenticate", new OpenIddictRequest
{
AccessToken = "access_token"
});
// Assert
Assert.Equal("Bob le Magnifique", (string?) response[Claims.Subject]);
}
[Fact]
public async Task ValidateToken_TokenIdentifiersAreRestoredFromDatabaseEntry()
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
options.SetUserInfoEndpointUris("/authenticate");
options.AddEventHandler<HandleUserInfoRequestContext>(builder =>
builder.UseInlineHandler(context =>
{
context.SkipRequest();
return ValueTask.CompletedTask;
}));
options.AddEventHandler<ValidateTokenContext>(builder =>
{
builder.UseInlineHandler(context =>
{
Assert.Equal("access_token", context.Token);
Assert.Equal([TokenTypeIdentifiers.AccessToken], context.ValidTokenTypes);
context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer"))
.SetTokenType(TokenTypeIdentifiers.AccessToken)
.SetClaim(Claims.Subject, "Bob le Magnifique")
.SetAuthorizationId("18D15F73-BE2B-6867-DC01-B3C1E8AFDED0")
.SetSessionId("D61DB5C2-235F-4755-9B6F-7D31404A4771")
.SetTokenId("3E228451-1555-46F7-A471-951EFBA23A56");
return ValueTask.CompletedTask;
});
builder.SetOrder(ValidateIdentityModelToken.Descriptor.Order - 500);
});
options.AddEventHandler<ValidateTokenContext>(builder =>
{
builder.UseInlineHandler(context =>
{
Assert.Equal("0EB8CC35-F389-4F06-A156-9220B79C2101", context.Principal!.GetAuthorizationId());
Assert.Equal("563D96CC-9758-4D3E-AC4C-A0253D9DE192", context.Principal!.GetSessionId());
Assert.Equal("92A7963F-ECAF-4A3E-8A47-3A62DAFDF466", context.Principal!.GetTokenId());
return ValueTask.CompletedTask;
});
builder.SetOrder(int.MaxValue);
});
options.Services.AddSingleton(CreateTokenManager(mock =>
{
var token = new OpenIddictToken();
mock.Setup(manager => manager.FindByIdAsync("3E228451-1555-46F7-A471-951EFBA23A56", It.IsAny<CancellationToken>()))
.ReturnsAsync(token);
// Note: the GUIDs used here are deliberately different from the ones used in the
// principal to ensure that the identifiers are restored from the database entry.
mock.Setup(manager => manager.GetIdAsync(token, It.IsAny<CancellationToken>()))
.ReturnsAsync("92A7963F-ECAF-4A3E-8A47-3A62DAFDF466");
mock.Setup(manager => manager.GetAuthorizationIdAsync(token, It.IsAny<CancellationToken>()))
.ReturnsAsync("0EB8CC35-F389-4F06-A156-9220B79C2101");
mock.Setup(manager => manager.GetSessionIdAsync(token, It.IsAny<CancellationToken>()))
.ReturnsAsync("563D96CC-9758-4D3E-AC4C-A0253D9DE192");
mock.Setup(manager => manager.FindByIdAsync("92A7963F-ECAF-4A3E-8A47-3A62DAFDF466", It.IsAny<CancellationToken>()))
.ReturnsAsync(token);
mock.Setup(manager => manager.GetTypeAsync(token, It.IsAny<CancellationToken>()))
.ReturnsAsync(TokenTypeIdentifiers.AccessToken);
mock.Setup(manager => manager.HasStatusAsync(token, Statuses.Valid, It.IsAny<CancellationToken>()))
.ReturnsAsync(true);
}));
options.Services.AddSingleton(CreateAuthorizationManager(mock =>
{
var authorization = new OpenIddictAuthorization();
mock.Setup(manager => manager.FindByIdAsync("0EB8CC35-F389-4F06-A156-9220B79C2101", It.IsAny<CancellationToken>()))
.ReturnsAsync(authorization);
mock.Setup(manager => manager.HasStatusAsync(authorization, Statuses.Valid, It.IsAny<CancellationToken>()))
.ReturnsAsync(true);
}));
options.Services.AddSingleton(CreateSessionManager(mock =>
{
var session = new OpenIddictSession();
mock.Setup(manager => manager.FindByIdAsync("563D96CC-9758-4D3E-AC4C-A0253D9DE192", It.IsAny<CancellationToken>()))
.ReturnsAsync(session);
mock.Setup(manager => manager.HasStatusAsync(session, Statuses.Valid, It.IsAny<CancellationToken>()))
.ReturnsAsync(true);
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.GetAsync("/authenticate", new OpenIddictRequest
{
AccessToken = "access_token"
});
// Assert
Assert.Equal("Bob le Magnifique", (string?) response[Claims.Subject]);
}
[Fact]
public async Task ValidateToken_IssuedAtIsMappedToCreationDate()
{
@ -872,7 +1049,7 @@ public abstract partial class OpenIddictServerIntegrationTests
var manager = CreateSessionManager(mock =>
{
mock.Setup(manager => manager.FindByIdAsync("DE7F0AF0-9595-4546-BE3D-F6BB43FB5FA5", It.IsAny<CancellationToken>()))
mock.Setup(manager => manager.FindByIdAsync("D61DB5C2-235F-4755-9B6F-7D31404A4771", It.IsAny<CancellationToken>()))
.ReturnsAsync(session);
mock.Setup(manager => manager.HasStatusAsync(session, Statuses.Valid, It.IsAny<CancellationToken>()))
@ -891,7 +1068,7 @@ public abstract partial class OpenIddictServerIntegrationTests
context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer"))
.SetTokenType(TokenTypeIdentifiers.RefreshToken)
.SetTokenId("60FFF7EA-F98E-437B-937E-5073CC313103")
.SetSessionId("18D15F73-BE2B-6867-DC01-B3C1E8AFDED0")
.SetSessionId("D61DB5C2-235F-4755-9B6F-7D31404A4771")
.SetClaim(Claims.Subject, "Bob le Bricoleur");
return ValueTask.CompletedTask;
@ -920,7 +1097,7 @@ public abstract partial class OpenIddictServerIntegrationTests
.ReturnsAsync(true);
mock.Setup(manager => manager.GetSessionIdAsync(token, It.IsAny<CancellationToken>()))
.ReturnsAsync("DE7F0AF0-9595-4546-BE3D-F6BB43FB5FA5");
.ReturnsAsync("D61DB5C2-235F-4755-9B6F-7D31404A4771");
}));
options.Services.AddSingleton(manager);
@ -943,7 +1120,7 @@ public abstract partial class OpenIddictServerIntegrationTests
Assert.Equal(SR.GetResourceString(SR.ID2210), response.ErrorDescription);
Assert.Equal(SR.FormatID8000(SR.ID2210), response.ErrorUri);
Mock.Get(manager).Verify(manager => manager.FindByIdAsync("DE7F0AF0-9595-4546-BE3D-F6BB43FB5FA5", It.IsAny<CancellationToken>()), Times.Once());
Mock.Get(manager).Verify(manager => manager.FindByIdAsync("D61DB5C2-235F-4755-9B6F-7D31404A4771", It.IsAny<CancellationToken>()), Times.Once());
Mock.Get(manager).Verify(manager => manager.HasStatusAsync(session, Statuses.Valid, It.IsAny<CancellationToken>()), Times.Once());
}
}

178
test/OpenIddict.Validation.IntegrationTests/OpenIddictValidationIntegrationTests.Protection.cs

@ -0,0 +1,178 @@
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
*/
using System.Security.Claims;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Moq;
using Xunit;
using static OpenIddict.Validation.OpenIddictValidationEvents;
using static OpenIddict.Validation.OpenIddictValidationHandlers.Protection;
namespace OpenIddict.Validation.IntegrationTests;
public abstract partial class OpenIddictValidationIntegrationTests
{
[Fact]
public async Task ValidateToken_TokenIdentifiersAreRestoredFromClaims()
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
options.AddEventHandler<ValidateTokenContext>(builder =>
{
builder.UseInlineHandler(context =>
{
Assert.Equal("access_token", context.Token);
Assert.Equal([TokenTypeIdentifiers.AccessToken], context.ValidTokenTypes);
context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer"))
.SetTokenType(TokenTypeIdentifiers.AccessToken)
.SetClaim(Claims.Subject, "Bob le Magnifique")
.SetAuthorizationId("18D15F73-BE2B-6867-DC01-B3C1E8AFDED0")
.SetSessionId("D61DB5C2-235F-4755-9B6F-7D31404A4771")
.SetTokenId("3E228451-1555-46F7-A471-951EFBA23A56");
return ValueTask.CompletedTask;
});
builder.SetOrder(ValidateIdentityModelToken.Descriptor.Order - 500);
});
options.AddEventHandler<ValidateTokenContext>(builder =>
{
builder.UseInlineHandler(context =>
{
Assert.Equal("18D15F73-BE2B-6867-DC01-B3C1E8AFDED0", context.Principal!.GetAuthorizationId());
Assert.Equal("D61DB5C2-235F-4755-9B6F-7D31404A4771", context.Principal!.GetSessionId());
Assert.Equal("3E228451-1555-46F7-A471-951EFBA23A56", context.Principal!.GetTokenId());
return ValueTask.CompletedTask;
});
builder.SetOrder(int.MaxValue);
});
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.GetAsync("/authenticate", new OpenIddictRequest
{
AccessToken = "access_token"
});
// Assert
Assert.Equal("Bob le Magnifique", (string?) response[Claims.Subject]);
}
[Fact]
public async Task ValidateToken_TokenIdentifiersAreRestoredFromDatabaseEntry()
{
// Arrange
await using var server = await CreateServerAsync(options =>
{
options.EnableAuthorizationEntryValidation();
options.EnableSessionEntryValidation();
options.EnableTokenEntryValidation();
options.AddEventHandler<ValidateTokenContext>(builder =>
{
builder.UseInlineHandler(context =>
{
Assert.Equal("access_token", context.Token);
Assert.Equal([TokenTypeIdentifiers.AccessToken], context.ValidTokenTypes);
context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer"))
.SetTokenType(TokenTypeIdentifiers.AccessToken)
.SetClaim(Claims.Subject, "Bob le Magnifique")
.SetAuthorizationId("18D15F73-BE2B-6867-DC01-B3C1E8AFDED0")
.SetSessionId("D61DB5C2-235F-4755-9B6F-7D31404A4771")
.SetTokenId("3E228451-1555-46F7-A471-951EFBA23A56");
return ValueTask.CompletedTask;
});
builder.SetOrder(ValidateIdentityModelToken.Descriptor.Order - 500);
});
options.AddEventHandler<ValidateTokenContext>(builder =>
{
builder.UseInlineHandler(context =>
{
Assert.Equal("0EB8CC35-F389-4F06-A156-9220B79C2101", context.Principal!.GetAuthorizationId());
Assert.Equal("563D96CC-9758-4D3E-AC4C-A0253D9DE192", context.Principal!.GetSessionId());
Assert.Equal("92A7963F-ECAF-4A3E-8A47-3A62DAFDF466", context.Principal!.GetTokenId());
return ValueTask.CompletedTask;
});
builder.SetOrder(int.MaxValue);
});
options.Services.AddSingleton(CreateTokenManager(mock =>
{
var token = new OpenIddictToken();
mock.Setup(manager => manager.FindByIdAsync("3E228451-1555-46F7-A471-951EFBA23A56", It.IsAny<CancellationToken>()))
.ReturnsAsync(token);
// Note: the GUIDs used here are deliberately different from the ones used in the
// principal to ensure that the identifiers are restored from the database entry.
mock.Setup(manager => manager.GetIdAsync(token, It.IsAny<CancellationToken>()))
.ReturnsAsync("92A7963F-ECAF-4A3E-8A47-3A62DAFDF466");
mock.Setup(manager => manager.GetAuthorizationIdAsync(token, It.IsAny<CancellationToken>()))
.ReturnsAsync("0EB8CC35-F389-4F06-A156-9220B79C2101");
mock.Setup(manager => manager.GetSessionIdAsync(token, It.IsAny<CancellationToken>()))
.ReturnsAsync("563D96CC-9758-4D3E-AC4C-A0253D9DE192");
mock.Setup(manager => manager.FindByIdAsync("92A7963F-ECAF-4A3E-8A47-3A62DAFDF466", It.IsAny<CancellationToken>()))
.ReturnsAsync(token);
mock.Setup(manager => manager.GetTypeAsync(token, It.IsAny<CancellationToken>()))
.ReturnsAsync(TokenTypeIdentifiers.AccessToken);
mock.Setup(manager => manager.HasStatusAsync(token, Statuses.Valid, It.IsAny<CancellationToken>()))
.ReturnsAsync(true);
}));
options.Services.AddSingleton(CreateAuthorizationManager(mock =>
{
var authorization = new OpenIddictAuthorization();
mock.Setup(manager => manager.FindByIdAsync("0EB8CC35-F389-4F06-A156-9220B79C2101", It.IsAny<CancellationToken>()))
.ReturnsAsync(authorization);
mock.Setup(manager => manager.HasStatusAsync(authorization, Statuses.Valid, It.IsAny<CancellationToken>()))
.ReturnsAsync(true);
}));
options.Services.AddSingleton(CreateSessionManager(mock =>
{
var session = new OpenIddictSession();
mock.Setup(manager => manager.FindByIdAsync("563D96CC-9758-4D3E-AC4C-A0253D9DE192", It.IsAny<CancellationToken>()))
.ReturnsAsync(session);
mock.Setup(manager => manager.HasStatusAsync(session, Statuses.Valid, It.IsAny<CancellationToken>()))
.ReturnsAsync(true);
}));
});
await using var client = await server.CreateClientAsync();
// Act
var response = await client.GetAsync("/authenticate", new OpenIddictRequest
{
AccessToken = "access_token"
});
// Assert
Assert.Equal("Bob le Magnifique", (string?) response[Claims.Subject]);
}
}

6
test/OpenIddict.Validation.IntegrationTests/OpenIddictValidationIntegrationTests.cs

@ -1,6 +1,4 @@

/*
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/openiddict/openiddict-core for more information concerning
* the license and the contributors participating to this project.
@ -24,7 +22,7 @@ using static OpenIddict.Validation.OpenIddictValidationHandlers.Protection;
namespace OpenIddict.Validation.IntegrationTests;
public abstract class OpenIddictValidationIntegrationTests
public abstract partial class OpenIddictValidationIntegrationTests
{
protected OpenIddictValidationIntegrationTests(ITestOutputHelper outputHelper)
{

Loading…
Cancel
Save