summaryrefslogtreecommitdiff
path: root/docs/oauth2/tokens/bearer.rst
blob: c23efabc322a26ab8573706808936526fd328538 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
=============
Bearer Tokens
=============

The most common OAuth 2 token type.

Bearer tokens is the default setting for all configured endpoints. Generally
you will not need to ever construct a token yourself as the provided servers
will do so for you.

By default, :doc:`*Server </oauth2/preconfigured_servers>` generate Bearer tokens as
random strings. However, you can change the default behavior to generate JWT
instead. All preconfigured servers take as parameters `token_generator` and
`refresh_token_generator` to fit your needs.

.. contents:: Tutorial Contents
    :depth: 3


1. Generate signed JWT
----------------------

A function is available to generate signed JWT (with RS256 PEM key) with static
and dynamic claims.

.. code-block:: python

    from oauthlib.oauth2.rfc6749 import tokens
    from oauthlib.oauth2 import Server

    private_pem_key = <load_your_key_in_pem_format>
    validator = <instantiate_your_validator>

    server = Server(
      your_validator,
      token_generator=tokens.signed_token_generator(private_pem_key, issuer="foobar")
    )


Note that you can add any custom claims in `RequestValidator` methods by adding them to
`request.claims` dictionary. Example below:


.. code-block:: python

    def validate_client_id(self, client_id, request):
        (.. your usual checks ..)

        request.claims = {
            'aud': self.client_id
        }
        return True


Once completed, the token endpoint will generate access_token in JWT form:

.. code-block:: shell


    access_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJy(..)&expires_in=120&token_type=Bearer(..)


And you will find all claims in its decoded form:


.. code-block:: javascript

    {
      "aud": "<client_id>",
      "iss": "foobar",
      "scope": "profile calendar",
      "exp": 12345,
    }


2. Define your own implementation (text, JWT, JWE, ...)
----------------------------------------------------------------

Sometime you may want to generate custom `access_token` with a reference from a
database (as text) or use a HASH signature in JWT or use JWE (encrypted content).

Also, note that you can declare the generate function in your instantiated
validator to benefit of the `self` variables.

See the example below:

.. code-block:: python

    class YourValidator(RequestValidator):
        def __init__(self, secret, issuer):
            self.secret = secret
            self.issuer = issuer

        def generate_access_token(self, request):
            token = jwt.encode({
                "ref": str(libuuid.uuid4()),
                "aud": request.client_id,
                "iss": self.issuer,
                "exp": now + datetime.timedelta(seconds=request.expires_in)
            }, self.secret, algorithm='HS256').decode()
            return token


Then associate it to your `Server`:

.. code-block:: python

    validator = YourValidator(secret="<your_secret>", issuer="<your_issuer_id>")

    server = Server(
        your_validator,
        token_generator=validator.generate_access_token
    )


3. BearerToken API
------------------

If none of the :doc:`/oauth2/preconfigured_servers` fit your needs, you can
declare your own Endpoints and use the `BearerToken` API as below.

.. autoclass:: oauthlib.oauth2.BearerToken
    :members: