User Authentication Procedure

User authentication is one of those things that is developed only occasionally but requires a lot of thought. Every time I am needing to set up user authentication from scratch I have to come up with my own procedure. I can never find something satisfactory that will work in my situation.

I have developed what I believe to be a very versatile user authentication procedure. This post lacks specific code implementation and is intended to provide insight into the procedure and not a specific implementation.


First of all, let’s discuss the database table structure that will be used to track tokens.

api_user_key {
 id (int): Unique record ID
 created_at (timestamp): Time the record was created
 user_id (int): User's ID from your user table
 app_id (varchar): ID randomly generated by the front-end application
 api_key (varchar): ID randomly generated by the back-end API

 UNIQUE KEY (user_id, app_id, api_key)
 UNIQUE KEY (api_key)

This table structure is very simple and allows a user to authenticated with multiple application instances simultaneously. For instance, the user can be logged in to the app on a FireFox browser, Chrome browser, and native mobile app all at the same time. Each of these logins would be managed separately and expire independently of one another. The “created_at” field can be used in a scheduled job to determine session timeouts.


  1. Generate app ID. This would be generated for each instance of a browse SPA (each time the page is loaded). For native apps it could be generated once per installation.
  2. Store app ID in cookie. This ID would then be stored in a cache on the client-side. For a browser this would be a cookie. For native apps it could be a configuration file. When the app is reloaded the ID will be retrieved from this cache.
  3. Get username and password from the user.
  4. Send username and password to the API.


  1. Validate username and password. This is done like a traditional username/password authentication. This authentication will be done only once per API key pair.
  2. Generate user API key.
  3. Store user ID, app ID, and user API key in the database.
  4. Send user API key to UI.


  1. Store the API key in a cache. This may not be the same cache that stores the app ID. An API key may be deleted at any time to invalidate the authentication. When this occurs the user will have to generate a new key using a username/password authentication. Timeout rules and what constitutes an application instance will be determined by the needs of your application.
  2. API key and app ID are sent in a header to API with each request. The UI will use this key pair for authentication instead of a username and password. At any time the API can delete the key pair to invalidate the authentication and require a username/password authentication.

Leave a Reply

Your email address will not be published. Required fields are marked *