Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

when renewing server-side session, create new entry if current session not found #1008

Merged
merged 2 commits into from
Aug 30, 2022
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
8 changes: 4 additions & 4 deletions src/EntityFramework.Storage/Stores/ServerSideSessionStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public virtual async Task CreateSessionAsync(ServerSideSession session, Cancella
await Context.SaveChangesAsync(cancellationToken);
Logger.LogDebug("Created new server-side session {serverSideSessionKey} in database", session.Key);
}
catch (DbUpdateConcurrencyException ex)
catch (DbUpdateException ex)
{
Logger.LogWarning("Exception creating new server-side session in database: {error}", ex.Message);
}
Expand Down Expand Up @@ -150,7 +150,7 @@ public virtual async Task UpdateSessionAsync(ServerSideSession session, Cancella
await Context.SaveChangesAsync(cancellationToken);
Logger.LogDebug("Updated server-side session {serverSideSessionKey} in database", session.Key);
}
catch (DbUpdateConcurrencyException ex)
catch (DbUpdateException ex)
{
Logger.LogWarning("Exception updating existing server side session {serverSideSessionKey} in database: {error}", session.Key, ex.Message);
}
Expand Down Expand Up @@ -180,7 +180,7 @@ public virtual async Task DeleteSessionAsync(string key, CancellationToken cance
await Context.SaveChangesAsync(cancellationToken);
Logger.LogDebug("Deleted server-side session {serverSideSessionKey} in database", key);
}
catch (DbUpdateConcurrencyException ex)
catch (DbUpdateException ex)
{
Logger.LogWarning("Exception deleting server-side session {serverSideSessionKey} in database: {error}", key, ex.Message);
}
Expand Down Expand Up @@ -239,7 +239,7 @@ public virtual async Task DeleteSessionsAsync(SessionFilter filter, Cancellation
await Context.SaveChangesAsync(cancellationToken);
Logger.LogDebug("Removed {serverSideSessionCount} server-side sessions from database for {@filter}", entities.Length, filter);
}
catch (DbUpdateConcurrencyException ex)
catch (DbUpdateException ex)
{
Logger.LogInformation("Error removing {serverSideSessionCount} server-side sessions from database for {@filter}: {error}", entities.Length, filter, ex.Message);
}
Expand Down
13 changes: 10 additions & 3 deletions src/IdentityServer/Stores/Default/ServerSideTicketStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,13 @@ public async Task<string> StoreAsync(AuthenticationTicket ticket)

var key = CryptoRandom.CreateUniqueId(format: CryptoRandom.OutputFormat.Hex);

await CreateNewSessionAsync(key, ticket);

return key;
}

private async Task CreateNewSessionAsync(string key, AuthenticationTicket ticket)
{
_logger.LogDebug("Creating entry in store for AuthenticationTicket, key {key}, with expiration: {expiration}", key, ticket.GetExpiration());

var session = new ServerSideSession
Expand All @@ -77,8 +84,6 @@ public async Task<string> StoreAsync(AuthenticationTicket ticket)
};

await _store.CreateSessionAsync(session);

return key;
}

/// <inheritdoc />
Expand Down Expand Up @@ -121,7 +126,9 @@ public async Task RenewAsync(string key, AuthenticationTicket ticket)
var session = await _store.GetSessionAsync(key);
if (session == null)
{
throw new InvalidOperationException($"No matching item in store for key `{key}`");
// https://github.com/dotnet/aspnetcore/issues/41516#issuecomment-1178076544
await CreateNewSessionAsync(key, ticket);
return;
}

_logger.LogDebug("Renewing AuthenticationTicket for key {key}, with expiration: {expiration}", key, ticket.GetExpiration());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
using System.Collections.Generic;
using System;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Session;
using FluentAssertions.Common;
using Duende.IdentityServer;

namespace IntegrationTests.Hosting;

Expand All @@ -38,23 +42,37 @@ public class MockServerUrls : IServerUrls
public string Origin { get; set; }
public string BasePath { get; set; }
}

public bool ShouldRenewCookie { get; set; } = false;

public ServerSideSessionTests()
{
_urls.Origin = IdentityServerPipeline.BaseUrl;
_urls.BasePath = "/";
_pipeline.OnPostConfigureServices += s =>
_pipeline.OnPostConfigureServices += s =>
{
s.PostConfigure<CookieAuthenticationOptions>(IdentityServerConstants.DefaultCookieAuthenticationScheme, opts =>
{
opts.Events.OnValidatePrincipal = async ctx =>
{
ctx.ShouldRenew = ShouldRenewCookie;
if (ShouldRenewCookie)
{
await _sessionStore.DeleteSessionsAsync(new SessionFilter { SubjectId = "bob" });
}
};
});

s.AddSingleton<IServerUrls>(_urls);
s.AddIdentityServerBuilder().AddServerSideSessions();
};
_pipeline.OnPostConfigure += app =>
{
_pipeline.Options.ServerSideSessions.RemoveExpiredSessionsFrequency = TimeSpan.FromMilliseconds(100);

app.Map("/user", ep => {
ep.Run(ctx =>
{
app.Map("/user", ep =>
{
ep.Run(ctx =>
{
if (ctx.User.Identity.IsAuthenticated)
{
ctx.Response.StatusCode = 200;
Expand Down Expand Up @@ -122,6 +140,18 @@ public async Task login_should_create_server_side_session()
(await IsLoggedIn()).Should().BeTrue();
}

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

ShouldRenewCookie = true;
(await IsLoggedIn()).Should().BeTrue();

(await _sessionStore.GetSessionsAsync(new SessionFilter { SubjectId = "bob" })).Should().NotBeEmpty();
}

[Fact]
[Trait("Category", Category)]
public async Task remove_server_side_session_should_logout_user()
Expand Down