Debian Codegraph @

docs/headless/token-strategies/jwt-tokens.rst

raw
1 JWT Tokens
2 ==========
3
4 Introduction
5 ------------
6
7 When using the JWT token strategy, an access token and refresh token pair is
8 handed out when the user becomes fully authenticated. The access token is a JWT
9 token, and is typically short-lived. The refresh token can be used to issue a
10 new access token in case the access token is expired.
11
12 The use of JWT is mainly beneficial for a multi-service architecture, where
13 authentication can be performed in each service without having to contact a
14 central authority.
15
16 Often, the JWT token strategy is incorrectly touted as being stateless. Unless
17 it is acceptable that access tokens can still be used after logging out, state
18 is needed to invalidate outstanding access tokens, diminishing the stateless
19 aspect of the JWT token strategy.
20
21
22 Usage
23 -----
24
25 With the JWT token strategy enabled, the way of working is as follows:
26
27 - End users are guided through the authentication process. For as long as
28 they are not fully authenticated, you communicate the ``X-Session-Token`` header
29 back to the allauth API.
30
31 - In the response of the request that resulted in the user becoming fully
32 authenticated, you will find an access token and refresh token pair in the
33 ``meta`` payload.
34
35 - From this moment onward, your application can drop the ``X-Session-Token``
36 completely. The access token can be used to reach out to your own API
37 endpoints, as well as to the allauth API endpoints.
38
39
40 Configuration
41 -------------
42
43 Available settings:
44
45 ``HEADLESS_JWT_ALGORITHM`` (default: ``"RS256"``)
46 The algorithm used to sign the tokens. For asymmetric algorithms (e.g. ``"RS256"``),
47 the ``HEADLESS_JWT_PRIVATE_KEY`` is used as the RSA private key. For symmetric
48 algorithms (e.g. ``"HS256"``), ``HEADLESS_JWT_PRIVATE_KEY`` is used as the
49 secret. In case a symmetric algorithm is used and the private key is not
50 configured, ``settings.SECRET_KEY`` is used as a fallback.
51
52 ``HEADLESS_JWT_PRIVATE_KEY`` (default: ``""``)
53 The private key (or secret) used to sign the JWT tokens. For asymmetric
54 algorithms, it can be generated using the following command::
55
56 openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048
57
58 Then, include that ``private_key.pem`` in your ``settings.py``::
59
60 HEADLESS_JWT_PRIVATE_KEY = """
61 -----BEGIN PRIVATE KEY-----
62 MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCiStSwvoSk61uf
63 cQvkGDmR6gsM2QjVgKxCTPtg3tMhMO7kXq3PPMEiWlF49JicjPWs5vkYcLAsWNVE
64 ...
65 rfnteLIERvzd4rLi9WjTahfKA2Mq3YNIe3Hw8IDrrczJgd/XkEaENGYXmmNCX22B
66 gtUcukumVPtrDhGK9i/PG3Q=
67 -----END PRIVATE KEY-----
68 """
69
70 ``HEADLESS_JWT_ACCESS_TOKEN_EXPIRES_IN`` (default: ``300``)
71 The lifetime (in seconds) of the access tokens.
72
73 ``HEADLESS_JWT_REFRESH_TOKEN_EXPIRES_IN`` (default: ``86400``)
74 The lifetime (in seconds) of the refresh tokens.
75
76 ``HEADLESS_JWT_AUTHORIZATION_HEADER_SCHEME`` (default: ``"Bearer"``)
77 Specifies the HTTP Authorization header scheme for access tokens, e.g.: ``Authorization: Bearer <access-token>``.
78
79 ``HEADLESS_JWT_STATEFUL_VALIDATION_ENABLED`` (default: ``False``)
80 When enabled, it is validated that the access token still belongs to an
81 active session. As a result, logging out will immediately invalidate the
82 access token.
83
84 ``HEADLESS_JWT_ROTATE_REFRESH_TOKEN`` (default: ``True``)
85 When enabled, refreshing the access token results in a new refresh token
86 as well. The original refresh token is invalidated.
87
88
89 Customization
90 -------------
91
92 You can customize the behavior of the JWT token strategy by creating a custom
93 class deriving from ``JWTTokenStrategy``, and pointing
94 ``settings.HEADLESS_TOKEN_STRATEGY`` to that class.
95
96 .. autoclass:: allauth.headless.tokens.strategies.jwt.JWTTokenStrategy
97 :members: get_claims
98
99
100 Securing Your API Endpoints
101 ---------------------------
102
103 Django Ninja
104 ~~~~~~~~~~~~
105
106 For Django Ninja, the following security class is available:
107
108 .. autoclass:: allauth.headless.contrib.ninja.security.JWTTokenAuth
109 :members:
110
111 An example on how to use that security class in your own code is listed below:
112
113 .. code-block:: python
114
115 from allauth.headless.contrib.ninja.security import jwt_token_auth
116 from ninja import NinjaAPI
117
118 api = NinjaAPI()
119
120 @api.get("/your/own/api", auth=[jwt_token_auth])
121 def your_own_api(request):
122 ...
123
124
125
126 Django REST framework
127 ~~~~~~~~~~~~~~~~~~~~~
128
129 For Django REST framework, the following authentication class is available:
130
131 .. autoclass:: allauth.headless.contrib.rest_framework.authentication.JWTTokenAuthentication
132 :members:
133
134 An example on how to use that authentication class in your own code is listed below:
135
136 .. code-block:: python
137
138 from allauth.headless.contrib.rest_framework.authentication import (
139 JWTTokenAuthentication,
140 )
141 from rest_framework import permissions
142 from rest_framework.views import APIView
143
144 class YourOwnAPIView(APIView):
145
146 authentication_classes = [
147 JWTTokenAuthentication,
148 ]
149 permission_classes = [permissions.IsAuthenticated]
150
151 def get(self, request):
152 ...