gpt4 book ai didi

authentication - 如何使用 RxDB 处理 JWT 身份验证?

转载 作者:行者123 更新时间:2023-12-05 02:53:37 24 4
gpt4 key购买 nike

我有一个本地 RxDB 数据库,我想将它与 CouchDB 连接。除了身份验证之外,一切似乎都正常。我不知道如何以不同的方式添加它然后在数据库 url 中插入凭据:

database.tasks.sync({
remote: `http://${username}:${pass}@127.0.0.1:5984/tododb`,
});

我想使用 JWT 身份验证,但找不到如何将 token 添加到同步请求。我只找到了 PouchDB(pouchdb 身份验证插件)的一些解决方案,但无法让它与 RxDB 一起工作。

最佳答案

RxDB 与 PouchDB 紧密耦合,并在底层使用其同步实现。据我了解,将自定义 header 添加到远程 PouchDB 实例的唯一方法(这是当您将 url 作为 sync 中的 remote 参数传递时为您创建的) , 是 intercept the HTTP request :

var db = new PouchDB('http://example.com/dbname', {
fetch: function (url, opts) {
opts.headers.set('X-Some-Special-Header', 'foo');
return PouchDB.fetch(url, opts);
}
});

PouchDB replication documentation (sync) 还指出:

The remoteDB can either be a string or a PouchDB object. If you have a fetch override on a remote database, you will want to use PouchDB objects instead of strings, so that the options are used.

幸运的是,RxDB 的 Rx.Collection.sync 不仅接受服务器 url 作为 remote 参数,而且还接受另一个 RxCollection 或 PouchDB 实例。

RxDB 甚至重新导出了内部使用的 PouchDB 模块,因此您不必将 PouchDB 作为直接依赖安装。

import { ..., PouchDB } from 'rxdb';

// ...


const remotePouch = new PouchDB('http://27.0.0.1:5984/tododb', {
fetch: function (url, opts) {
opts.headers.set('Authorization', `Bearer ${getYourJWTToken()}`)
return PouchDB.fetch(url, opts);
}
})

database.tasks.sync({
remote: remotePouch,
});

关于authentication - 如何使用 RxDB 处理 JWT 身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62129654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com