User Tokens

User tokens are secure keys which are generated when a user logs in. By using a token as the value for the Authorization header in a view-based request, you can make secure, cross-origin requests as a logged-in user without exposing an API key.

Because the token identifies the specific user who retrieved it by logging in, token-authenticated requests behave just like a user's visit to your live Knack app; the authenticated user can only make requests to views to which he/she has access, and any forms whose record rules track the logged-in user will identify the user by this token. Similarly, requests to views which display records connected to the logged-in user will only return those same records.

If the 'Remember Me' box is checked upon login, tokens are valid for two weeks after which they are replaced with new ones when the user logs in again. Otherwise, a user's token is good for 48 hours after login.

After the user logs in, his/her token is accessible by calling Knack.getUserToken() - in your app's custom JavaScript - which returns the token as a string:

Knack.getUserToken();
//"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTU0N2VhNjVkMmE3MzgxNDA5MjU3YWQzIiwiYXBwbGljYXRpb25faWQiOiI1MzllNjYzYjZlNTNlY2M1NjAwMDBiNzkiLCJpYXQiOjE0MzA3NzY0NDF9.g7C3iJexG3Na2dt6m_vumheXLUe1H_4NEYKziH9Gtm8"

📘

Note: You may notice that this header is not prefixed by “X-Knack-”. That’s because the authorization header for use in a token-based authentication systems is an industry-standard approach as defined by this Internet Engineering Task Force proposal.

See below for an example of using jQuery in a Knack app to determine a user’s token and then to make an API call using it. Note that there is no API key included in the headers.

// change "scene_1" to the scene you want to listen for
$(document).on('knack-scene-render.scene_1', function(event, scene) {
  // change scene_1 and view_1 to the view that works with the logged-in user
  $.ajax({
    url: 'https://api.knack.com/v1/pages/scene_1/views/view_1/records',
    type: 'GET',
    headers: {
      'Authorization': Knack.getUserToken(),
      'X-Knack-Application-Id': Knack.application_id,
      'Content-Type': 'application/json'
    },
    success: function(data) {
      alert('Got records!')
      console.log(data);
    }
  });
});

What’s Next