JSON API » Authentication tokens

JSON API authentication is normally by username and password using the "auth_username" and "auth_password" parameters. As an alternative, authentication tokens may be used. These improve performance by having the client store the authentication information. This information is encrypted as a JSON Web Token (JWT) to prevent API users from tampering with it. The encryption key is automatically generated by Enswitch, global to the Enswitch installation, and stored in the Enswitch database.

To use authentication tokens in your code

  • Call the user/login function (or user/switch function if you wish to switch user), passing token=1 as a parameter.
  • The returned data will include extra fields. These are:
    • "auth_token", which contains the JWT token.
    • "auth_token_expiry", which is the number of seconds until the token expires. Use this to keep track of the expiry time, and call user/login again when the token is about to expire. Allow a few seconds leeway for rounding and clock skew.
    • "auth_token_expires", which contains the Unix timestamp at which the token expires. Use this as an alternative to auth_token_expiry, but only if you're confident that the clock on the client machine is the same as on the Enswitch server. This field is not returned if tokens do not expire (see below).
  • In subsequent calls to the JSON API, you can pass an "auth_token" parameter containing the token instead of auth_username and auth_password. This is faster and puts less load on the database as the user is not authenticated again.
  • If an API call with auth_token fails with a 401 error, it is because the token has expired or is corrupt. If this happens, call user/login again with token=1 to get a new token. If that also fails with a 401 error, then the username and password provided are invalid and your code should return an error.

Expiry time

The expiry time is controlled by the "Authentication token expiry" configuration setting. The value of this setting is returned in the auth_token_expiry field. If this is set to zero, tokens never expire, and the auth_token_expires return field is not included. Setting tokens to never expire is not recommended.

Changes to the user

When using a token, the provided authentication is not re-checked against the database for each API call. This means that any changes to the user are not reflected in the token. If a person is deleted, or their password changed, or their role changed, any tokens active for them will continue to work with their old settings until the tokens expire. If calling people/update for the person you're logged in as, it's a good idea to immediately get a new token with the new person settings.