Skip to content
Merged
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
3 changes: 3 additions & 0 deletions docs/reference/options.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ IdentityServer Options
* ``AccessTokenJwtType``
Specifies the value used for the JWT typ header for access tokens (defaults to ``at+jwt``).

* ``IdentityTokenJwtTypes``
Specifies the allowable JWT typ values during identity token validation. (defaults to ``JWT``).

* ``EmitScopesAsSpaceDelimitedStringInJwt``
Specifies whether scopes in JWTs are emitted as array or string

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ public class IdentityServerOptions
/// The JWT typ value.
/// </value>
public string AccessTokenJwtType { get; set; } = "at+jwt";

/// <summary>
/// Gets or sets the accepted JWT typ header values for identity tokens.
/// </summary>
public ICollection<string> IdentityTokenJwtTypes { get; set; } = ["JWT"];

/// <summary>
/// Emits an aud claim with the format issuer/resources. That's needed for some older access token validation plumbing. Defaults to false.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,31 +122,42 @@ public async Task<EndSessionValidationResult> ValidateAsync(NameValueCollection
};

var idTokenHint = parameters.Get(OidcConstants.EndSessionRequest.IdTokenHint);
TokenValidationResult tokenValidationResult = null;

if (idTokenHint.IsPresent())
{
// validate id_token - no need to validate token life time
var tokenValidationResult = await TokenValidator.ValidateIdentityTokenAsync(idTokenHint, null, false);
if (tokenValidationResult.IsError)
var hintValidationResult = await TokenValidator.ValidateIdentityTokenAsync(idTokenHint, null, false);
var hasSubject = hintValidationResult.Claims?
.Any(c => c.Type == JwtClaimTypes.Subject && c.Value.IsPresent())
?? false;

if (!hintValidationResult.IsError && hasSubject)
{
tokenValidationResult = hintValidationResult;
}
else
{
return Invalid("Error validating id token hint", validatedRequest);
Logger.LogWarning("Ignoring id_token_hint that is invalid or has no subject claim.");
}
}

if (tokenValidationResult != null)
{
validatedRequest.Client = tokenValidationResult.Client;

// validate sub claim against currently logged on user

var subClaim = tokenValidationResult.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.Subject);
if (subClaim != null && isAuthenticated)
{
if (subject.GetSubjectId() != subClaim.Value)
{
return Invalid("Current user does not match identity token", validatedRequest);
}

validatedRequest.Subject = subject;
validatedRequest.SessionId = await UserSession.GetSessionIdAsync();
validatedRequest.ClientIds = await UserSession.GetClientListAsync();
}

var redirectUri = parameters.Get(OidcConstants.EndSessionRequest.PostLogoutRedirectUri);
if (redirectUri.IsPresent())
{
Expand All @@ -159,7 +170,7 @@ public async Task<EndSessionValidationResult> ValidateAsync(NameValueCollection
Logger.LogWarning("Invalid PostLogoutRedirectUri: {postLogoutRedirectUri}", redirectUri);
}
}

