You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/api-guide/authentication.md
+29-31Lines changed: 29 additions & 31 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -3,8 +3,6 @@ source:
3
3
- authentication.py
4
4
---
5
5
6
-
# Authentication
7
-
8
6
> Auth needs to be pluggable.
9
7
>
10
8
> — Jacob Kaplan-Moss, ["REST worst practices"][cite]
@@ -104,9 +102,9 @@ If you are deploying to Apache, and using any non-session based authentication,
104
102
105
103
---
106
104
107
-
# API Reference
105
+
##API Reference
108
106
109
-
## BasicAuthentication
107
+
###BasicAuthentication
110
108
111
109
This authentication scheme uses [HTTP Basic Authentication][basicauth], signed against a user's username and password. Basic authentication is generally only appropriate for testing.
112
110
@@ -122,7 +120,7 @@ Unauthenticated responses that are denied permission will result in an `HTTP 401
122
120
!!! note
123
121
If you use `BasicAuthentication` in production you must ensure that your API is only available over `https`. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.
124
122
125
-
## TokenAuthentication
123
+
###TokenAuthentication
126
124
127
125
!!! note
128
126
The token authentication provided by Django REST framework is a fairly simple implementation.
@@ -171,9 +169,9 @@ The `curl` command line tool may be useful for testing token authenticated APIs.
171
169
!!! note
172
170
If you use `TokenAuthentication` in production you must ensure that your API is only available over `https`.
173
171
174
-
### Generating Tokens
172
+
####Generating Tokens
175
173
176
-
#### By using signals
174
+
#####By using signals
177
175
178
176
If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.
179
177
@@ -197,7 +195,7 @@ If you've already created some users, you can generate tokens for all existing u
197
195
for user in User.objects.all():
198
196
Token.objects.get_or_create(user=user)
199
197
200
-
#### By exposing an api endpoint
198
+
#####By exposing an api endpoint
201
199
202
200
When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf:
203
201
@@ -246,7 +244,7 @@ And in your `urls.py`:
246
244
]
247
245
248
246
249
-
#### With Django admin
247
+
#####With Django admin
250
248
251
249
It is also possible to create Tokens manually through the admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class to customize it to your needs, more specifically by declaring the `user` field as `raw_field`.
252
250
@@ -257,7 +255,7 @@ It is also possible to create Tokens manually through the admin interface. In ca
257
255
TokenAdmin.raw_id_fields = ['user']
258
256
259
257
260
-
#### Using Django manage.py command
258
+
#####Using Django manage.py command
261
259
262
260
Since version 3.6.4 it's possible to generate a user token using the following command:
263
261
@@ -272,7 +270,7 @@ In case you want to regenerate the token (for example if it has been compromised
272
270
./manage.py drf_create_token -r <username>
273
271
274
272
275
-
## SessionAuthentication
273
+
###SessionAuthentication
276
274
277
275
This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.
278
276
@@ -291,7 +289,7 @@ If you're using an AJAX-style API with SessionAuthentication, you'll need to mak
291
289
CSRF validation in REST framework works slightly differently from standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behavior is not suitable for login views, which should always have CSRF validation applied.
292
290
293
291
294
-
## RemoteUserAuthentication
292
+
###RemoteUserAuthentication
295
293
296
294
This authentication scheme allows you to delegate authentication to your web server, which sets the `REMOTE_USER`
297
295
environment variable.
@@ -312,7 +310,7 @@ Consult your web server's documentation for information about configuring an aut
To implement a custom authentication scheme, subclass `BaseAuthentication` and override the `.authenticate(self, request)` method. The method should return a two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise.
318
316
@@ -330,7 +328,7 @@ If the `.authenticate_header()` method is not overridden, the authentication sch
330
328
!!! note
331
329
When your custom authenticator is invoked by the request object's `.user` or `.auth` properties, you may see an `AttributeError` re-raised as a `WrappedAttributeError`. This is necessary to prevent the original exception from being suppressed by the outer property access. Python will not recognize that the `AttributeError` originates from your custom authenticator and will instead assume that the request object does not have a `.user` or `.auth` property. These errors should be fixed or otherwise handled by your authenticator.
332
330
333
-
## Example
331
+
###Example
334
332
335
333
The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X-USERNAME'.
336
334
@@ -353,19 +351,19 @@ The following example will authenticate any incoming request as the user given b
353
351
354
352
---
355
353
356
-
# Third party packages
354
+
##Third party packages
357
355
358
356
The following third-party packages are also available.
359
357
360
-
## django-rest-knox
358
+
###django-rest-knox
361
359
362
360
[Django-rest-knox][django-rest-knox] library provides models and views to handle token-based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into).
363
361
364
-
## Django OAuth Toolkit
362
+
###Django OAuth Toolkit
365
363
366
364
The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support and works with Python 3.4+. The package is maintained by [jazzband][jazzband] and uses the excellent [OAuthLib][oauthlib]. The package is well documented, and well supported and is currently our **recommended package for OAuth 2.0 support**.
367
365
368
-
### Installation & configuration
366
+
####Installation & configuration
369
367
370
368
Install using `pip`.
371
369
@@ -386,42 +384,42 @@ Add the package to your `INSTALLED_APPS` and modify your REST framework settings
386
384
387
385
For more details see the [Django REST framework - Getting started][django-oauth-toolkit-getting-started] documentation.
388
386
389
-
## Django REST framework OAuth
387
+
###Django REST framework OAuth
390
388
391
389
The [Django REST framework OAuth][django-rest-framework-oauth] package provides both OAuth1 and OAuth2 support for REST framework.
392
390
393
391
This package was previously included directly in the REST framework but is now supported and maintained as a third-party package.
394
392
395
-
### Installation & configuration
393
+
####Installation & configuration
396
394
397
395
Install the package using `pip`.
398
396
399
397
pip install djangorestframework-oauth
400
398
401
399
For details on configuration and usage see the Django REST framework OAuth documentation for [authentication][django-rest-framework-oauth-authentication] and [permissions][django-rest-framework-oauth-permissions].
402
400
403
-
## JSON Web Token Authentication
401
+
###JSON Web Token Authentication
404
402
405
403
JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. A package for JWT authentication is [djangorestframework-simplejwt][djangorestframework-simplejwt] which provides some features as well as a pluggable token blacklist app.
406
404
407
-
## Hawk HTTP Authentication
405
+
###Hawk HTTP Authentication
408
406
409
407
The [HawkREST][hawkrest] library builds on the [Mohawk][mohawk] library to let you work with [Hawk][hawk] signed requests and responses in your API. [Hawk][hawk] lets two parties securely communicate with each other using messages signed by a shared key. It is based on [HTTP MAC access authentication][mac] (which was based on parts of [OAuth 1.0][oauth-1.0a]).
410
408
411
-
## HTTP Signature Authentication
409
+
###HTTP Signature Authentication
412
410
413
411
HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to [Amazon's HTTP Signature scheme][amazon-http-signature], used by many of its services, it permits stateless, per-request authentication. [Elvio Toccalino][etoccalino] maintains the [djangorestframework-httpsignature][djangorestframework-httpsignature] (outdated) package which provides an easy-to-use HTTP Signature Authentication mechanism. You can use the updated fork version of [djangorestframework-httpsignature][djangorestframework-httpsignature], which is [drf-httpsig][drf-httpsig].
414
412
415
-
## Djoser
413
+
###Djoser
416
414
417
415
[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and uses token-based authentication. This is a ready to use REST implementation of the Django authentication system.
418
416
419
-
## DRF Auth Kit
417
+
###DRF Auth Kit
420
418
421
419
[DRF Auth Kit][drf-auth-kit] library provides a modern REST authentication solution with JWT cookies, social login, multi-factor authentication, and comprehensive user management. The package offers full type safety, automatic OpenAPI schema generation with DRF Spectacular. It supports multiple authentication types (JWT, DRF Token, or Custom) and includes built-in internationalization for 50+ languages.
422
420
423
421
424
-
## django-rest-auth / dj-rest-auth
422
+
###django-rest-auth / dj-rest-auth
425
423
426
424
This library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management.
427
425
@@ -431,25 +429,25 @@ There are currently two forks of this project.
431
429
*[Django-rest-auth][django-rest-auth] is the original project, [but is not currently receiving updates](https://github.com/Tivix/django-rest-auth/issues/568).
432
430
*[Dj-rest-auth][dj-rest-auth] is a newer fork of the project.
433
431
434
-
## drf-social-oauth2
432
+
###drf-social-oauth2
435
433
436
434
[Drf-social-oauth2][drf-social-oauth2] is a framework that helps you authenticate with major social oauth2 vendors, such as Facebook, Google, Twitter, Orcid, etc. It generates tokens in a JWTed way with an easy setup.
437
435
438
-
## drfpasswordless
436
+
###drfpasswordless
439
437
440
438
[drfpasswordless][drfpasswordless] adds (Medium, Square Cash inspired) passwordless support to Django REST Framework's TokenAuthentication scheme. Users log in and sign up with a token sent to a contact point like an email address or a mobile number.
441
439
442
-
## django-rest-authemail
440
+
###django-rest-authemail
443
441
444
442
[django-rest-authemail][django-rest-authemail] provides a RESTful API interface for user signup and authentication. Email addresses are used for authentication, rather than usernames. API endpoints are available for signup, signup email verification, login, logout, password reset, password reset verification, email change, email change verification, password change, and user detail. A fully functional example project and detailed instructions are included.
445
443
446
-
## Django-Rest-Durin
444
+
###Django-Rest-Durin
447
445
448
446
[Django-Rest-Durin][django-rest-durin] is built with the idea to have one library that does token auth for multiple Web/CLI/Mobile API clients via one interface but allows different token configuration for each API Client that consumes the API. It provides support for multiple tokens per user via custom models, views, permissions that work with Django-Rest-Framework. The token expiration time can be different per API client and is customizable via the Django Admin Interface.
449
447
450
448
More information can be found in the [Documentation](https://django-rest-durin.readthedocs.io/en/latest/index.html).
451
449
452
-
## django-pyoidc
450
+
###django-pyoidc
453
451
454
452
[django_pyoidc][django-pyoidc] adds support for OpenID Connect (OIDC) authentication. This allows you to delegate user management to an Identity Provider, which can be used to implement Single-Sign-On (SSO). It provides support for most uses-cases, such as customizing how token info are mapped to user models, using OIDC audiences for access control, etc.
Copy file name to clipboardExpand all lines: docs/api-guide/content-negotiation.md
+3-5Lines changed: 3 additions & 5 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -3,8 +3,6 @@ source:
3
3
- negotiation.py
4
4
---
5
5
6
-
# Content negotiation
7
-
8
6
> HTTP has provisions for several mechanisms for "content negotiation" - the process of selecting the best representation for a given response when there are multiple representations available.
9
7
>
10
8
> —[RFC 2616][cite], Fielding et al.
@@ -40,7 +38,7 @@ For more information on the `HTTP Accept` header, see [RFC 2616][accept-header]
40
38
41
39
This is a valid approach as the HTTP spec deliberately underspecifies how a server should weight server-based preferences against client-based preferences.
42
40
43
-
# Custom content negotiation
41
+
##Custom content negotiation
44
42
45
43
It's unlikely that you'll want to provide a custom content negotiation scheme for REST framework, but you can do so if needed. To implement a custom content negotiation scheme override `BaseContentNegotiation`.
46
44
@@ -50,7 +48,7 @@ The `select_parser()` method should return one of the parser instances from the
50
48
51
49
The `select_renderer()` method should return a two-tuple of (renderer instance, media type), or raise a `NotAcceptable` exception.
52
50
53
-
## Example
51
+
###Example
54
52
55
53
The following is a custom content negotiation class which ignores the client
56
54
request when selecting the appropriate parser or renderer.
@@ -70,7 +68,7 @@ request when selecting the appropriate parser or renderer.
70
68
"""
71
69
return (renderers[0], renderers[0].media_type)
72
70
73
-
## Setting the content negotiation
71
+
###Setting the content negotiation
74
72
75
73
The default content negotiation class may be set globally, using the `DEFAULT_CONTENT_NEGOTIATION_CLASS` setting. For example, the following settings would use our example `IgnoreClientContentNegotiation` class.
Raised when an incoming request includes incorrect authentication.
159
159
160
160
By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details.
Raised when an unauthenticated request fails the permission checks.
167
167
168
168
By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details.
The following third-party packages are also available.
265
265
266
-
## DRF Standardized Errors
266
+
###DRF Standardized Errors
267
267
268
268
The [drf-standardized-errors][drf-standardized-errors] package provides an exception handler that generates the same format for all 4xx and 5xx responses. It is a drop-in replacement for the default exception handler and allows customizing the error response format without rewriting the whole exception handler. The standardized error response format is easier to document and easier to handle by API consumers.
0 commit comments