Skip to content

Instantly share code, notes, and snippets.

@fspot
Last active December 6, 2018 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fspot/dd9ef22c247a97a5892d3d189fa3f46f to your computer and use it in GitHub Desktop.
Save fspot/dd9ef22c247a97a5892d3d189fa3f46f to your computer and use it in GitHub Desktop.

How to craft authenticated tokens ?

Say you want to create a token with limited rights, for example with only access to a specific small app "myapp", and with a limited view on the data, like if you had a group "mygroup" assigned (this mechanism requires to setup permissions).

And say you want this token to expire in 10 hours, for security reasons.

The python code for crafting the token (using pyjwt library) would be:

import jwt
from datetime import datetime, timedelta

secret_key = "HE6wKbD5Bskls7yCurI8Nk6"
issued_at = datetime.utcnow()
payload = {
    "username": "embed-user",
    "groups": [{"name": "mygroup"}],
    "roles": ["USER"],
    "privileges": {"smallApp": {"myapp": ["view"]}},
    "iat": issued_at,
    "exp": issued_at + timedelta(hours=10),
}
token = jwt.encode(payload, secret_key)

And the equivalent NodeJS code (using jsonwebtoken library):

var jwt = require('jsonwebtoken');

var secret_key = "HE6wKbD5Bskls7yCurI8Nk6";
var payload = {
    username: "embed-user",
    groups: [{name: "mygroup"}],
    roles: ["USER"],
    privileges: {smallApp: {myapp: ["view"]}}
};
var token = jwt.sign(payload, secret_key, {expiresIn: "10h"});

If you use another language on the platform which will be in charge of crafting the tokens, you can find an appropriate library here.

Security note

As you see, the jwt payload needs to follow a specific structure. Fields "username", "groups", "roles" and "privileges" are mandatory, and must strictly follow the examples put above. Badly structured jwt may result in a user seeing more things than he should.

How can I know the secret_key ?

This key is specific to your instance, and was setup during installation. If your instance is on our cloud, we can share this key with you. Keep in mind that this is sensitive data which can be used to generate all kind of accesses to your instance.

How to use the token ?

To use this token, simply append it to your Toucan Toco's app URL (e.g: https://yourinstance.toucantoco.com/?token=YOURTOKEN)

You can then use this URL in HTML elements like links or iframes so they will be automatically authenticated with the appropriate rights.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment