简体   繁体   中英

How to handle JWT authentication with RxDB?

I have a local RxDB database and I want to connect it with CouchDB. Everything seems to works fine except for authentication. I have no idea how to add it differently then inserting credentials in database url:

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

I would like to use JWT auth but can't find how to add a token to sync request. I found only some solutions for PouchDB (pouchdb-authentication plugin) but can't get it working with RxDB.

RxDB is tightly coupled with PouchDB and uses its sync implementation under the hood. To my understanding, the only way to add custom headers to a remote PouchDB instance (which is what is created for you when you pass a url as the remote argument in sync ), is to 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) also states that:

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.

Luckily, RxDB's Rx.Collection.sync does not only accept an server url as the remote argument, but also another RxCollection or a PouchDB-instance.

RxDB even reexport the internally used PouchDB module, so you do not have to install PouchDB as a direct dependency.

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,
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM