diff --git a/src/IdentityServer4/src/Services/Default/DefaultTokenService.cs b/src/IdentityServer4/src/Services/Default/DefaultTokenService.cs index 1042951efe..0085e5d8b7 100644 --- a/src/IdentityServer4/src/Services/Default/DefaultTokenService.cs +++ b/src/IdentityServer4/src/Services/Default/DefaultTokenService.cs @@ -197,6 +197,11 @@ public virtual async Task CreateAccessTokenAsync(TokenCreationRequest req claims.Add(new Claim(JwtClaimTypes.JwtId, CryptoRandom.CreateUniqueId(16))); } + if (request.ValidatedRequest.SessionId.IsPresent()) + { + claims.Add(new Claim(JwtClaimTypes.SessionId, request.ValidatedRequest.SessionId)); + } + var issuer = ContextAccessor.HttpContext.GetIdentityServerIssuerUri(); var token = new Token(OidcConstants.TokenTypes.AccessToken) { @@ -236,7 +241,7 @@ public virtual async Task CreateAccessTokenAsync(TokenCreationRequest req } } } - + return token; } diff --git a/src/IdentityServer4/test/IdentityServer.UnitTests/Services/Default/DefaultTokenServiceTests.cs b/src/IdentityServer4/test/IdentityServer.UnitTests/Services/Default/DefaultTokenServiceTests.cs index 9c69121e37..e95c12301e 100644 --- a/src/IdentityServer4/test/IdentityServer.UnitTests/Services/Default/DefaultTokenServiceTests.cs +++ b/src/IdentityServer4/test/IdentityServer.UnitTests/Services/Default/DefaultTokenServiceTests.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Threading.Tasks; using FluentAssertions; +using IdentityModel; using IdentityServer.UnitTests.Common; using IdentityServer4.Configuration; using IdentityServer4.Models; @@ -114,5 +115,41 @@ public async Task CreateAccessTokenAsync_when_no_apiresources_should_not_include result.Audiences.Count.Should().Be(0); } + + + [Fact] + public async Task CreateAccessTokenAsync_when_no_session_should_not_include_sid() + { + var request = new TokenCreationRequest + { + ValidatedResources = new ResourceValidationResult(), + ValidatedRequest = new ValidatedRequest() + { + Client = new Client { }, + SessionId = null + } + }; + + var result = await _subject.CreateAccessTokenAsync(request); + + result.Claims.SingleOrDefault(x => x.Type == JwtClaimTypes.SessionId).Should().BeNull(); + } + [Fact] + public async Task CreateAccessTokenAsync_when_session_should_include_sid() + { + var request = new TokenCreationRequest + { + ValidatedResources = new ResourceValidationResult(), + ValidatedRequest = new ValidatedRequest() + { + Client = new Client { }, + SessionId = "123" + } + }; + + var result = await _subject.CreateAccessTokenAsync(request); + + result.Claims.SingleOrDefault(x => x.Type == JwtClaimTypes.SessionId).Value.Should().Be("123"); + } } }