Auth using Auth token
What is it?
This integration allows to set up a completely seamless signup and login flow between an external system and publica.la.
To accomplish this in a secure way, it uses a JWT. JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. You can learn more in these sites:
The integration works synchronously, for example with the press of a button by the user. It does not work asynchronously, like a regular REST API.
The system has a route /auth/token
that looks for a parameter named external-auth-token
on query strings, cookies or headers. This parameter is the JWT, with specific information and signed with a shared key (The algorithm is HS256).
For example: https://yout-store.com/auth/token?external-auth-token={new-jwt-token}
Pre-requisites
Contact us at [email protected] to send the following data:
- redirect_url: URL for redirection in case of failure in the process of Login or Registration
- key: Used during the creation of the token. It's a shared key used to sign the tokens. We recommend to use a UUID, you may generate one in the following link
- issuer: Identifies the trusted signer of the token. It is used in the payload data of the token.
How to configure it?
Create a JWT token:
Key | Description |
---|---|
iss | Slug to identify who signs the token. You must use the issuer provided in the previous step |
jti | A unique id for the token, could be in UUID V4 format. |
exp | Expiry date of the token, it’s a timestamp expressed in seconds. It must be 60 seconds in the future. The time zone used is UTC. |
aud | Identifies the token destinataire. It must be the string farfalla. |
sub | It must be the string user |
intended_url | Allows you to configure the destination URL after authenticating the user. Take the following considerations into account:
|
user | An object with the following fields:
|
reader_exit_url | This value allows you to configure the behavior for redirecting the user when they choose to exit the reader. This is useful for customizing a unique exit experience that reflects the integrator's identity. |
Example
{
"iss": "publicala", // Slug to identify who signs the token. You must use the issuer provided in the prerequisites step.
"jti": "jnosqixu-waibsvsz8x89wgyxtfdy4x6r", // A unique id for the token, could be in UUID V4 format.
"exp": 1614556800, // Expiry date of the token, it’s a timestamp expressed in seconds. It must be 60 seconds in the future. The time zone used is UTC. https://www.unixtimestamp.com/
"aud": "farfalla", // Identifies the token destinataire. It must be the string farfalla
"sub": "user", // It must be the string user always.
"intended_url": "https://your-store.com/reader/publication-name" // Allows you to configure the destination URL after authenticating the user. You can check how configure this in How use intended url section.
"user": {
"uuid": "44b8cc41-503c-4e76-9144-7193af85384e", // [required ] It is a required string and is used to identify each user. It is essential that it is unique for each user, it could be the user id casted to string (eg 1234) or a UUID (eg eeb78e86-8105-443d-bd28-b2eee1607d52).
"email": "[email protected]", // [optional] Used to identify users within the system and when analyzing usage stats.
"picture_url": "https://image-picture-domain.com/picture.jpg" // [optional] If present it is used as a profile picture.
"accept_terms_and_policies": true // [optional] If present, it is used to automatically accept terms a conditions when the user is created.
},
"reader_exit_url": "https://your-store.com/custom_exit_url/", // URL where the user will be redirected once they leave the reader.
}
The following code may be used as example to create JWT tokens.
- PHP
- Python
- JavaScript
<?php
use Lcobucci\JWT\Builder;
use Ramsey\Uuid\Uuid;
use Lcobucci\JWT\Signer\Hmac\Sha256;
$tokenSecret = 'ee9a9f38-81b0-40de-8919-23f6ef75ea0d';
$userUuid = 'f1853db8-a9e5-4a38-b1cd-540a7e74d4b8';
$userEmail = '[email protected]';
$userPictureUrl = 'https://storage.com/userpci.jpg';
$userAcceptTermsAndPolicies = true;
$token = (new Builder())
->setIssuer('naciondigital')
->setAudience('farfalla')
->setId(Uuid::uuid4(), true)
->setIssuedAt(time())
->setExpiration(time() + 3600)
->set('sub', 'user')
->set('user', [
'uuid' => $userUuid,
'email' => $userEmail,
'picture_url' => $userPictureUrl,
'accept_terms_and_policies' => $userAcceptTermsAndPolicies,
])
->sign(new Sha256(), $tokenSecret)
->getToken();
$tokenString = (string) $token;
# Example token generation inside a Django view or context processor (note the request parameter used)
import jwt
from time import time
from uuid import uuid4
from django.conf import settings
encoded_token = jwt.encode({
'iss': 'naciondigital', 'jti': uuid4().hex, 'exp': int(time()) + 60,
'aud': 'farfalla', 'sub': 'user', 'user': {
'uuid': str(request.user.id), 'email': request.user.email, accept_terms_and_policies: request.user.accept_terms_and_policies}
}, settings.JWT_SECRET, algorithm='HS256')
// Example token generation and redirection inside an Express route
const jwt = require('jsonwebtoken');
const uuidv4 = require('uuid/v4');
const libraryUrl = 'https://biblioteca.naciondigital.com';
const tokenSecret = 'ee9a9f38-81b0-40de-8919-23f6ef75ea0d';
router.get('/go-to-library', async (req, res) => {
try {
const token = jwt.sign(
{
iss: 'naciondigital',
jti: uuidv4(),
aud: 'farfalla',
sub: 'user',
user: { uuid: req.query.uuid },
},
tokenSecret,
{ algorithm: 'HS256' }
);
res.redirect(`${libraryUrl}/auth/token?external-auth-token=${token}`);
} catch (error) {
console.log('Error trying to generate token', {
error: error,
request: req,
});
res.status(500).send('error');
}
});
Troubleshooting
Any problem with the token or the user will return an error code contained in the redirection URL under the parameter external-auth-token-error
.
There are two possible error cases:
invalid-token
: A problem with the token itself. It adds a parameter calledexternal-auth-token-details
that includes a JSON object encoded in Base64 with the error’s details.
For example: https://your-library-url.com?external-auth-token-error=invalid-token&external-auth-token-error-details=eyJ0b2tlbiI6eyJleHAiOiJUb2tlbiBlcyBleHBpcmVkIG9yIGBleHBgIGF0dHJpYnV0ZSBub3QgcHJlc2VudC4ifX0=
And decoding the string we can see this error message:
{
"token": {
"exp": "Token es expired or `exp` attribute not present."
}
}
invalid-user
: A problem with the user included in the token. It adds a parameter calledexternal-auth-token-details
that includes a JSON object encoded in Base64 with the error’s details.
For example, here we have an error with the email field inside the object user: https://your-library-url.com?external-auth-token-error=invalid-user&external-auth-token-error-details=eyJlbWFpbCI6WyJUaGUgZW1haWwgbXVzdCBiZSBhIHZhbGlkIGVtYWlsIGFkZHJlc3MuIl19.
And decoding the string we can see this error message:
{
"email": [
"The email must be a valid email address."
]
}
tip
Tips:
- When sending the token in the query string you do not need to URL encode it, as a JWT already is URL safe.
- If you don't include the
email
in the token, then the integration is 100% anonymous. - There are many online tools that can help you work with Base64 strings. For example, this is a good one: https://www.base64decode.org/