> For the complete documentation index, see [llms.txt](https://docs.mobguards.com/ru/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.mobguards.com/ru/backend-integration/jwt-token/python.md).

# Python

### Требования

Чтобы иметь возможность декодировать токен JWT с помощью Python, необходимо установить пакет PyJWT.

Лучший способ установить его - через менеджер пакетов pip:

```bash
$ pip3 install pyjwt
```

### Использование PyJWT

Во-первых, необходимо импортировать пакет `PyJWT`:

```python
import jwt
```

Во-вторых, необходимо прочитать и сохранить публичный ключ (используемый для расшифровки токена). Нужно заранее получить его заранее и хранить рядом с проектом (в данном случае `./keys/id_rsa.pub`).

```python
# Choose a place to store a public key
pub_key_path = '.keys/id_rsa.pub'
with open(pub_key_path, mode='rb') as public_file:
    PUBLIC_KEY = public_file.read()
```

Теперь публичный ключ хранится в переменной `PUBLIC_KEY`.

Далее необходимо реализовать функцию для проверки токена:

```python
def verify_jwt(jwt_token):
    try:
        return jwt.decode(jwt_token, PUBLIC_KEY, algorithms='RS256')
    except:
        return None
```

Эта функция содержит две основные ветви: токен действителен или нет.&#x20;

В блоке `try` выполняется попытка проверить токен. Если токен действителен, то функция `verify_jwt` вернет его JSON-значение. Если токен неверен или истек срок действия, `verify_jwt` возвращает None.

Чтобы использовать эту функцию, следует передать ей токен JWT.

```python
public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCvt9ZrQP23A06ZLaOLoXtY2NYLkaAO+UyJG7S6WPD4ue49flkzNEKYlTKdk3L9HzMNeQZTqT+Bn310E/u/yOci8yY8GUBNb+kuH1VM2EAl7MPY41eX+tZe/wy0OWvrnhj1H5V5aXt8hISbIZLmgtUQWNINn/xsrn8EIETxbHiEVAXZoVXQYddiw+EY6uD/GRPCLNVr4gx43Yfcx+jSACotoy2hmK8v6N5VmLs+AOILf4INfE8MnzAJt8PD5T5CEVPO82+qj67E9Y40tQnyWpZ028QOerFnqRNRoa0+Fh5xXE+lExP8gRq47cUmWLAkCpUpNvFyStkr56SWrE/NZgCx"

result = verify_jwt(jwt_token)
```

`jwt_token` - это токен, который был получен в запросе. Пример токена:

```python
>>> jwt_token
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJjaGFsbGVuZ2VfaWQiOiI2MTAyZTBlNi1hMDZjLTRmODEtYjA5NS03ZGUxODUzY2U1YTIiLCJyZXN1bHQiOjAuOTQ5NDQ3NTU2MDI4NzU2LCJpYXQiOjE1NzgzMzY1NzMsImV4cCI6MTU3ODMzNjYzM30.UGFLV4qJGWEF2ZDpFk5tafBB9q9DwHOEMw9i7y_gQ6GsgyD5C9osoXaQwlZXaQ_oDoeGDGiLUzjFdsdhDAADEAGKbmuiLC1JWWdd-pC2JxIQlId4kLw1hZEe6ljUljxSJH980rWoeUMhNjmq3CddaesoYBxi1hLW0LM0oWv_DxNZqzd8VehM1rS8hDRszgG-EJR_lWr3sMMyN82mh4-55xEgNd3KF_UG0hqja55x6pESTEhmTxzAjywK5tiitwOYoRgy2W_krOD6oUadJlX_0W4CLzn2g0gdjwtYxNfImdcJoIXSSWoMC1NikSMIsrDmGtofjS_icmwn_cxks-Qyhg"
```

### Результат

Если токен правильный и срок его действия не истек, после использования `jwt_verify` будет получен декодированную структуру JWT:

```javascript
{
  "challenge_id": "3aa67786-d8cb-4ed5-ae83-ae7ace27e372",
  "result": 94,
  "iat": 1578001068,
  "exp": 1578001128
}
```

Результат проверки бот/не бот можно получить из поля `result`.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.mobguards.com/ru/backend-integration/jwt-token/python.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
