Asp.net core 挂接到IdentityServer4会话cookie中

Asp.net core 挂接到IdentityServer4会话cookie中,asp.net-core,identityserver4,session-cookies,slidingexpiration,Asp.net Core,Identityserver4,Session Cookies,Slidingexpiration,当IdentityServer在会话cookie上执行过期时间滑动时(idsrv),我需要运行一些自定义代码(管理另一个自定义cookie) 如何或在何处连接到IdentityServer管道以实现这一点? 是否有我可以覆盖的内容,或者是否有我可以订阅的事件 我目前正在asp.net core 3.1应用程序中使用IdentityServer4 3.x。扩展只是添加默认的cookie处理程序。并根据传递的值设置道具 根据官方描述,滑动过期的工作原理如下: SlidingExpiration设置为

当IdentityServer在会话cookie上执行过期时间滑动时(
idsrv
),我需要运行一些自定义代码(管理另一个自定义cookie)

如何或在何处连接到IdentityServer管道以实现这一点? 是否有我可以覆盖的内容,或者是否有我可以订阅的事件

我目前正在asp.net core 3.1应用程序中使用IdentityServer4 3.x。

扩展只是添加默认的cookie处理程序。并根据传递的值设置道具

根据官方描述,滑动过期的工作原理如下:

SlidingExpiration设置为true,指示处理程序在处理过期时间超过一半的请求时,以新的过期时间重新发布新cookie


考虑到这些,如果你需要在会话cookie上滑动过期时间,你需要有一个定制的cookie处理程序,它以不同的方式处理事情,这是使用标准cookie处理程序

每当刷新cookie时,它不会发出任何外部事件,但是有一些方法可以通过副作用检测到这一点

如果您使用的是自定义ITicketStore,则可以使用StoreAsync来检测票证的更改时间

如果未使用自定义票证存储,则可以在连接身份验证中间件之前连接中间件:

public class CookieSlidingMiddleware
{
    private readonly RequestDelegate next;
    
    public CookieSlidingMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext httpContext)
    {
        httpContext.Response.OnStarting(ResponseStarting, httpContext);
        await next(httpContext);
    }

    public async Task ResponseStarting(object contextObject)
    {
        HttpContext httpContext = (HttpContext)contextObject;
        var reponseCookies = httpContext.Response.Cookies;

        if (httpContext.Response.Headers.ContainsKey("Set-Cookie"))
        {
            foreach (var setCookie in httpContext.Response.Headers["Set-Cookie"])
            {
                var cookie = SetCookieHeaderValue.Parse(setCookie);
                if (cookie.Name == "idsrv")
                {
                    if (cookie.Expires == null)
                    {
                        // The cookie is a session cookie, and not sliding
                        return;
                    }
                    else if (cookie.Expires == DateTime.UnixEpoch)
                    {
                        // the cookie is being deleted
                        return;
                    }
                    else if (!httpContext.Request.Cookies.ContainsKey("idsrv"))
                    {
                        // The cookie is being set for the first time
                        return;
                    }
                    else
                    {
                        // the cookie is being refreshed
                        
                        // Do stuff here;
                        return;
                    }
                }
            }
        }
    }
}
cookie身份验证在自己的Response.OnStarting事件处理程序中处理cookie刷新

此事件处理程序当前实现为函数堆栈,因此按相反顺序调用(即,必须在验证中间件之前调用此中间件)

然而,我不认为有任何关于这个呼叫订单的保证,所以在将来可能有必要切换订单