我正在尝试使用 typescript servicestack-client从 ServiceStack 服务器 Hook SSE 事件。
通过发送 Authenticate
类并接收 session cookie 进行身份验证:
import { ServerEventsClient } from 'servicestack-client';
export class ServicestackService {
private sseClient: ServerEventsClient;
constructor() {
this.createSseClient();
}
login(username: string, password: string) {
let request = new Authenticate(username, password);
return this.sseClient.serviceClient.post(request);
}
startClient() {
this.sseClient.start();
console.log('eventSource created');
}
subscribeChannel(channel: string) {
this.sseClient.subscribeToChannels(channel);
}
private createSseClient() {
this.sseClient = new ServerEventsClient('http://ss_api_url', ['*'], {
handlers: { ...define handlers for onConnect & onMessage here... }
}
}
}
上面的代码成功地再次验证了 servicestack API,并且安全的 API 请求运行良好。
startClient()
方法在所有登录身份验证完成后调用,并创建 eventSource
对象作为 this.sseClient
中的属性。
但是这个对象有 withCredentials: false
!
因此,以下任何 channel 订阅都因未通过身份验证而失败,因为 servicestack 客户端未发送 Cookies
header 。
如何实现经过身份验证的 SSE 连接?
最佳答案
我刚刚在 this commit 中添加了对指定 withCredentials
EventSource 选项的支持默认为 true
,因此如果您升级到 servicestack-client 的最新 v0.0.34,它将自动启用.
如果需要,可以通过以下方式禁用它:
var sseClient = new ServerEventsClient('http://ss_api_url', ['*'], { ... });
sseClient.withCredentials = false;
关于authentication - SSE 事件的 Typescript Servicestack 客户端身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43719968/