If you working with web applications, it usually necessary to 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
# utils/secrets.py
#!/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.
# utils/secrets.py
#!/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.
# utils/secrets.py
#!/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!
Top comments (0)