如何验证客户端和服务器位于单独域中的websocket连接? [英] How can I authenticate a websocket connection where client and server reside on seperate domains?

查看:129
本文介绍了如何验证客户端和服务器位于单独域中的websocket连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用SignalR和websocket.从我的研究看来,由于websocket不支持自定义标头,因此在基于令牌的身份验证期间,基本上只有两种方法可以对websocket连接进行身份验证.

I'm currently playing around with SignalR and websockets. From my research, it seems, as websockets do not support custom headers, there's basically only two ways to authenticate a websocket connection during token based authentication.

1)在查询字符串中传递令牌 2)将令牌存储在cookie中,然后在WithCredentials设置为true时传递给服务器

1) Passing the token in the query string 2) Storing the token in a cookie which then gets passed to the server when WithCredentials is set to true

第一种方法不是一个好习惯-即使通过websocket通信进行加密,查询字符串也可能由服务器等记录.

The first method isn't great practice - even through websocket communication is encrypted, query strings may be logged by servers etc.

我已经在本地计算机上工作的第二种方法,但是一旦部署就无法使用,因为我的客户端和服务器位于不同的域中.因此,基本上,我有一个具有一个域的Angular站点(例如client.com)和一个将CORS与一个完全不同的域结合在一起的WebAPI站点(例如server.com).在我的浏览器上,如果我在client.com上,则无法设置一个cookie,该cookie会根据请求发送到server.com.

The second method I have got working on my local machine but it doesn't work once deployed because my client and server reside on different domains. So basically, I have an Angular site that has one domain (eg. client.com) and a WebAPI site that alls CORS with a completely different domain (eg. server.com). On my browser, if I'm on client.com, I cannot set a cookie that gets sent to server.com on a request.

当客户端和服务器位于不同的域上时,对Websocket进行身份验证的好方法是什么?

What is a good way to authenticate websockets when client and server sit on different domains?

推荐答案

WebSocket协议规范未指定身份验证的任何特定方式.您需要在握手阶段执行身份验证,为此,您可以使用任何HTTP身份验证机制,例如Basic,Digest等.

The WebSocket Protocol specification doesn't specify any particular way for authentication. You need to perform the authentication during the handshake phase and for that you can use any HTTP authentication mechanism like Basic, Digest, etc.

进一步,您可以研究基于JWT令牌的身份验证. Angular应用程序可以将令牌存储在本地存储和在握手请求期间将其作为传输头发送给服务器.如果令牌无效,则服务器可以终止WebSocket连接升级请求,并且Angular应用可以将用户重定向到登录页面.

Further you could look into JWT token based authentication. Angular app can store the token in local storage and send it as a Transport header during the handshake request to the server. If the token is invalid, server can terminate the WebSocket connection upgrade request and the Angular app can re-direct the user to login page.

这篇关于如何验证客户端和服务器位于单独域中的websocket连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