Authenticating Users as Contexts
Getting tokens for your users to access Xkit
In order for Xkit to be able to manage the authorization process with 3rd party apps (e.g. the OAuth process), we need to know who the user is and that they have been authorized by you to create connections.
We do this through Xkit Context Tokens, tokens that you create that authenticate the user with Xkit in a particular context, our term for any grouping that is meaningful to your app as a way to organize user connections.
For example, if your app requires that each user have their own connection to an app, the context would be an individual user. If, on the other hand, your app requires that there is one connection to an app that is shared by an entire company, the context would be the company.
You create a Context (and an accompanying token) by calling the Create Context API with an active API Key.
The only data you need to provide is an external_id
- an identifier that uniquely identifies the context in your systems. For example, if the context is a user, this would be a User ID, or if it's a company, it would be the Company ID.
You can optionally provide an external_name
, a friendly name for you and your staff to recognize the context, like a Company name or a user's email address. You can also provide custom attributes - they will be saved and returned back with the context.
A simple example using Node.js with an ExpressJS server follows, but it should be similar in any language.
Create a context
When your authenticated user needs to access Xkit on the front-end (e.g. to create a connection to a 3rd party service), call the Create Context endpoint to create (or update) a context and retrieve a Context Token to identify the user to Xkit.
import axios from 'axios'
const XKIT_PUBLISHABLE_KEY = process.env.XKIT_PUBLISHABLE_KEY
const XKIT_SECRET_KEY = process.env.XKIT_SECRET_KEY
app.post('/xkit-token', async (req, res) => {
if (!req.user) {
throw new Error('No user is logged in')
}
const { access_token } = await axios({
baseUrl: 'https://app.xkit.co/api/platform',
method: 'post',
url: '/context',
auth: {
username: XKIT_PUBLISHABLE_KEY,
password: XKIT_SECRET_KEY
},
data: {
// Using the current user as the context
context: {
external_id: req.user.id,
// Optional friendly name
external_name: req.user.name,
// Optional extra attributes
email: req.user.email
}
}
})
res.json({ token: access_token })
})
Authenticate with Xkit
Once your front-end has the Xkit Context Token, you can authenticate using xkit.js.
import axios from 'axios'
import createXkit from '@xkit-co/xkit.js'
const xkit = createXkit('<your-slug>.xkit.co')
xkit.login(async () => {
const { token } = await axios({
method: 'post',
url: '/xkit-token'
})
return token
})
Updated over 2 years ago