Skip to content

Commit b7ccf4d

Browse files
committed
added pwdlib support with argon2, instead of passlib
1 parent ed48cc4 commit b7ccf4d

3 files changed

Lines changed: 24 additions & 24 deletions

File tree

docs/en/docs/tutorial/security/oauth2-jwt.md

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -64,20 +64,20 @@ If your database is stolen, the thief won't have your users' plaintext passwords
6464

6565
So, the thief won't be able to try to use that password in another system (as many users use the same password everywhere, this would be dangerous).
6666

67-
## Install `passlib`
67+
## Install `pwdlib`
6868

69-
PassLib is a great Python package to handle password hashes.
69+
pwdlib is a great Python package to handle password hashes.
7070

7171
It supports many secure hashing algorithms and utilities to work with them.
7272

73-
The recommended algorithm is "Bcrypt".
73+
The recommended algorithm is "Argon2".
7474

75-
Make sure you create a [virtual environment](../../virtual-environments.md){.internal-link target=_blank}, activate it, and then install PassLib with Bcrypt:
75+
Make sure you create a [virtual environment](../../virtual-environments.md){.internal-link target=_blank}, activate it, and then install pwdlib with Argon2:
7676

7777
<div class="termy">
7878

7979
```console
80-
$ pip install "passlib[bcrypt]"
80+
$ pip install "pwdlib[argon2]"
8181

8282
---> 100%
8383
```
@@ -86,7 +86,7 @@ $ pip install "passlib[bcrypt]"
8686

8787
/// tip
8888

89-
With `passlib`, you could even configure it to be able to read passwords created by **Django**, a **Flask** security plug-in or many others.
89+
With `pwdlib`, you could even configure it to be able to read passwords created by **Django**, a **Flask** security plug-in or many others.
9090

9191
So, you would be able to, for example, share the same data from a Django application in a database with a FastAPI application. Or gradually migrate a Django application using the same database.
9292

@@ -96,15 +96,15 @@ And your users would be able to login from your Django app or from your **FastAP
9696

9797
## Hash and verify the passwords
9898

99-
Import the tools we need from `passlib`.
99+
Import the tools we need from `pwdlib`.
100100

101-
Create a PassLib "context". This is what will be used to hash and verify passwords.
101+
Create a PasswordHash instance with recommended settings — it will be used for hashing and verifying passwords.
102102

103103
/// tip
104104

105-
The PassLib context also has functionality to use different hashing algorithms, including deprecated old ones only to allow verifying them, etc.
105+
pwdlib also supports the bcrypt hashing algorithm but does not include legacy algorithms — for working with outdated hashes, it is recommended to use the passlib library.
106106

107-
For example, you could use it to read and verify passwords generated by another system (like Django) but hash any new passwords with a different algorithm like Bcrypt.
107+
For example, you could use it to read and verify passwords generated by another system (like Django) but hash any new passwords with a different algorithm like Argon2 or Bcrypt.
108108

109109
And be compatible with all of them at the same time.
110110

docs/ru/docs/tutorial/security/oauth2-jwt.md

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -62,28 +62,28 @@ $ pip install pyjwt
6262

6363
Таким образом, вор не сможет использовать этот пароль в другой системе (поскольку многие пользователи везде используют один и тот же пароль, это было бы опасно).
6464

65-
## Установка `passlib`
65+
## Установка `pwdlib`
6666

67-
PassLib - это отличный пакет Python для работы с хэшами паролей.
67+
pwdlib - это отличный пакет Python для работы с хэшами паролей, пришедший на замену passlib.
6868

6969
Он поддерживает множество безопасных алгоритмов хеширования и утилит для работы с ними.
7070

71-
Рекомендуемый алгоритм - "Bcrypt".
71+
Рекомендуемый алгоритм - "Argon2".
7272

73-
Убедитесь, что вы создали и активировали виртуальное окружение, и затем установите PassLib вместе с Bcrypt:
73+
Убедитесь, что вы создали и активировали виртуальное окружение, и затем установите pwdlib вместе с Argon2:
7474

7575
<div class="termy">
7676

7777
```console
78-
$ pip install "passlib[bcrypt]"
78+
$ pip install "pwdlib[argon2]"
7979

8080
---> 100%
8181
```
8282

8383
</div>
8484

8585
/// tip | Подсказка
86-
С помощью `passlib` можно даже настроить его на чтение паролей, созданных **Django**, плагином безопасности **Flask** или многими другими библиотеками.
86+
С помощью `pwdlib` можно даже настроить его на чтение паролей, созданных **Django**, плагином безопасности **Flask** или многими другими библиотеками.
8787

8888
Таким образом, вы сможете, например, совместно использовать одни и те же данные из приложения Django в базе данных с приложением FastAPI. Или постепенно мигрировать Django-приложение, используя ту же базу данных.
8989

@@ -92,14 +92,14 @@ $ pip install "passlib[bcrypt]"
9292

9393
## Хеширование и проверка паролей
9494

95-
Импортируйте необходимые инструменты из `passlib`.
95+
Импортируйте необходимые инструменты из `pwdlib`.
9696

97-
Создайте "контекст" PassLib. Именно он будет использоваться для хэширования и проверки паролей.
97+
Создайте экземпляр `PasswordHash` с рекомендованными настройками — он будет использоваться для хэширования и проверки паролей.
9898

9999
/// tip | Подсказка
100-
Контекст PassLib также имеет функциональность для использования различных алгоритмов хеширования, в том числе и устаревших, только для возможности их проверки и т.д.
100+
pwdlib также имеет функциональность для использования алгоритма хэширования bcrypt, но не поддерживает старые алгоритмы — для работы с устаревшими хэшами рекомендуется использовать библиотеку passlib.
101101

102-
Например, вы можете использовать его для чтения и проверки паролей, сгенерированных другой системой (например, Django), но хэшировать все новые пароли другим алгоритмом, например Bcrypt.
102+
Например, вы можете использовать его для чтения и проверки паролей, сгенерированных другой системой (например, Django), но хэшировать все новые пароли другим алгоритмом, например Argon2 или Bcrypt.
103103

104104
И при этом быть совместимым со всеми этими системами.
105105
///

docs_src/security/tutorial004_an_py310.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from fastapi import Depends, FastAPI, HTTPException, status
66
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
77
from jwt.exceptions import InvalidTokenError
8-
from passlib.context import CryptContext
8+
from pwdlib import PasswordHash
99
from pydantic import BaseModel
1010

1111
# to get a string like this run:
@@ -46,19 +46,19 @@ class UserInDB(User):
4646
hashed_password: str
4747

4848

49-
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
49+
password_hash = PasswordHash.recommended()
5050

5151
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
5252

5353
app = FastAPI()
5454

5555

5656
def verify_password(plain_password, hashed_password):
57-
return pwd_context.verify(plain_password, hashed_password)
57+
return password_hash.verify(plain_password, hashed_password)
5858

5959

6060
def get_password_hash(password):
61-
return pwd_context.hash(password)
61+
return password_hash.hash(password)
6262

6363

6464
def get_user(db, username: str):

0 commit comments

Comments
 (0)