Sample Header Ad - 728x90

How to efficiently combine user authentication with token authentication?

0 votes
1 answer
311 views
What is the most efficient approach of authentication, considering an user based authentication system combined with a token based authentication system? For this question please consider the following tables:
create table users (
  id int generated always as identity primary key,
  username text not null unique,
  password text not null
);

create table tokens (
  id int generated always as identity primary key,
  user_id int not null references users(id),
  access_token text unique default generate_random_token(),
  refresh_token text default generate_random_token(),
  updated_on timestamp with time zone default current_timestamp,
  created_on timestamp with time zone default current_timestamp
);
As far as I know to create an user and allow it to authenticate the following steps are mandatory (explained with query statements): 1. Optional: Create an user record.
insert into users (username, password) values ('foo', create_password_hash('bar'));
2. Check if the user can authenticate itself and remember the user's ID:
select * from users where username = 'foo' and password = validate_password_hash('bar', password);
3. Check if the user has an existing token and hand over the access_token:
select access_token from tokens where user_id = 123;
4. Optional: Create a token if the user doesn't have one yet:
insert into tokens (user_id) values (123) returning access_token;
If my assumption for the steps to be taken is right, then I wonder how to minimize these four statements into a single one or have at least some guidance how this could be done more efficient. Also I could imagine that my approach for this use case incorrect and that there is an other more efficient approach, please let me know. --- **BONUS** Perhaps your approach could also cover the process of refreshing a token. Considering the approach explained above the refresh should only occur when a token is found at the third step and according to the updated_on timestamp the token is "expired".
Asked by luukvhoudt (111 rep)
Jul 22, 2020, 09:16 AM
Last activity: May 2, 2025, 09:01 PM