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

signout when session token expires #1801

Closed
wants to merge 1 commit into from
Closed
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: 2 additions & 1 deletion bff/hosts/Hosts.Bff.EF/Extensions.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using Duende.Bff;
using Duende.Bff.Yarp;
using Microsoft.AspNetCore.Builder;
Expand Down Expand Up @@ -46,7 +47,7 @@ public static WebApplication ConfigureServices(this WebApplicationBuilder builde
{
// host prefixed cookie name
options.Cookie.Name = "__Host-spa-ef";

options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
// strict SameSite handling
options.Cookie.SameSite = SameSiteMode.Strict;
})
Expand Down
2 changes: 1 addition & 1 deletion bff/hosts/Hosts.Bff.InMemory/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ Func<IServiceProvider> getServiceProvider
.AddCookie("cookie", options =>
{
// set session lifetime
options.ExpireTimeSpan = TimeSpan.FromHours(8);
options.ExpireTimeSpan = TimeSpan.FromMinutes(8);

// sliding or absolute
options.SlidingExpiration = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ private async Task Initialize()
AllowOfflineAccess = true,
AllowedScopes = { "openid", "profile", "api", "scope-for-isolated-api" },

AccessTokenLifetime = 75 // Force refresh
RefreshTokenExpiration = TokenExpiration.Absolute,
AbsoluteRefreshTokenLifetime = 60,
AccessTokenLifetime = 15 // Force refresh
},
new Client
{
Expand Down Expand Up @@ -101,8 +103,9 @@ private async Task Initialize()

AllowOfflineAccess = true,
AllowedScopes = { "openid", "profile", "api", "scope-for-isolated-api" },

AccessTokenLifetime = 75 // Force refresh
RefreshTokenExpiration = TokenExpiration.Absolute,
AbsoluteRefreshTokenLifetime = 60,
AccessTokenLifetime = 15 // Force refresh
},

new Client
Expand Down
2 changes: 1 addition & 1 deletion bff/src/Bff/Configuration/BffOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ public class BffOptions
/// Interval at which expired sessions are cleaned up.
/// Defaults to 10 minutes.
/// </summary>
public TimeSpan SessionCleanupInterval { get; set; } = TimeSpan.FromMinutes(10);
public TimeSpan SessionCleanupInterval { get; set; } = TimeSpan.FromSeconds(10);

///// <summary>
///// Batch size expired sessions are deleted.
Expand Down
46 changes: 43 additions & 3 deletions bff/src/Bff/EndpointProcessing/BffMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@
// See LICENSE in the project root for license information.

using System.Threading.Tasks;
using Duende.AccessTokenManagement.OpenIdConnect;
using Duende.Bff.Logging;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

Expand All @@ -18,18 +21,21 @@ public class BffMiddleware
private readonly RequestDelegate _next;
private readonly BffOptions _options;
private readonly ILogger<BffMiddleware> _logger;
private readonly IAuthenticationSchemeProvider _authenticationSchemeProvider;

/// <summary>
/// ctor
/// </summary>
/// <param name="next"></param>
/// <param name="options"></param>
/// <param name="logger"></param>
public BffMiddleware(RequestDelegate next, IOptions<BffOptions> options, ILogger<BffMiddleware> logger)
/// <param name="authenticationSchemeProvider"></param>
public BffMiddleware(RequestDelegate next, IOptions<BffOptions> options, ILogger<BffMiddleware> logger, IAuthenticationSchemeProvider authenticationSchemeProvider)
{
_next = next;
_options = options.Value;
_logger = logger;
_authenticationSchemeProvider = authenticationSchemeProvider;
}

/// <summary>
Expand All @@ -42,8 +48,6 @@ public async Task Invoke(HttpContext context)
// add marker so we can determine if middleware has run later in the pipeline
context.Items[Constants.BffMiddlewareMarker] = true;

// inbound: add CSRF check for local APIs

var endpoint = context.GetEndpoint();
if (endpoint == null)
{
Expand All @@ -54,6 +58,42 @@ public async Task Invoke(HttpContext context)
var isBffEndpoint = endpoint.Metadata.GetMetadata<IBffApiEndpoint>() != null;
if (isBffEndpoint)
{
if (context.User.Identity?.IsAuthenticated == true)
{
var userTokens = context.RequestServices.GetRequiredService<IUserTokenStore>();
var token = await userTokens.GetTokenAsync(context.User);

if (token.Expiration < DateTimeOffset.Now)
{
_logger.LogInformation("expired");

var tokenService = context.RequestServices.GetRequiredService<IUserTokenManagementService>();

token = await tokenService.GetAccessTokenAsync(context.User);

if (token.Expiration < DateTimeOffset.Now)
{
// get rid of local cookie first
var signInScheme = await _authenticationSchemeProvider.GetDefaultSignInSchemeAsync();
await context.SignOutAsync(signInScheme?.Name);

var props = new AuthenticationProperties
{
RedirectUri = "/"
};


// trigger idp logout
await context.SignOutAsync(props);
//context.RequestServices.GetRequiredService<IUserSessionStore>().DeleteUserSessionAsync()
context.Response.StatusCode = 401;
return;
}

}
}


var requireAntiForgeryCheck = endpoint.Metadata.GetMetadata<IBffApiSkipAntiforgery>() == null;
if (requireAntiForgeryCheck)
{
Expand Down
Loading