How to Create Secret Tokens in Python
Generate Secrets (3 Part Series)
If you working with web applications, it usually necessary to generate tokens, API keys, personal keys etc.
We assign them to clients to use as authentication.
We already saw how to create secrets. However using that method could cause problem sometimes like if we use them in url.
Python’s built-in secrets module provides functions for generating secure tokens, suitable for methods such as password resets, hard-to-guess URLs, and similar.
Generating Tokens
Bytes
Return a random byte string containing nbytes number of bytes
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import string
import secrets
def generate_token_bytes(length: int = 32):
return secrets.token_bytes(length)
In [2]: generate_token_bytes()
Out[2]: b'\x8a\xb7\x19\xd8\x8f\x94\x16\x15\xedg\xc1\x833\xd4\xb9\xfe\xd8\xa7\xc5\xa17d\xd7k\xe5\x14\xea\xe4\x7fz\x0f}'
Hex
Return a random text string, in hexadecimal.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import string
import secrets
def generate_token_bytes(length: int = 32):
return secrets.token_bytes(length)
In [3]: generate_token_hex()
Out[3]: 'b9165728eb46a36db8389c902c20bd7bd7a8430be398f47818323b0d15b46600'
URL Safe
Return a random URL-safe text string, containing nbytes random bytes.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import string
import secrets
def generate_token_urlsafe(length: int = 32):
return secrets.token_urlsafe(length)
In [5]: generate_token_urlsafe()
Out[5]: 'uNuz07y8mkmwvHftrszV_SFffh9LT25L98UZO0w_LHA'
urlsafe
is very useful when you want to use password reset:
http://tech.serhatteker.com/accounts/reset/MQ/uNuz07y8mkmwvHftrszV_SFffh9LT25L98UZO0w_LHA/
or using it as a password:
# redis://user:pass@instance:port/db
redis://redis-user:uNuz07y8mkmwvHftrszV_SFffh9LT25L98UZO0w_LHA@redis_instance_url:6379/0
All done!
Subscribe
Read Related
How to Create Secrets in Python
#secret #python #securityHow to create secrets; passwords, database credentials, secret keys etc. in python
How to Create SECRET_KEY for Django Settings
#secret #django #python #securityWhen you start a django project, django-admin startproject automatically adds a randomly-generated SECRET_KEY to each new project.
However if you want to change it, or add a seperate one to each of your environment, e.g: one for ‘production’, one for ‘staging’, one for ‘production’ etc, how do you gerenerate a new ones?
There would be another case: you cloned a project from a remote repo and want to change the default SECRET_KEY.
Testing created/updated/auto_now fields in Django
#python #django #unittest #mockTesing created_at, updated_at, modified_at fields with auto_now and auto_now_add in Django