0

I build a Django site wheres requires all users to be authenticated using the standard authentication of Django. In some of the pages django will be doing Request to a third party site which also require authentication.

This third party site is not a django site and only has one user, this means that all django users will be sharing that 1 user to retrieve the information.

The authentication to this third party site, is with a JWT Flow. We first retrieve an auth token and then we send this token to the desire end point adding the Django user ID, to retrieve that user ID information.

I want to avoid all users in django doing multiple request to get the same auth token as this should be the same for all of them.

Is there a way in Django to storage this auth Token safely? and perhaps if a user fail due to expiry token, django retrieves a new one and keep it safely store for all users to use?

Manza
  • 2,109
  • 1
  • 27
  • 34
  • you could you an in-memory cache backend for this, this way each django process would only retrieve the JWT once. – DevLounge Mar 27 '21 at 23:01

2 Answers2

2

In the code which needs access to this 3rd party site token do something like:

remote_token = cache.get_or_set('remote-token', get_remote_token)

get_or_set can take a callable (function) which will be executed only if the cache is not populated yet.

More info here

DevLounge
  • 8,313
  • 3
  • 31
  • 44
  • In case anyone, use this, we need to add into the page: from django.core.cache import cache – Manza Mar 29 '21 at 01:43
  • is it normal that my pages and code is been cache? I want to use the cache to save the auth token value and another value. But I am having the issue now that my pages keep the cache, I use 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', and the only way to clear is by deleting the records from the table – Manza Mar 29 '21 at 02:20
  • Sorry I just found the issue, I had to remove the following from MIddleware to void caching the whole site, 'django.middleware.cache.UpdateCacheMiddleware' and 'django.middleware.cache.FetchFromCacheMiddleware' – Manza Mar 29 '21 at 05:25
0

You can store your token in environment variables. It's safety and multiple request of this var isn't problem, because default django is synchronous. So just store it in .env file and extract it with python_decouple package

Degrijo
  • 15
  • 3