Implementing User Auth with API Key

How to Implement User Auth with API Key#

Rollout can also authenticate users within your app using an API Key, which can be supplied in the JWT while embedding rollout. Unlike with the oauth authentication method, the user won't see a popup when authenticating with this method. It can then be appended to all future HTTP requests made to your app to authenticate that user. We also support making the API key refreshable, which is explained further below.

Setup API Key to be sent in JWT Auth#

Go to the User Auth page in the Rollout dashboard and select the API Key option. Make sure that your are returning the API key in the authData when passing the JWT claim. See the example below and see Rollout Auth JWT for more information on setting up JWT's.

const TOKEN_TTL_SECS = 3600;
function generateRolloutConnectToken(userId) {
const nowSecs = Math.round(new Date() / 1000);
return jsonwebtoken.sign(
{
iss: process.env.ROLLOUT_CLIENT_ID, // Provided in the Rollout dashboard
sub: userId, // Persistent identifier for the consuming user. Must be a string
exp: nowSecs + TOKEN_TTL_SECS, // Token expiration,
"rollouthq.com": {
authData: { apiKey: "[API_KEY_FOR_THIS_END_USER]" },
},
},
process.env.ROLLOUT_CLIENT_SECRET, // Provided in the Rollout dashboard
{ algorithm: "HS512" }
);
}

Use API Key in requests#

You can now use the {{context.authData.apiKey}} variable in an action or any other API request in the dashboard. We strongly recommend validation of Rollout requests via the verification token found on the Configuration page of the Dashboard.

Refreshable token authentication#

We also support refreshing the apiKey by utilizing a refreshToken and expiresIn.

In order to supply a refreshable token, pass the data in the rollouthq.com field of the JWT, with the authData type.

authData#

type authData = {
apiKey: string; //a key your server generates to authenticate
refreshToken: string; //a token used to refresh the apiKey
expiresIn: number; //the number of seconds the apiKey is valid
};

JWT with authData#

{
iss: customer.clientId,
iat: nowSecs,
exp: nowSecs + 3600,
"rollouthq.com": {
authData: {
apiKey: "[TOKEN]",
refreshToken: "[REFRESH_TOKEN]",
expiresIn: 20000
},
}
customer.clientSecret,
{ algorithm: "HS512" }
}

Refreshing apiKey#

On the authentication dashboard, you must also specify the API request to refresh the key. You can specify the URL endpoint we will supply along with any data needed for the request.

The endpoint should return the authData as described above.

app.post("/[URL_ON_YOUR_SEVER]", (req, res) => {
// some logic
res.json({
apiKey: "[new api key]",
refreshToken: "[new refresh token]",
expiresIn: 20000, // some number of seconds
});
});