我正在使用.net core 1.1和identityserver 4来获取 token 并验证用户。 Web API 可以很好地从 header 中读取不记名 token 并获取用户主体声明。
现在我想使用 websocket(不是 SignalR)来发送通知。我可以打开 ws:// channel (或 wss),但 token 不随 header 一起发送,因此在 .net core 应用程序中我没有用户的信息(用户声明和身份)。
如何通过 websocket 验证用户身份?我进行了搜索,但找不到任何有用的信息。
谢谢
最佳答案
WebSocket 中间件中与身份验证相关的主要问题有两个:
应手动调用授权
首先,授权不适用于Web套接字请求(因为它不是可以标记Authorize属性的 Controller )。
这就是为什么在WebSocket中间件中你需要自己调用授权。通过调用 HttpContext
对象的 AuthenticateAsync
扩展方法可以轻松实现这一点。
因此,您的中间件将如下所示:
public class WebSocketMiddleware
{
private readonly RequestDelegate next;
public WebSocketMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
if (!context.WebSockets.IsWebSocketRequest)
{
await this.next.Invoke(context);
return;
}
AuthenticateResult authenticateResult =
await context.AuthenticateAsync(OAuthValidationDefaults.AuthenticationScheme);
....
});
}
因此,使用身份验证结果,您可以检查用户是否通过身份验证,然后访问经过身份验证的用户信息。
将不记名 token 传递给网络套接字请求
对于 Web Socket 连接,默认的 Authorization header 不起作用,因为 WebSockets JS API 不允许设置自定义参数。为了解决此限制,访问 token 经常在查询字符串中传递。
要使身份验证中间件使用它,您需要更新身份验证验证选项。这基本上可以在启动脚本中完成,如下所示:
services
.AddAuthentication()
.AddOAuthValidation(options =>
{
options.Events = new OAuthValidationEvents
{
// Note: for Web Socket connections, the default Authorization header does not work,
// because the WebSockets JS API doesn't allow setting custom parameters.
// To work around this limitation, the access token is retrieved from the query string.
OnRetrieveToken = context =>
{
context.Token = context.Request.Query["access_token"];
return Task.FromResult(0);
}
};
});
以下代码可以作为示例,在连接初始化期间向 Web 套接字 url 添加访问 token :
const protocol = location.protocol === "https:" ? "wss:" : "ws:";
const wsUri = protocol + "//" + window.location.host + "/ws" + "?access_token=" + token;
this.socket = new WebSocket(wsUri);
关于Websocket 和 Identityserver4 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43135765/