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, *Server 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.

1. Generate signed JWT

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

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(
  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 dictionary. Example below:

def validate_client_id(self, client_id, request):
    (.. your usual checks ..) = {
        'aud': self.client_id
    return True

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


And you will find all claims in its decoded form:

  "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:

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:

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

server = Server(

3. BearerToken API

If none of the Preconfigured all-in-one servers fit your needs, you can declare your own Endpoints and use the BearerToken API as below.

class oauthlib.oauth2.BearerToken(request_validator=None, token_generator=None, expires_in=None, refresh_token_generator=None)[source]
create_token(request, refresh_token=False, **kwargs)[source]

Create a BearerToken, by default without refresh token.

  • request (oauthlib.common.Request) – OAuthlib request.
  • refresh_token
Parameters:request (oauthlib.common.Request) – OAuthlib request.
Parameters:request (oauthlib.common.Request) – OAuthlib request.