如何使用WebSocket在ASP.NET Core 3.1的长寿命管道中检测Bearer令牌到期?

问题描述

我的SPA客户端发送access_token作为Websocket连接上的第一条消息。然后通过调用httpContext.AuthenticateAsync();在API上进行身份验证,并将接收到的ClaimsPrincipal设置为httpContext.User。

让我们想象一下,我们总是可以从当前的access_token字典中获得新鲜的HttpContext.Items(因为它是从we​​bsocket消息中填充的)。

需要知道如何检测当前承载何时在API端过期并执行以下操作之一:

  • 还原当前HttpContext的“已认证”状态(如果可能)
  • 关闭websocket以强制客户端重新连接。

如果有新令牌,是否可以在旧令牌过期之前用新令牌替换旧令牌?

API具有三种身份验证方案。在我的情况下,它总是选择自省。

services.AddAuthentication(x =>
{
    x.DefaultScheme = ApiAuthenticationSchemes.DefaultScheme;
    x.DefaultAuthenticateScheme = ApiAuthenticationSchemes.DefaultScheme;
})
// Stub to not start process before protocol being upgraded to websocket
// as there is no bearer in header.
.AddJwtBearer(ApiAuthenticationSchemes.WebsocketScheme,default)
.AddJwtBearer(ApiAuthenticationSchemes.DefaultScheme,x =>
{
    // ...
    // Switching scheme by condition.
    // Three stages - stub before protocol upgraded,interceptor if there
    // is no dot in token (reference),current scheme,if there is
    // just regular access token.
    x.ForwardDefaultSelector = ApiAuthenticationSchemes.ForwardWebsocket();
    // ...
})
.AddOAuth2Introspection(ApiAuthenticationSchemes.IntrospectionScheme,x =>
{
    // ...
});

它使用了article中所述的“ ASP.NET Core中的灵活访问令牌验证”的原理。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...