# JWT

### Links

* [Insegurança em JWT](https://tiagotavares.io/2020/06/inseguran%C3%A7a-em-tokens-jwt/)
* [Stop using JWT for Sessions](http://cryto.net/~joepie91/blog/2016/06/13/stop-using-jwt-for-sessions/)
* [JWT With RSA Signature](https://connect2id.com/products/nimbus-jose-jwt/examples/jwt-with-rsa-signature)
* [JSON Web Tokens (JWT) are Dangerous for User Sessions—Here’s a Solution](https://redis.com/blog/json-web-tokens-jwt-are-dangerous-for-user-sessions/)

### Asymmetric

Some times we will need to generate a JWT from a trusted source and other applications can check and validate but not generate new tokens.

In this case we will need an asymmetric token.

The token will be generated using a private key and the other services will use a public key to validate the signature.

Here is an example using python

***public\_key.txt***

```
-----BEGIN PUBLIC KEY-----
MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQBlNHhNAoTgUvv8cNqhjtrH
aA9MaS24MXmotQC8WR/8How33Xom6xxhQNp/eXD7/dzRZAw+Hf7vvIPTGSsA2PsS
jYt1EaS6F87sHVHlJFSSjQK7uNsHft5tltgz12U6smZY5/XlG3Vss2LGEzd3vV/t
lwXa4i3iIEYQRJz9ypU4AR/dOcD/yiY/n/wZUvMYNYq8u400/oqJJPA3n9KEPzZo
Pgbc/TBG9uc7CRbkN1qCtz19VwD8ufUzpLvE880iFuijmtCA+n4r1bm3KWKNjuRv
BhChApTvqEkyXEVV8H94N/Un0C3DMyuWHtXa0oE+r2or5GEZs4v18CG4YlglbD3p
AgMBAAE=
-----END PUBLIC KEY-----
```

***private\_key.txt***

```
-----BEGIN RSA PRIVATE KEY-----
MIIEoQIBAAKCAQBlNHhNAoTgUvv8cNqhjtrHaA9MaS24MXmotQC8WR/8How33Xom
6xxhQNp/eXD7/dzRZAw+Hf7vvIPTGSsA2PsSjYt1EaS6F87sHVHlJFSSjQK7uNsH
ft5tltgz12U6smZY5/XlG3Vss2LGEzd3vV/tlwXa4i3iIEYQRJz9ypU4AR/dOcD/
yiY/n/wZUvMYNYq8u400/oqJJPA3n9KEPzZo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MT75s7D0D0OosZ8wcifdtFfqIV5Knk79ULGaVq/h1nOdDodQkWge/Goqgl
WC/9KVDf2gGpBukAHSlW5035fW8/lTgglqyIE2IQDk3zj6hCgPus+Zc3yh2HQXHO
eGkCgYA5r3ZrJadbUueZa7L99YHQ9OVUHVUZ8V3K5y6AR838S4+EzYKjD18S9yP4
xNg3AyN31k9+iWRQW+LYjmVzOL4kHVNHmAslw+11tu5HL+z0w08CiPK/0TXEaHrz
/ozUu6Lwn9JlAFN3lMrBiz5qgor6BgealH0VThi6m1NHtgAvHA==
-----END RSA PRIVATE KEY-----
```

***jwt\_asymmetric.py***

```python
# === SETUP ===
# pip install pyjwt
# pip install cryptography

import jwt

with open('public_key.txt') as public_key_file, open('private_key.txt') as private_key_file:
    PUBLIC_KEY = public_key_file.read()
    PRIVATE_KEY = private_key_file.read()

    encodedToken = jwt.encode({'userid':'1'}, PRIVATE_KEY, algorithm = 'RS256')
    decodedToken = jwt.decode(encodedToken, PUBLIC_KEY, verify=True, algorithms='RS256')

    print(encodedToken)
    print(decodedToken)
    
```

***Output:***

```
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1c2VyaWQiOiIxIn0.J8qmVxyyCsmIxiqMl8NCOFgaJZEYX3bsc_PyZbAmOWKeeBaOuKVfCBloLR17BC0BwdkfxGtsLhjKtfC1K5Q2W5K3eM3YFEVk57HxnrJoz9v8ZTrdJ1QCfsD2DSasZufVg-3P6ZsBK3ro70PO32mPBkNI5eI4Qp6lcubBMbaIDymWBMFNw04d28-u6AneBqjAtf7BtUQgpFKSzXSW2_kQpcpEHJfu8yB3jVs252UjPUu9yUvA0x49aZzkl3jUZqCXegFebv2ZSNLQ637VpKHIe6hijMSpfK15jJ8k7R2M85JKzRb37EpsdO20GBuWOEL_12d7zNlT96Rrd5vmrd0jZg

{'userid': '1'}
```
