Sync DiscourseConnect user data with the sync_sso route [JavaScript]

GregorSondermeier
Thu, 06 Apr 2023 14:21:51 +0000
Administrators

Hello,

for my company I needed to make use of this feature from our Node.js backend, so here is a reference implementation in JavaScript using Node.js’s cypto and Buffer if anyone is interested:

Note:
For consistency I’m using the same variable values as in the PHP implementation.

Setup your API credentials and SSO secret key

const apiKey = '4fe83002bb5fba8c9a61a65e5b4b0a3cf8233b0e4ccafc85ebd6607abab4651a';
const apiUser = 'system';
const connectSecret = 'jdhb19*Xh3!nu(#k';

Setup the sso parameters

const ssoRecord = new URLSearchParams({
  external_id: 1,
  email: 'bob@example.com',
  username: 'bob',
  add_groups: 'eurorack',
  require_activation: true,
}).toString();

const ssoPayload = Buffer.from(ssoRecord, 'utf8').toString('base64');
const signature = crypto.createHmac('sha256', connectSecret).update(ssoPayload).digest('hex');

Send the POST request

const updatedUser = await fetch({ // or axios
  method: 'POST',
  url: 'https://forum.example.com/admin/users/sync_sso',
  headers: {
    'Api-Key': apiKey,
    'Api-Username': apiUser,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    sso: ssoPayload,
    sig: signature,
  })
}).then((response) => response.json());

1 messaggio - 1 partecipante