if (validatedRequest.PostLogOutUri != null)
{
var state = parameters.Get(OidcConstants.EndSessionRequest.State);
Expand All @@ -171,7 +182,6 @@ public async Task<EndSessionValidationResult> ValidateAsync(NameValueCollection
}
else
{
// no id_token to authenticate the client, but we do have a user and a user session
validatedRequest.Subject = subject;
validatedRequest.SessionId = await UserSession.GetSessionIdAsync();
validatedRequest.ClientIds = await UserSession.GetClientListAsync();
Expand Down
23 changes: 20 additions & 3 deletions src/Open.IdentityServer/src/Validation/Default/TokenValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,12 @@ public async Task<TokenValidationResult> ValidateIdentityTokenAsync(string token
_logger.LogDebug("Client found: {clientId} / {clientName}", client.ClientId, client.ClientName);

var keys = await _keys.GetValidationKeysAsync();
var result = await ValidateJwtAsync(token, keys, audience: clientId, validateLifetime: validateLifetime);
var result = await ValidateJwtAsync(
token,
keys,
validateLifetime: validateLifetime,
audience: clientId,
expectedJwtTypes: _options.IdentityTokenJwtTypes ?? Array.Empty<string>());

result.Client = client;

Expand Down Expand Up @@ -248,7 +253,12 @@ public async Task<TokenValidationResult> ValidateAccessTokenAsync(string token,
return customResult;
}

private async Task<TokenValidationResult> ValidateJwtAsync(string jwt, IEnumerable<SecurityKeyInfo> validationKeys, bool validateLifetime = true, string audience = null)
private async Task<TokenValidationResult> ValidateJwtAsync(
string jwt,
IEnumerable<SecurityKeyInfo> validationKeys,
bool validateLifetime = true,
string audience = null,
IEnumerable<string> expectedJwtTypes = null)
{
var handler = new JwtSecurityTokenHandler();
handler.InboundClaimTypeMap.Clear();
Expand All @@ -274,8 +284,15 @@ private async Task<TokenValidationResult> ValidateJwtAsync(string jwt, IEnumerab
var id = handler.ValidateToken(jwt, parameters, out var securityToken);
var jwtSecurityToken = securityToken as JwtSecurityToken;

if (expectedJwtTypes != null)
{
if (!expectedJwtTypes.Contains(jwtSecurityToken.Header.Typ, StringComparer.Ordinal))
{
return Invalid(OidcConstants.ProtectedResourceErrors.InvalidToken);
}
}
// if no audience is specified, we make at least sure that it is an access token
if (audience.IsMissing())
else if (audience.IsMissing())
{
if (_options.AccessTokenJwtType.IsPresent())
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Modified by Rock Solid Knowledge Ltd. Copyright in modifications 2026, Rock Solid Knowledge Ltd.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

using System;
Expand All @@ -19,6 +20,7 @@
using Open.IdentityServer;
using Open.IdentityServer.Utility;
using Xunit;
using System.IdentityModel.Tokens.Jwt;
using static Open.IdentityServer.IdentityServerConstants;
using QueryHelpers = Microsoft.AspNetCore.WebUtilities.QueryHelpers;

Expand Down Expand Up @@ -97,6 +99,23 @@ public EndSessionTests()
_mockPipeline.IdentityScopes.AddRange([
new IdentityResources.OpenId()
]);

_mockPipeline.Clients.Add(new Client
{
ClientId = "orders",
ClientSecrets = { new Secret("secret".Sha256()) },
AllowedGrantTypes = GrantTypes.ClientCredentials,
AllowedScopes = { "orders.read" },
AccessTokenType = AccessTokenType.Jwt,
PostLogoutRedirectUris = { "https://attacker.example/post-logout" }
});

_mockPipeline.ApiResources.Add(new ApiResource
{
Name = "orders",
Scopes = { "orders.read" }
});
_mockPipeline.ApiScopes.Add(new ApiScope { Name = "orders.read" });

_mockPipeline.Initialize();
}
Expand Down Expand Up @@ -600,4 +619,42 @@ await _mockPipeline.BrowserClient.GetAsync(

_mockPipeline.BackChannelMessageHandler.InvokeWasCalled.Should().BeTrue();
}

[Fact]
[Trait("Category", Category)]
public async Task client_credentials_access_token_for_client_id_collision_should_require_logout_prompt()
{
await _mockPipeline.LoginAsync("bob");

var tokenResponse = await _mockPipeline.BackChannelClient!.RequestClientCredentialsTokenAsync(
new ClientCredentialsTokenRequest
{
Address = IdentityServerPipeline.TokenEndpoint,
ClientId = "orders",
ClientSecret = "secret",
Scope = "orders.read"
},
TestContext.Current.CancellationToken);

tokenResponse.IsError.Should().BeFalse();
tokenResponse.AccessToken.Should().NotBeNullOrEmpty();

var jwt = new JwtSecurityTokenHandler().ReadJwtToken(tokenResponse.AccessToken!);
jwt.Audiences.Should().Contain("orders");
jwt.Header.Typ.Should().Be("at+jwt");
jwt.Payload.ContainsKey(JwtClaimTypes.Subject).Should().BeFalse();
jwt.Payload.ContainsKey(JwtClaimTypes.SessionId).Should().BeFalse();

var endSessionUrl = IdentityServerPipeline.EndSessionEndpoint
+ "?id_token_hint=" + Uri.EscapeDataString(tokenResponse.AccessToken!)
+ "&post_logout_redirect_uri="
+ Uri.EscapeDataString("https://attacker.example/post-logout");

await _mockPipeline.BrowserClient!.GetAsync(endSessionUrl, TestContext.Current.CancellationToken);

_mockPipeline.LogoutRequest.Should().NotBeNull();
_mockPipeline.LogoutRequest.ShowSignoutPrompt.Should().BeTrue();
_mockPipeline.LogoutRequest.ClientId.Should().BeNull();
_mockPipeline.LogoutRequest.PostLogoutRedirectUri.Should().BeNull();
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Modified by Rock Solid Knowledge Ltd. Copyright in modifications 2026, Rock Solid Knowledge Ltd.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
#nullable enable

Expand Down Expand Up @@ -443,4 +444,32 @@ public async Task Valid_token_with_invalid_scopes_should_fail()
introspectionResponse.IsActive.Should().Be(false);
introspectionResponse.IsError.Should().Be(false);
}

[Fact]
[Trait("Category", Category)]
public async Task public_client_without_api_secret_cannot_introspect_reference_token()
{
var tokenResponse = await _client.RequestClientCredentialsTokenAsync(
new ClientCredentialsTokenRequest
{
Address = TokenEndpoint,
ClientId = "public.client",
Scope = "api1"
},
TestContext.Current.CancellationToken);

tokenResponse.IsError.Should().BeFalse();
tokenResponse.AccessToken.Should().NotBeNullOrEmpty();

var response = await _client.PostAsync(
IntrospectionEndpoint,
new FormUrlEncodedContent(new Dictionary<string, string>
{
["client_id"] = "public.client",
["token"] = tokenResponse.AccessToken!
}),
TestContext.Current.CancellationToken);

response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Modified by Rock Solid Knowledge Ltd. Copyright in modifications 2026, Rock Solid Knowledge Ltd.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.


Expand Down Expand Up @@ -60,6 +61,14 @@ public static IEnumerable<Client> Get()
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
AllowedScopes = { "api1", "api2", "api3-a", "api3-b" },
AccessTokenType = AccessTokenType.Reference
},
new Client
{
ClientId = "public.client",
RequireClientSecret = false,
AllowedGrantTypes = GrantTypes.ClientCredentials,
AllowedScopes = { "api1" },
AccessTokenType = AccessTokenType.Reference
}
};
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Modified by Rock Solid Knowledge Ltd. Copyright in modifications 2026, Rock Solid Knowledge Ltd.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.


Expand Down Expand Up @@ -232,4 +233,31 @@ public async Task ValidateCallbackAsync_WhenCalled_ShouldTraceTelemetry()
TelemetryConstants.TraceCategories.Validation, _subject, "ValidateCallbackAsync"));
_trace.Verify(t => t.Dispose(), Times.Once);
}

[Fact]
public async Task id_token_hint_without_subject_or_session_should_be_ignored_and_show_signout_prompt()
{
_stubTokenValidator.IdentityTokenValidationResult = new TokenValidationResult
{
IsError = false,
Claims = new Claim[] { },
Client = new Client { ClientId = "client" }
};
_stubRedirectUriValidator.IsPostLogoutRedirectUriValid = true;

var parameters = new NameValueCollection
{
["id_token_hint"] = "id_token",
["post_logout_redirect_uri"] = "https://client/signout-callback"
};

var result = await _subject.ValidateAsync(parameters, _user);

result.IsError.Should().BeFalse();
result.ValidatedRequest.Client.Should().BeNull();
result.ValidatedRequest.PostLogOutUri.Should().BeNull();

var logoutRequest = new LogoutRequest(null, new LogoutMessage(result.ValidatedRequest));
logoutRequest.ShowSignoutPrompt.Should().BeTrue();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
using System.Threading.Tasks;
using AwesomeAssertions;
using Moq;
using Open.IdentityServer;
using Open.IdentityServer.Models;
using Open.IdentityServer.Services;
using Open.IdentityServer.UnitTests.Validation.Setup;
using Xunit;
Expand Down Expand Up @@ -107,4 +109,27 @@ public async Task IdentityToken_ShouldTraceTelemetry()
TelemetryConstants.TraceCategories.Validation, validator, "ValidateIdentityTokenAsync"));
trace.Verify(t => t.Dispose(), Times.Once);
}

[Fact]
[Trait("Category", Category)]
public async Task Signed_AccessToken_with_ClientId_Audience_ShouldNotValidateAs_IdentityToken()
{
var client = new Client { ClientId = "roclient" };
var accessToken = TokenFactory.CreateAccessToken(client, "valid", 600, "read");
accessToken.Audiences.Clear();
accessToken.Audiences.Add(client.ClientId);

var creator = Factory.CreateDefaultTokenCreator();
var jwt = await creator.CreateTokenAsync(accessToken);
new JwtSecurityTokenHandler().ReadJwtToken(jwt).Header.Typ.Should().Be("at+jwt");

var validator = Factory.CreateTokenValidator();
var identityResult = await validator.ValidateIdentityTokenAsync(jwt);

identityResult.IsError.Should().BeTrue();
identityResult.Error.Should().Be(OidcConstants.ProtectedResourceErrors.InvalidToken);

var accessResult = await validator.ValidateAccessTokenAsync(jwt);
accessResult.IsError.Should().BeFalse();
}
}
Loading