-

4.3.0

+

5.0.0

    +
  • Tokens created prior to this release will no longer work
  • Fix migration reverse flow, enable migrate 0
  • Various documentation fixes and improvements
  • Drop cryptography in favor of hashlib
  • diff --git a/index.html b/index.html index 2cfad55..df432b3 100644 --- a/index.html +++ b/index.html @@ -172,5 +172,5 @@

    Django-Rest-Knox

    diff --git a/search/search_index.json b/search/search_index.json index 6138f4e..3ea2309 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Django-Rest-Knox Knox provides easy-to-use authentication for Django REST Framework The aim is to allow for common patterns in applications that are REST based, with little extra effort; and to ensure that connections remain secure. Knox authentication is token based, similar to the TokenAuthentication built into DRF. However, it overcomes some problems present in the default implementation: DRF tokens are limited to one per user. This does not facilitate securely signing in from multiple devices, as the token is shared. It also requires all devices to be logged out if a server-side logout is required (i.e. the token is deleted). Knox provides one token per call to the login view - allowing each client to have its own token which is deleted on the server side when the client logs out. Knox also provides an optional setting to limit the amount of tokens generated per user. Knox also provides an option for a logged in client to remove all tokens that the server has - forcing all clients to re-authenticate. DRF tokens are stored unencrypted in the database. This would allow an attacker unrestricted access to an account with a token if the database were compromised. Knox tokens are only stored in an encrypted form. Even if the database were somehow stolen, an attacker would not be able to log in with the stolen credentials. DRF tokens track their creation time, but have no inbuilt mechanism for tokens expiring. Knox tokens can have an expiry configured in the app settings (default is 10 hours.)","title":"Home"},{"location":"#django-rest-knox","text":"Knox provides easy-to-use authentication for Django REST Framework The aim is to allow for common patterns in applications that are REST based, with little extra effort; and to ensure that connections remain secure. Knox authentication is token based, similar to the TokenAuthentication built into DRF. However, it overcomes some problems present in the default implementation: DRF tokens are limited to one per user. This does not facilitate securely signing in from multiple devices, as the token is shared. It also requires all devices to be logged out if a server-side logout is required (i.e. the token is deleted). Knox provides one token per call to the login view - allowing each client to have its own token which is deleted on the server side when the client logs out. Knox also provides an optional setting to limit the amount of tokens generated per user. Knox also provides an option for a logged in client to remove all tokens that the server has - forcing all clients to re-authenticate. DRF tokens are stored unencrypted in the database. This would allow an attacker unrestricted access to an account with a token if the database were compromised. Knox tokens are only stored in an encrypted form. Even if the database were somehow stolen, an attacker would not be able to log in with the stolen credentials. DRF tokens track their creation time, but have no inbuilt mechanism for tokens expiring. Knox tokens can have an expiry configured in the app settings (default is 10 hours.)","title":"Django-Rest-Knox"},{"location":"auth/","text":"Authentication knox.auth Knox provides one class to handle authentication. TokenAuthentication This works using DRF's authentication system . Knox tokens should be generated using the provided views. Any APIView or ViewSet can be accessed using these tokens by adding TokenAuthentication to the View's authentication_classes . To authenticate, the Authorization header should be set on the request, with a value of the word \"Token\" , then a space, then the authentication token provided by LoginView . Example: from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from knox.auth import TokenAuthentication class ExampleView(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get(self, request, format=None): content = { 'foo': 'bar' } return Response(content) Example auth header: Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b9836F45E23A345 Tokens expire after a preset time. See settings. Global usage on all views You can activate TokenAuthentication on all your views by adding it to REST_FRAMEWORK[\"DEFAULT_AUTHENTICATION_CLASSES\"] . If it is your only default authentication class, remember to overwrite knox's LoginView, otherwise it'll not work, since the login view will require a authentication token to generate a new token, rendering it unusable. For instance, you can authenticate users using Basic Authentication by simply overwriting knox's LoginView and setting BasicAuthentication as one of the acceptable authentication classes, as follows: views.py: from knox.views import LoginView as KnoxLoginView from rest_framework.authentication import BasicAuthentication class LoginView(KnoxLoginView): authentication_classes = [BasicAuthentication] urls.py: from knox import views as knox_views from yourapp.api.views import LoginView urlpatterns = [ path(r'login/', LoginView.as_view(), name='knox_login'), path(r'logout/', knox_views.LogoutView.as_view(), name='knox_logout'), path(r'logoutall/', knox_views.LogoutAllView.as_view(), name='knox_logoutall'), ] You can use any number of authentication classes if you want to be able to authenticate using different methods (eg.: Basic and JSON) in the same view. Just be sure not to set TokenAuthentication as your only authentication class on the login view. If you decide to use Token Authentication as your only authentication class, you can overwrite knox's login view as such: views.py: from django.contrib.auth import login from rest_framework import permissions from rest_framework.authtoken.serializers import AuthTokenSerializer from knox.views import LoginView as KnoxLoginView class LoginView(KnoxLoginView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(LoginView, self).post(request, format=None) urls.py: from knox import views as knox_views from yourapp.api.views import LoginView urlpatterns = [ path(r'login/', LoginView.as_view(), name='knox_login'), path(r'logout/', knox_views.LogoutView.as_view(), name='knox_logout'), path(r'logoutall/', knox_views.LogoutAllView.as_view(), name='knox_logoutall'), ]","title":"Authentication"},{"location":"auth/#authentication-knoxauth","text":"Knox provides one class to handle authentication.","title":"Authentication knox.auth"},{"location":"auth/#tokenauthentication","text":"This works using DRF's authentication system . Knox tokens should be generated using the provided views. Any APIView or ViewSet can be accessed using these tokens by adding TokenAuthentication to the View's authentication_classes . To authenticate, the Authorization header should be set on the request, with a value of the word \"Token\" , then a space, then the authentication token provided by LoginView . Example: from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from knox.auth import TokenAuthentication class ExampleView(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get(self, request, format=None): content = { 'foo': 'bar' } return Response(content) Example auth header: Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b9836F45E23A345 Tokens expire after a preset time. See settings.","title":"TokenAuthentication"},{"location":"auth/#global-usage-on-all-views","text":"You can activate TokenAuthentication on all your views by adding it to REST_FRAMEWORK[\"DEFAULT_AUTHENTICATION_CLASSES\"] . If it is your only default authentication class, remember to overwrite knox's LoginView, otherwise it'll not work, since the login view will require a authentication token to generate a new token, rendering it unusable. For instance, you can authenticate users using Basic Authentication by simply overwriting knox's LoginView and setting BasicAuthentication as one of the acceptable authentication classes, as follows: views.py: from knox.views import LoginView as KnoxLoginView from rest_framework.authentication import BasicAuthentication class LoginView(KnoxLoginView): authentication_classes = [BasicAuthentication] urls.py: from knox import views as knox_views from yourapp.api.views import LoginView urlpatterns = [ path(r'login/', LoginView.as_view(), name='knox_login'), path(r'logout/', knox_views.LogoutView.as_view(), name='knox_logout'), path(r'logoutall/', knox_views.LogoutAllView.as_view(), name='knox_logoutall'), ] You can use any number of authentication classes if you want to be able to authenticate using different methods (eg.: Basic and JSON) in the same view. Just be sure not to set TokenAuthentication as your only authentication class on the login view. If you decide to use Token Authentication as your only authentication class, you can overwrite knox's login view as such: views.py: from django.contrib.auth import login from rest_framework import permissions from rest_framework.authtoken.serializers import AuthTokenSerializer from knox.views import LoginView as KnoxLoginView class LoginView(KnoxLoginView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(LoginView, self).post(request, format=None) urls.py: from knox import views as knox_views from yourapp.api.views import LoginView urlpatterns = [ path(r'login/', LoginView.as_view(), name='knox_login'), path(r'logout/', knox_views.LogoutView.as_view(), name='knox_logout'), path(r'logoutall/', knox_views.LogoutAllView.as_view(), name='knox_logoutall'), ]","title":"Global usage on all views"},{"location":"changelog/","text":"4.3.0 Fix migration reverse flow, enable migrate 0 Various documentation fixes and improvements Drop cryptography in favor of hashlib Make custom AuthModel work Token prefix can be set in the setttings Drop support for Django 4.0 Add support for Dango 4.2, 5.0 and Python 3.11 and 3.12 Cleanup legacy Python 2.0 code Fix isort, flake8 usage for Python 3.10 in the test suite Update Github actions version Upgrade markdown dependency Get rid of the six library Add custom login / logout response support Join the jazzband organization Add pre-commit hooks Add tracking of tests code coverage Fix migrations when used in condition with a custom DB Improve typing Use self.authenticate_header() in authenticate() method to get auth header prefix 4.2.0 compatibility with Python up to 3.10 and Django up to 4.0 integration with github CI instead of travis Migration: \"salt\" field of model \"AuthToken\" is removed, WARNING: invalidates old tokens! 4.1.0 Expiry format now defaults to whatever is used Django REST framework The behavior can be overridden via EXPIRY_DATETIME_FORMAT setting Fully customizable expiry format via format_expiry_datetime Fully customizable response payload via get_post_response_data 4.0.1 Fix for tox config to build Django 2.2 on python 3.6 4.0.0 BREAKING This is a major release version because it breaks the existing API. Changes have been made to the create() method on the AuthToken model. It now returns the model instance and the raw token instead of just the token to allow the expiry field to be included in the success response. Model field of AuthToken has been renamed from expires to expiry to remain consistent across the code base. This patch requires you to run a migration. Depending on your usage you might have to adjust your code to fit these new changes. AuthToken model field has been changed from expires to expiry Successful login now always returns a expiry field for when the token expires 3.6.0 The user serializer for each LoginView is now dynamic 3.5.0 The context, token TTL and tokens per user settings in LoginView are now dynamic 3.4.0 Our release cycle was broken since 3.1.5, hence you can not find the previous releases on pypi. We now fixed the problem. Adds optional token limit #129, #128 fixed Changelog and Readme converted to markdown Auth header prefix is now configurable We ensure not to have flake8 errors in our code during our build MIN_REFRESH_INTERVAL is now a configurable setting 3.3.1 Ensure compatibility with Django 2.1 up to Python 3.7 3.3.0 Breaking changes : Successful authentication ONLY returns Token object by default now. USER_SERIALIZER must be overridden to return more data. Introduce new setting MIN_REFRESH_INTERVAL to configure the time interval (in seconds) to wait before a token is automatically refreshed. 3.2.1 Fix !111: Avoid knox failing if settings are not overwritten 3.2.0 Introduce new setting AUTO_REFRESH for controlling if token expiry time should be extended automatically 3.1.5 Make AuthTokenAdmin more compatible with big user tables Extend docs regarding usage of Token Authentication as single authentication method. 3.1.4 Fix compatibility with django-rest-swagger (bad inheritance) 3.1.3 Avoid 500 error response for invalid-length token requests 3.1.2 restore compatibility with Python <2.7.7 3.1.1 use hmac.compare_digest instead of == for comparing hashes for more security 3.1.0 drop Django 1.8 support as djangorestframework did so too in v.3.7.0 build rest-knox on Django 1.11 and 2.0 3.0.3 drop using OpenSSL in favor of urandom 3.0.2 Add context to UserSerializer improve docs 3.0.1 improved docs and readme login response better supporting hyperlinked fields 3.0.0 Please be aware: updating to this version requires applying a database migration. All clients will need to reauthenticate. Big performance fix: Introduction of token_key field to avoid having to compare a login request's token against each and every token in the database (issue #21) increased test coverage 2.2.2 Bugfix: invalid token length does no longer trigger a server error Extending documentation 2.2.1 Please be aware: updating to his version requires applying a database migration Introducing token_key to avoid loop over all tokens on login-requests Signals are sent on login/logout Test for invalid token length Cleanup in code and documentation Bugfix: invalid token length does no longer trigger a server error Extending documentation 2.2.0 Change to support python 2.7 2.0.0 Hashing of tokens on the server introduced. Updating to this version will clean the AuthToken table. In real terms, this means all users will be forced to log in again. 1.1.0 LoginView changed to respect DEFAULT_AUTHENTICATION_CLASSES 1.0.0 Initial release","title":"Changelog"},{"location":"changelog/#430","text":"Fix migration reverse flow, enable migrate 0 Various documentation fixes and improvements Drop cryptography in favor of hashlib Make custom AuthModel work Token prefix can be set in the setttings Drop support for Django 4.0 Add support for Dango 4.2, 5.0 and Python 3.11 and 3.12 Cleanup legacy Python 2.0 code Fix isort, flake8 usage for Python 3.10 in the test suite Update Github actions version Upgrade markdown dependency Get rid of the six library Add custom login / logout response support Join the jazzband organization Add pre-commit hooks Add tracking of tests code coverage Fix migrations when used in condition with a custom DB Improve typing Use self.authenticate_header() in authenticate() method to get auth header prefix","title":"4.3.0"},{"location":"changelog/#420","text":"compatibility with Python up to 3.10 and Django up to 4.0 integration with github CI instead of travis Migration: \"salt\" field of model \"AuthToken\" is removed, WARNING: invalidates old tokens!","title":"4.2.0"},{"location":"changelog/#410","text":"Expiry format now defaults to whatever is used Django REST framework The behavior can be overridden via EXPIRY_DATETIME_FORMAT setting Fully customizable expiry format via format_expiry_datetime Fully customizable response payload via get_post_response_data","title":"4.1.0"},{"location":"changelog/#401","text":"Fix for tox config to build Django 2.2 on python 3.6","title":"4.0.1"},{"location":"changelog/#400","text":"BREAKING This is a major release version because it breaks the existing API. Changes have been made to the create() method on the AuthToken model. It now returns the model instance and the raw token instead of just the token to allow the expiry field to be included in the success response. Model field of AuthToken has been renamed from expires to expiry to remain consistent across the code base. This patch requires you to run a migration. Depending on your usage you might have to adjust your code to fit these new changes. AuthToken model field has been changed from expires to expiry Successful login now always returns a expiry field for when the token expires","title":"4.0.0"},{"location":"changelog/#360","text":"The user serializer for each LoginView is now dynamic","title":"3.6.0"},{"location":"changelog/#350","text":"The context, token TTL and tokens per user settings in LoginView are now dynamic","title":"3.5.0"},{"location":"changelog/#340","text":"Our release cycle was broken since 3.1.5, hence you can not find the previous releases on pypi. We now fixed the problem. Adds optional token limit #129, #128 fixed Changelog and Readme converted to markdown Auth header prefix is now configurable We ensure not to have flake8 errors in our code during our build MIN_REFRESH_INTERVAL is now a configurable setting","title":"3.4.0"},{"location":"changelog/#331","text":"Ensure compatibility with Django 2.1 up to Python 3.7","title":"3.3.1"},{"location":"changelog/#330","text":"Breaking changes : Successful authentication ONLY returns Token object by default now. USER_SERIALIZER must be overridden to return more data. Introduce new setting MIN_REFRESH_INTERVAL to configure the time interval (in seconds) to wait before a token is automatically refreshed.","title":"3.3.0"},{"location":"changelog/#321","text":"Fix !111: Avoid knox failing if settings are not overwritten","title":"3.2.1"},{"location":"changelog/#320","text":"Introduce new setting AUTO_REFRESH for controlling if token expiry time should be extended automatically","title":"3.2.0"},{"location":"changelog/#315","text":"Make AuthTokenAdmin more compatible with big user tables Extend docs regarding usage of Token Authentication as single authentication method.","title":"3.1.5"},{"location":"changelog/#314","text":"Fix compatibility with django-rest-swagger (bad inheritance)","title":"3.1.4"},{"location":"changelog/#313","text":"Avoid 500 error response for invalid-length token requests","title":"3.1.3"},{"location":"changelog/#312","text":"restore compatibility with Python <2.7.7","title":"3.1.2"},{"location":"changelog/#311","text":"use hmac.compare_digest instead of == for comparing hashes for more security","title":"3.1.1"},{"location":"changelog/#310","text":"drop Django 1.8 support as djangorestframework did so too in v.3.7.0 build rest-knox on Django 1.11 and 2.0","title":"3.1.0"},{"location":"changelog/#303","text":"drop using OpenSSL in favor of urandom","title":"3.0.3"},{"location":"changelog/#302","text":"Add context to UserSerializer improve docs","title":"3.0.2"},{"location":"changelog/#301","text":"improved docs and readme login response better supporting hyperlinked fields","title":"3.0.1"},{"location":"changelog/#300","text":"Please be aware: updating to this version requires applying a database migration. All clients will need to reauthenticate. Big performance fix: Introduction of token_key field to avoid having to compare a login request's token against each and every token in the database (issue #21) increased test coverage","title":"3.0.0"},{"location":"changelog/#222","text":"Bugfix: invalid token length does no longer trigger a server error Extending documentation","title":"2.2.2"},{"location":"changelog/#221","text":"Please be aware: updating to his version requires applying a database migration Introducing token_key to avoid loop over all tokens on login-requests Signals are sent on login/logout Test for invalid token length Cleanup in code and documentation Bugfix: invalid token length does no longer trigger a server error Extending documentation","title":"2.2.1"},{"location":"changelog/#220","text":"Change to support python 2.7","title":"2.2.0"},{"location":"changelog/#200","text":"Hashing of tokens on the server introduced. Updating to this version will clean the AuthToken table. In real terms, this means all users will be forced to log in again.","title":"2.0.0"},{"location":"changelog/#110","text":"LoginView changed to respect DEFAULT_AUTHENTICATION_CLASSES","title":"1.1.0"},{"location":"changelog/#100","text":"Initial release","title":"1.0.0"},{"location":"installation/","text":"Installation Requirements Knox depends on pythons internal library hashlib to provide bindings to OpenSSL or uses an internal implementation of hashing algorithms for token generation. Installing Knox Knox should be installed with pip pip install django-rest-knox Setup knox Add rest_framework and knox to your INSTALLED_APPS , remove rest_framework.authtoken if you were using it. INSTALLED_APPS = ( ... 'rest_framework', 'knox', ... ) Make knox's TokenAuthentication your default authentication class for django-rest-framework: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',), ... } Add the knox url patterns to your project. If you set TokenAuthentication as the only default authentication class on the second step, override knox's LoginView to accept another authentication method and use it instead of knox's default login view. Apply the migrations for the models. python manage.py migrate","title":"Installation"},{"location":"installation/#installation","text":"","title":"Installation"},{"location":"installation/#requirements","text":"Knox depends on pythons internal library hashlib to provide bindings to OpenSSL or uses an internal implementation of hashing algorithms for token generation.","title":"Requirements"},{"location":"installation/#installing-knox","text":"Knox should be installed with pip pip install django-rest-knox","title":"Installing Knox"},{"location":"installation/#setup-knox","text":"Add rest_framework and knox to your INSTALLED_APPS , remove rest_framework.authtoken if you were using it. INSTALLED_APPS = ( ... 'rest_framework', 'knox', ... ) Make knox's TokenAuthentication your default authentication class for django-rest-framework: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',), ... } Add the knox url patterns to your project. If you set TokenAuthentication as the only default authentication class on the second step, override knox's LoginView to accept another authentication method and use it instead of knox's default login view. Apply the migrations for the models. python manage.py migrate","title":"Setup knox"},{"location":"settings/","text":"Settings knox.settings Settings in Knox are handled in a similar way to the rest framework settings. All settings are namespaced in the 'REST_KNOX' setting. Example settings.py #...snip... # These are the default values if none are set from datetime import timedelta from rest_framework.settings import api_settings KNOX_TOKEN_MODEL = 'knox.AuthToken' REST_KNOX = { 'SECURE_HASH_ALGORITHM': 'hashlib.sha512', 'AUTH_TOKEN_CHARACTER_LENGTH': 64, 'TOKEN_TTL': timedelta(hours=10), 'USER_SERIALIZER': 'knox.serializers.UserSerializer', 'TOKEN_LIMIT_PER_USER': None, 'AUTO_REFRESH': False, 'MIN_REFRESH_INTERVAL': 60, 'AUTH_HEADER_PREFIX': 'Token', 'EXPIRY_DATETIME_FORMAT': api_settings.DATETIME_FORMAT, 'TOKEN_MODEL': 'knox.AuthToken', } #...snip... KNOX_TOKEN_MODEL This is the variable used in the swappable dependency of the AuthToken model SECURE_HASH_ALGORITHM This is a reference to the class used to provide the hashing algorithm for token storage. Do not change this unless you know what you are doing By default, Knox uses SHA-512 to hash tokens in the database. hashlib.sha3_512 is an acceptable alternative setting for production use. Tests SHA-512 and SHA3-512 are secure, however, they are slow. This should not be a problem for your users, but when testing it may be noticeable (as test cases tend to use many more requests much more quickly than real users). In testing scenarios it is acceptable to use MD5 hashing ( hashlib.md5 ). MD5 is not secure and must never be used in production sites. AUTH_TOKEN_CHARACTER_LENGTH This is the length of the token that will be sent to the client. By default it is set to 64 characters (this shouldn't need changing). TOKEN_TTL This is how long a token can exist before it expires. Expired tokens are automatically removed from the system. The setting should be set to an instance of datetime.timedelta . The default is 10 hours () timedelta(hours=10) ). Setting the TOKEN_TTL to None will create tokens that never expire. Warning: setting a 0 or negative timedelta will create tokens that instantly expire, the system will not prevent you setting this. TOKEN_LIMIT_PER_USER This allows you to control how many valid tokens can be issued per user. If the limit for valid tokens is reached, an error is returned at login. By default this option is disabled and set to None -- thus no limit. USER_SERIALIZER This is the reference to the class used to serialize the User objects when successfully returning from LoginView . The default is knox.serializers.UserSerializer AUTO_REFRESH This defines if the token expiry time is extended by TOKEN_TTL each time the token is used. MIN_REFRESH_INTERVAL This is the minimum time in seconds that needs to pass for the token expiry to be updated in the database. AUTH_HEADER_PREFIX This is the Authorization header value prefix. The default is Token EXPIRY_DATETIME_FORMAT This is the expiry datetime format returned in the login view. The default is the DATETIME_FORMAT of Django REST framework. May be any of None , iso-8601 or a Python strftime format string. TOKEN_MODEL This is the reference to the model used as AuthToken . We can define a custom AuthToken model in our project that extends knox.AbstractAuthToken and add our business logic to it. The default is knox.AuthToken TOKEN_PREFIX This is the prefix for the generated token that is used in the Authorization header. The default is just an empty string. It can be up to CONSTANTS.MAXIMUM_TOKEN_PREFIX_LENGTH long. Constants knox.settings Knox also provides some constants for information. These must not be changed in external code; they are used in the model definitions in knox and an error will be raised if there is an attempt to change them. from knox.settings import CONSTANTS print(CONSTANTS.DIGEST_LENGTH) #=> 128 DIGEST_LENGTH This is the length of the digest that will be stored in the database for each token. MAXIMUM_TOKEN_PREFIX_LENGTH This is the maximum length of the token prefix.","title":"Settings"},{"location":"settings/#settings-knoxsettings","text":"Settings in Knox are handled in a similar way to the rest framework settings. All settings are namespaced in the 'REST_KNOX' setting. Example settings.py #...snip... # These are the default values if none are set from datetime import timedelta from rest_framework.settings import api_settings KNOX_TOKEN_MODEL = 'knox.AuthToken' REST_KNOX = { 'SECURE_HASH_ALGORITHM': 'hashlib.sha512', 'AUTH_TOKEN_CHARACTER_LENGTH': 64, 'TOKEN_TTL': timedelta(hours=10), 'USER_SERIALIZER': 'knox.serializers.UserSerializer', 'TOKEN_LIMIT_PER_USER': None, 'AUTO_REFRESH': False, 'MIN_REFRESH_INTERVAL': 60, 'AUTH_HEADER_PREFIX': 'Token', 'EXPIRY_DATETIME_FORMAT': api_settings.DATETIME_FORMAT, 'TOKEN_MODEL': 'knox.AuthToken', } #...snip...","title":"Settings knox.settings"},{"location":"settings/#knox_token_model","text":"This is the variable used in the swappable dependency of the AuthToken model","title":"KNOX_TOKEN_MODEL"},{"location":"settings/#secure_hash_algorithm","text":"This is a reference to the class used to provide the hashing algorithm for token storage. Do not change this unless you know what you are doing By default, Knox uses SHA-512 to hash tokens in the database. hashlib.sha3_512 is an acceptable alternative setting for production use.","title":"SECURE_HASH_ALGORITHM"},{"location":"settings/#tests","text":"SHA-512 and SHA3-512 are secure, however, they are slow. This should not be a problem for your users, but when testing it may be noticeable (as test cases tend to use many more requests much more quickly than real users). In testing scenarios it is acceptable to use MD5 hashing ( hashlib.md5 ). MD5 is not secure and must never be used in production sites.","title":"Tests"},{"location":"settings/#auth_token_character_length","text":"This is the length of the token that will be sent to the client. By default it is set to 64 characters (this shouldn't need changing).","title":"AUTH_TOKEN_CHARACTER_LENGTH"},{"location":"settings/#token_ttl","text":"This is how long a token can exist before it expires. Expired tokens are automatically removed from the system. The setting should be set to an instance of datetime.timedelta . The default is 10 hours () timedelta(hours=10) ). Setting the TOKEN_TTL to None will create tokens that never expire. Warning: setting a 0 or negative timedelta will create tokens that instantly expire, the system will not prevent you setting this.","title":"TOKEN_TTL"},{"location":"settings/#token_limit_per_user","text":"This allows you to control how many valid tokens can be issued per user. If the limit for valid tokens is reached, an error is returned at login. By default this option is disabled and set to None -- thus no limit.","title":"TOKEN_LIMIT_PER_USER"},{"location":"settings/#user_serializer","text":"This is the reference to the class used to serialize the User objects when successfully returning from LoginView . The default is knox.serializers.UserSerializer","title":"USER_SERIALIZER"},{"location":"settings/#auto_refresh","text":"This defines if the token expiry time is extended by TOKEN_TTL each time the token is used.","title":"AUTO_REFRESH"},{"location":"settings/#min_refresh_interval","text":"This is the minimum time in seconds that needs to pass for the token expiry to be updated in the database.","title":"MIN_REFRESH_INTERVAL"},{"location":"settings/#auth_header_prefix","text":"This is the Authorization header value prefix. The default is Token","title":"AUTH_HEADER_PREFIX"},{"location":"settings/#expiry_datetime_format","text":"This is the expiry datetime format returned in the login view. The default is the DATETIME_FORMAT of Django REST framework. May be any of None , iso-8601 or a Python strftime format string.","title":"EXPIRY_DATETIME_FORMAT"},{"location":"settings/#token_model","text":"This is the reference to the model used as AuthToken . We can define a custom AuthToken model in our project that extends knox.AbstractAuthToken and add our business logic to it. The default is knox.AuthToken","title":"TOKEN_MODEL"},{"location":"settings/#token_prefix","text":"This is the prefix for the generated token that is used in the Authorization header. The default is just an empty string. It can be up to CONSTANTS.MAXIMUM_TOKEN_PREFIX_LENGTH long.","title":"TOKEN_PREFIX"},{"location":"settings/#constants-knoxsettings","text":"Knox also provides some constants for information. These must not be changed in external code; they are used in the model definitions in knox and an error will be raised if there is an attempt to change them. from knox.settings import CONSTANTS print(CONSTANTS.DIGEST_LENGTH) #=> 128","title":"Constants knox.settings"},{"location":"settings/#digest_length","text":"This is the length of the digest that will be stored in the database for each token.","title":"DIGEST_LENGTH"},{"location":"settings/#maximum_token_prefix_length","text":"This is the maximum length of the token prefix.","title":"MAXIMUM_TOKEN_PREFIX_LENGTH"},{"location":"urls/","text":"URLS knox.urls Knox provides a url config ready with its three default views routed. This can easily be included in your url config: urlpatterns = [ #...snip... path(r'api/auth/', include('knox.urls')) #...snip... ] Note It is important to use the string syntax and not try to import knox.urls , as the reference to the User model will cause the app to fail at import time. The views would then accessible as: /api/auth/login -> LoginView /api/auth/logout -> LogoutView /api/auth/logoutall -> LogoutAllView they can also be looked up by name: reverse('knox_login') reverse('knox_logout') reverse('knox_logoutall')","title":"URLs"},{"location":"urls/#urls-knoxurls","text":"Knox provides a url config ready with its three default views routed. This can easily be included in your url config: urlpatterns = [ #...snip... path(r'api/auth/', include('knox.urls')) #...snip... ] Note It is important to use the string syntax and not try to import knox.urls , as the reference to the User model will cause the app to fail at import time. The views would then accessible as: /api/auth/login -> LoginView /api/auth/logout -> LogoutView /api/auth/logoutall -> LogoutAllView they can also be looked up by name: reverse('knox_login') reverse('knox_logout') reverse('knox_logoutall')","title":"URLS knox.urls"},{"location":"views/","text":"Views knox.views Knox provides three views that handle token management for you. LoginView This view accepts only a post request with an empty body. The LoginView accepts the same sort of authentication as your Rest Framework DEFAULT_AUTHENTICATION_CLASSES setting. If this is not set, it defaults to (SessionAuthentication, BasicAuthentication) . LoginView was designed to work well with Basic authentication, or similar schemes. If you would like to use a different authentication scheme to the default, you can extend this class to provide your own value for authentication_classes It is possible to customize LoginView behaviour by overriding the following helper methods: - get_context(self) , to change the context passed to the UserSerializer - get_token_ttl(self) , to change the token ttl - get_token_limit_per_user(self) , to change the number of tokens available for a user - get_user_serializer_class(self) , to change the class used for serializing the user - get_expiry_datetime_format(self) , to change the datetime format used for expiry - format_expiry_datetime(self, expiry) , to format the expiry datetime object at your convenience - create_token(self) , to create the AuthToken instance at your convenience Finally, if none of these helper methods are sufficient, you can also override get_post_response_data to return a fully customized payload. ...snip... def get_post_response_data(self, request, token, instance): UserSerializer = self.get_user_serializer_class() data = { 'expiry': self.format_expiry_datetime(instance.expiry), 'token': token } if UserSerializer is not None: data[\"user\"] = UserSerializer( request.user, context=self.get_context() ).data return data ...snip... When the endpoint authenticates a request, a json object will be returned containing the token key along with the actual value for the key by default. The success response also includes a expiry key with a timestamp for when the token expires. This is because USER_SERIALIZER setting is None by default. If you wish to return custom data upon successful authentication like first_name , last_name , and username then the included UserSerializer class can be used inside REST_KNOX settings by adding knox.serializers.UserSerializer Obviously, if your app uses a custom user model that does not have these fields, a custom serializer must be used. LogoutView This view accepts only a post request with an empty body. It responds to Knox Token Authentication. On a successful request, the token used to authenticate is deleted from the system and can no longer be used to authenticate. By default, this endpoint returns a HTTP 204 response on a successful request. To customize this behavior, you can override the get_post_response method, for example to include a body in the logout response and/or to modify the status code: ...snip... def get_post_response(self, request): return Response({\"bye-bye\": request.user.username}, status=200) ...snip... LogoutAllView This view accepts only a post request with an empty body. It responds to Knox Token Authentication. On a successful request, a HTTP 204 is returned and the token used to authenticate, and all other tokens registered to the same User account, are deleted from the system and can no longer be used to authenticate. The success response can be modified like the LogoutView by overriding the get_post_response method. Note It is not recommended to alter the Logout views. They are designed specifically for token management, and to respond to Knox authentication. Modified forms of the class may cause unpredictable results.","title":"Views"},{"location":"views/#views-knoxviews","text":"Knox provides three views that handle token management for you.","title":"Views knox.views"},{"location":"views/#loginview","text":"This view accepts only a post request with an empty body. The LoginView accepts the same sort of authentication as your Rest Framework DEFAULT_AUTHENTICATION_CLASSES setting. If this is not set, it defaults to (SessionAuthentication, BasicAuthentication) . LoginView was designed to work well with Basic authentication, or similar schemes. If you would like to use a different authentication scheme to the default, you can extend this class to provide your own value for authentication_classes It is possible to customize LoginView behaviour by overriding the following helper methods: - get_context(self) , to change the context passed to the UserSerializer - get_token_ttl(self) , to change the token ttl - get_token_limit_per_user(self) , to change the number of tokens available for a user - get_user_serializer_class(self) , to change the class used for serializing the user - get_expiry_datetime_format(self) , to change the datetime format used for expiry - format_expiry_datetime(self, expiry) , to format the expiry datetime object at your convenience - create_token(self) , to create the AuthToken instance at your convenience Finally, if none of these helper methods are sufficient, you can also override get_post_response_data to return a fully customized payload. ...snip... def get_post_response_data(self, request, token, instance): UserSerializer = self.get_user_serializer_class() data = { 'expiry': self.format_expiry_datetime(instance.expiry), 'token': token } if UserSerializer is not None: data[\"user\"] = UserSerializer( request.user, context=self.get_context() ).data return data ...snip... When the endpoint authenticates a request, a json object will be returned containing the token key along with the actual value for the key by default. The success response also includes a expiry key with a timestamp for when the token expires. This is because USER_SERIALIZER setting is None by default. If you wish to return custom data upon successful authentication like first_name , last_name , and username then the included UserSerializer class can be used inside REST_KNOX settings by adding knox.serializers.UserSerializer Obviously, if your app uses a custom user model that does not have these fields, a custom serializer must be used.","title":"LoginView"},{"location":"views/#logoutview","text":"This view accepts only a post request with an empty body. It responds to Knox Token Authentication. On a successful request, the token used to authenticate is deleted from the system and can no longer be used to authenticate. By default, this endpoint returns a HTTP 204 response on a successful request. To customize this behavior, you can override the get_post_response method, for example to include a body in the logout response and/or to modify the status code: ...snip... def get_post_response(self, request): return Response({\"bye-bye\": request.user.username}, status=200) ...snip...","title":"LogoutView"},{"location":"views/#logoutallview","text":"This view accepts only a post request with an empty body. It responds to Knox Token Authentication. On a successful request, a HTTP 204 is returned and the token used to authenticate, and all other tokens registered to the same User account, are deleted from the system and can no longer be used to authenticate. The success response can be modified like the LogoutView by overriding the get_post_response method. Note It is not recommended to alter the Logout views. They are designed specifically for token management, and to respond to Knox authentication. Modified forms of the class may cause unpredictable results.","title":"LogoutAllView"}]} \ No newline at end of file +{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Django-Rest-Knox Knox provides easy-to-use authentication for Django REST Framework The aim is to allow for common patterns in applications that are REST based, with little extra effort; and to ensure that connections remain secure. Knox authentication is token based, similar to the TokenAuthentication built into DRF. However, it overcomes some problems present in the default implementation: DRF tokens are limited to one per user. This does not facilitate securely signing in from multiple devices, as the token is shared. It also requires all devices to be logged out if a server-side logout is required (i.e. the token is deleted). Knox provides one token per call to the login view - allowing each client to have its own token which is deleted on the server side when the client logs out. Knox also provides an optional setting to limit the amount of tokens generated per user. Knox also provides an option for a logged in client to remove all tokens that the server has - forcing all clients to re-authenticate. DRF tokens are stored unencrypted in the database. This would allow an attacker unrestricted access to an account with a token if the database were compromised. Knox tokens are only stored in an encrypted form. Even if the database were somehow stolen, an attacker would not be able to log in with the stolen credentials. DRF tokens track their creation time, but have no inbuilt mechanism for tokens expiring. Knox tokens can have an expiry configured in the app settings (default is 10 hours.)","title":"Home"},{"location":"#django-rest-knox","text":"Knox provides easy-to-use authentication for Django REST Framework The aim is to allow for common patterns in applications that are REST based, with little extra effort; and to ensure that connections remain secure. Knox authentication is token based, similar to the TokenAuthentication built into DRF. However, it overcomes some problems present in the default implementation: DRF tokens are limited to one per user. This does not facilitate securely signing in from multiple devices, as the token is shared. It also requires all devices to be logged out if a server-side logout is required (i.e. the token is deleted). Knox provides one token per call to the login view - allowing each client to have its own token which is deleted on the server side when the client logs out. Knox also provides an optional setting to limit the amount of tokens generated per user. Knox also provides an option for a logged in client to remove all tokens that the server has - forcing all clients to re-authenticate. DRF tokens are stored unencrypted in the database. This would allow an attacker unrestricted access to an account with a token if the database were compromised. Knox tokens are only stored in an encrypted form. Even if the database were somehow stolen, an attacker would not be able to log in with the stolen credentials. DRF tokens track their creation time, but have no inbuilt mechanism for tokens expiring. Knox tokens can have an expiry configured in the app settings (default is 10 hours.)","title":"Django-Rest-Knox"},{"location":"auth/","text":"Authentication knox.auth Knox provides one class to handle authentication. TokenAuthentication This works using DRF's authentication system . Knox tokens should be generated using the provided views. Any APIView or ViewSet can be accessed using these tokens by adding TokenAuthentication to the View's authentication_classes . To authenticate, the Authorization header should be set on the request, with a value of the word \"Token\" , then a space, then the authentication token provided by LoginView . Example: from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from knox.auth import TokenAuthentication class ExampleView(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get(self, request, format=None): content = { 'foo': 'bar' } return Response(content) Example auth header: Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b9836F45E23A345 Tokens expire after a preset time. See settings. Global usage on all views You can activate TokenAuthentication on all your views by adding it to REST_FRAMEWORK[\"DEFAULT_AUTHENTICATION_CLASSES\"] . If it is your only default authentication class, remember to overwrite knox's LoginView, otherwise it'll not work, since the login view will require a authentication token to generate a new token, rendering it unusable. For instance, you can authenticate users using Basic Authentication by simply overwriting knox's LoginView and setting BasicAuthentication as one of the acceptable authentication classes, as follows: views.py: from knox.views import LoginView as KnoxLoginView from rest_framework.authentication import BasicAuthentication class LoginView(KnoxLoginView): authentication_classes = [BasicAuthentication] urls.py: from knox import views as knox_views from yourapp.api.views import LoginView urlpatterns = [ path(r'login/', LoginView.as_view(), name='knox_login'), path(r'logout/', knox_views.LogoutView.as_view(), name='knox_logout'), path(r'logoutall/', knox_views.LogoutAllView.as_view(), name='knox_logoutall'), ] You can use any number of authentication classes if you want to be able to authenticate using different methods (eg.: Basic and JSON) in the same view. Just be sure not to set TokenAuthentication as your only authentication class on the login view. If you decide to use Token Authentication as your only authentication class, you can overwrite knox's login view as such: views.py: from django.contrib.auth import login from rest_framework import permissions from rest_framework.authtoken.serializers import AuthTokenSerializer from knox.views import LoginView as KnoxLoginView class LoginView(KnoxLoginView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(LoginView, self).post(request, format=None) urls.py: from knox import views as knox_views from yourapp.api.views import LoginView urlpatterns = [ path(r'login/', LoginView.as_view(), name='knox_login'), path(r'logout/', knox_views.LogoutView.as_view(), name='knox_logout'), path(r'logoutall/', knox_views.LogoutAllView.as_view(), name='knox_logoutall'), ]","title":"Authentication"},{"location":"auth/#authentication-knoxauth","text":"Knox provides one class to handle authentication.","title":"Authentication knox.auth"},{"location":"auth/#tokenauthentication","text":"This works using DRF's authentication system . Knox tokens should be generated using the provided views. Any APIView or ViewSet can be accessed using these tokens by adding TokenAuthentication to the View's authentication_classes . To authenticate, the Authorization header should be set on the request, with a value of the word \"Token\" , then a space, then the authentication token provided by LoginView . Example: from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from knox.auth import TokenAuthentication class ExampleView(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get(self, request, format=None): content = { 'foo': 'bar' } return Response(content) Example auth header: Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b9836F45E23A345 Tokens expire after a preset time. See settings.","title":"TokenAuthentication"},{"location":"auth/#global-usage-on-all-views","text":"You can activate TokenAuthentication on all your views by adding it to REST_FRAMEWORK[\"DEFAULT_AUTHENTICATION_CLASSES\"] . If it is your only default authentication class, remember to overwrite knox's LoginView, otherwise it'll not work, since the login view will require a authentication token to generate a new token, rendering it unusable. For instance, you can authenticate users using Basic Authentication by simply overwriting knox's LoginView and setting BasicAuthentication as one of the acceptable authentication classes, as follows: views.py: from knox.views import LoginView as KnoxLoginView from rest_framework.authentication import BasicAuthentication class LoginView(KnoxLoginView): authentication_classes = [BasicAuthentication] urls.py: from knox import views as knox_views from yourapp.api.views import LoginView urlpatterns = [ path(r'login/', LoginView.as_view(), name='knox_login'), path(r'logout/', knox_views.LogoutView.as_view(), name='knox_logout'), path(r'logoutall/', knox_views.LogoutAllView.as_view(), name='knox_logoutall'), ] You can use any number of authentication classes if you want to be able to authenticate using different methods (eg.: Basic and JSON) in the same view. Just be sure not to set TokenAuthentication as your only authentication class on the login view. If you decide to use Token Authentication as your only authentication class, you can overwrite knox's login view as such: views.py: from django.contrib.auth import login from rest_framework import permissions from rest_framework.authtoken.serializers import AuthTokenSerializer from knox.views import LoginView as KnoxLoginView class LoginView(KnoxLoginView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) return super(LoginView, self).post(request, format=None) urls.py: from knox import views as knox_views from yourapp.api.views import LoginView urlpatterns = [ path(r'login/', LoginView.as_view(), name='knox_login'), path(r'logout/', knox_views.LogoutView.as_view(), name='knox_logout'), path(r'logoutall/', knox_views.LogoutAllView.as_view(), name='knox_logoutall'), ]","title":"Global usage on all views"},{"location":"changelog/","text":"5.0.0 Tokens created prior to this release will no longer work Fix migration reverse flow, enable migrate 0 Various documentation fixes and improvements Drop cryptography in favor of hashlib Make custom AuthModel work Token prefix can be set in the setttings Drop support for Django 4.0 Add support for Dango 4.2, 5.0 and Python 3.11 and 3.12 Cleanup legacy Python 2.0 code Fix isort, flake8 usage for Python 3.10 in the test suite Update Github actions version Upgrade markdown dependency Get rid of the six library Add custom login / logout response support Join the jazzband organization Add pre-commit hooks Add tracking of tests code coverage Fix migrations when used in condition with a custom DB Improve typing Use self.authenticate_header() in authenticate() method to get auth header prefix 4.2.0 compatibility with Python up to 3.10 and Django up to 4.0 integration with github CI instead of travis Migration: \"salt\" field of model \"AuthToken\" is removed, WARNING: invalidates old tokens! 4.1.0 Expiry format now defaults to whatever is used Django REST framework The behavior can be overridden via EXPIRY_DATETIME_FORMAT setting Fully customizable expiry format via format_expiry_datetime Fully customizable response payload via get_post_response_data 4.0.1 Fix for tox config to build Django 2.2 on python 3.6 4.0.0 BREAKING This is a major release version because it breaks the existing API. Changes have been made to the create() method on the AuthToken model. It now returns the model instance and the raw token instead of just the token to allow the expiry field to be included in the success response. Model field of AuthToken has been renamed from expires to expiry to remain consistent across the code base. This patch requires you to run a migration. Depending on your usage you might have to adjust your code to fit these new changes. AuthToken model field has been changed from expires to expiry Successful login now always returns a expiry field for when the token expires 3.6.0 The user serializer for each LoginView is now dynamic 3.5.0 The context, token TTL and tokens per user settings in LoginView are now dynamic 3.4.0 Our release cycle was broken since 3.1.5, hence you can not find the previous releases on pypi. We now fixed the problem. Adds optional token limit #129, #128 fixed Changelog and Readme converted to markdown Auth header prefix is now configurable We ensure not to have flake8 errors in our code during our build MIN_REFRESH_INTERVAL is now a configurable setting 3.3.1 Ensure compatibility with Django 2.1 up to Python 3.7 3.3.0 Breaking changes : Successful authentication ONLY returns Token object by default now. USER_SERIALIZER must be overridden to return more data. Introduce new setting MIN_REFRESH_INTERVAL to configure the time interval (in seconds) to wait before a token is automatically refreshed. 3.2.1 Fix !111: Avoid knox failing if settings are not overwritten 3.2.0 Introduce new setting AUTO_REFRESH for controlling if token expiry time should be extended automatically 3.1.5 Make AuthTokenAdmin more compatible with big user tables Extend docs regarding usage of Token Authentication as single authentication method. 3.1.4 Fix compatibility with django-rest-swagger (bad inheritance) 3.1.3 Avoid 500 error response for invalid-length token requests 3.1.2 restore compatibility with Python <2.7.7 3.1.1 use hmac.compare_digest instead of == for comparing hashes for more security 3.1.0 drop Django 1.8 support as djangorestframework did so too in v.3.7.0 build rest-knox on Django 1.11 and 2.0 3.0.3 drop using OpenSSL in favor of urandom 3.0.2 Add context to UserSerializer improve docs 3.0.1 improved docs and readme login response better supporting hyperlinked fields 3.0.0 Please be aware: updating to this version requires applying a database migration. All clients will need to reauthenticate. Big performance fix: Introduction of token_key field to avoid having to compare a login request's token against each and every token in the database (issue #21) increased test coverage 2.2.2 Bugfix: invalid token length does no longer trigger a server error Extending documentation 2.2.1 Please be aware: updating to his version requires applying a database migration Introducing token_key to avoid loop over all tokens on login-requests Signals are sent on login/logout Test for invalid token length Cleanup in code and documentation Bugfix: invalid token length does no longer trigger a server error Extending documentation 2.2.0 Change to support python 2.7 2.0.0 Hashing of tokens on the server introduced. Updating to this version will clean the AuthToken table. In real terms, this means all users will be forced to log in again. 1.1.0 LoginView changed to respect DEFAULT_AUTHENTICATION_CLASSES 1.0.0 Initial release","title":"Changelog"},{"location":"changelog/#500","text":"Tokens created prior to this release will no longer work Fix migration reverse flow, enable migrate 0 Various documentation fixes and improvements Drop cryptography in favor of hashlib Make custom AuthModel work Token prefix can be set in the setttings Drop support for Django 4.0 Add support for Dango 4.2, 5.0 and Python 3.11 and 3.12 Cleanup legacy Python 2.0 code Fix isort, flake8 usage for Python 3.10 in the test suite Update Github actions version Upgrade markdown dependency Get rid of the six library Add custom login / logout response support Join the jazzband organization Add pre-commit hooks Add tracking of tests code coverage Fix migrations when used in condition with a custom DB Improve typing Use self.authenticate_header() in authenticate() method to get auth header prefix","title":"5.0.0"},{"location":"changelog/#420","text":"compatibility with Python up to 3.10 and Django up to 4.0 integration with github CI instead of travis Migration: \"salt\" field of model \"AuthToken\" is removed, WARNING: invalidates old tokens!","title":"4.2.0"},{"location":"changelog/#410","text":"Expiry format now defaults to whatever is used Django REST framework The behavior can be overridden via EXPIRY_DATETIME_FORMAT setting Fully customizable expiry format via format_expiry_datetime Fully customizable response payload via get_post_response_data","title":"4.1.0"},{"location":"changelog/#401","text":"Fix for tox config to build Django 2.2 on python 3.6","title":"4.0.1"},{"location":"changelog/#400","text":"BREAKING This is a major release version because it breaks the existing API. Changes have been made to the create() method on the AuthToken model. It now returns the model instance and the raw token instead of just the token to allow the expiry field to be included in the success response. Model field of AuthToken has been renamed from expires to expiry to remain consistent across the code base. This patch requires you to run a migration. Depending on your usage you might have to adjust your code to fit these new changes. AuthToken model field has been changed from expires to expiry Successful login now always returns a expiry field for when the token expires","title":"4.0.0"},{"location":"changelog/#360","text":"The user serializer for each LoginView is now dynamic","title":"3.6.0"},{"location":"changelog/#350","text":"The context, token TTL and tokens per user settings in LoginView are now dynamic","title":"3.5.0"},{"location":"changelog/#340","text":"Our release cycle was broken since 3.1.5, hence you can not find the previous releases on pypi. We now fixed the problem. Adds optional token limit #129, #128 fixed Changelog and Readme converted to markdown Auth header prefix is now configurable We ensure not to have flake8 errors in our code during our build MIN_REFRESH_INTERVAL is now a configurable setting","title":"3.4.0"},{"location":"changelog/#331","text":"Ensure compatibility with Django 2.1 up to Python 3.7","title":"3.3.1"},{"location":"changelog/#330","text":"Breaking changes : Successful authentication ONLY returns Token object by default now. USER_SERIALIZER must be overridden to return more data. Introduce new setting MIN_REFRESH_INTERVAL to configure the time interval (in seconds) to wait before a token is automatically refreshed.","title":"3.3.0"},{"location":"changelog/#321","text":"Fix !111: Avoid knox failing if settings are not overwritten","title":"3.2.1"},{"location":"changelog/#320","text":"Introduce new setting AUTO_REFRESH for controlling if token expiry time should be extended automatically","title":"3.2.0"},{"location":"changelog/#315","text":"Make AuthTokenAdmin more compatible with big user tables Extend docs regarding usage of Token Authentication as single authentication method.","title":"3.1.5"},{"location":"changelog/#314","text":"Fix compatibility with django-rest-swagger (bad inheritance)","title":"3.1.4"},{"location":"changelog/#313","text":"Avoid 500 error response for invalid-length token requests","title":"3.1.3"},{"location":"changelog/#312","text":"restore compatibility with Python <2.7.7","title":"3.1.2"},{"location":"changelog/#311","text":"use hmac.compare_digest instead of == for comparing hashes for more security","title":"3.1.1"},{"location":"changelog/#310","text":"drop Django 1.8 support as djangorestframework did so too in v.3.7.0 build rest-knox on Django 1.11 and 2.0","title":"3.1.0"},{"location":"changelog/#303","text":"drop using OpenSSL in favor of urandom","title":"3.0.3"},{"location":"changelog/#302","text":"Add context to UserSerializer improve docs","title":"3.0.2"},{"location":"changelog/#301","text":"improved docs and readme login response better supporting hyperlinked fields","title":"3.0.1"},{"location":"changelog/#300","text":"Please be aware: updating to this version requires applying a database migration. All clients will need to reauthenticate. Big performance fix: Introduction of token_key field to avoid having to compare a login request's token against each and every token in the database (issue #21) increased test coverage","title":"3.0.0"},{"location":"changelog/#222","text":"Bugfix: invalid token length does no longer trigger a server error Extending documentation","title":"2.2.2"},{"location":"changelog/#221","text":"Please be aware: updating to his version requires applying a database migration Introducing token_key to avoid loop over all tokens on login-requests Signals are sent on login/logout Test for invalid token length Cleanup in code and documentation Bugfix: invalid token length does no longer trigger a server error Extending documentation","title":"2.2.1"},{"location":"changelog/#220","text":"Change to support python 2.7","title":"2.2.0"},{"location":"changelog/#200","text":"Hashing of tokens on the server introduced. Updating to this version will clean the AuthToken table. In real terms, this means all users will be forced to log in again.","title":"2.0.0"},{"location":"changelog/#110","text":"LoginView changed to respect DEFAULT_AUTHENTICATION_CLASSES","title":"1.1.0"},{"location":"changelog/#100","text":"Initial release","title":"1.0.0"},{"location":"installation/","text":"Installation Requirements Knox depends on pythons internal library hashlib to provide bindings to OpenSSL or uses an internal implementation of hashing algorithms for token generation. Installing Knox Knox should be installed with pip pip install django-rest-knox Setup knox Add rest_framework and knox to your INSTALLED_APPS , remove rest_framework.authtoken if you were using it. INSTALLED_APPS = ( ... 'rest_framework', 'knox', ... ) Make knox's TokenAuthentication your default authentication class for django-rest-framework: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',), ... } Add the knox url patterns to your project. If you set TokenAuthentication as the only default authentication class on the second step, override knox's LoginView to accept another authentication method and use it instead of knox's default login view. Apply the migrations for the models. python manage.py migrate","title":"Installation"},{"location":"installation/#installation","text":"","title":"Installation"},{"location":"installation/#requirements","text":"Knox depends on pythons internal library hashlib to provide bindings to OpenSSL or uses an internal implementation of hashing algorithms for token generation.","title":"Requirements"},{"location":"installation/#installing-knox","text":"Knox should be installed with pip pip install django-rest-knox","title":"Installing Knox"},{"location":"installation/#setup-knox","text":"Add rest_framework and knox to your INSTALLED_APPS , remove rest_framework.authtoken if you were using it. INSTALLED_APPS = ( ... 'rest_framework', 'knox', ... ) Make knox's TokenAuthentication your default authentication class for django-rest-framework: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',), ... } Add the knox url patterns to your project. If you set TokenAuthentication as the only default authentication class on the second step, override knox's LoginView to accept another authentication method and use it instead of knox's default login view. Apply the migrations for the models. python manage.py migrate","title":"Setup knox"},{"location":"settings/","text":"Settings knox.settings Settings in Knox are handled in a similar way to the rest framework settings. All settings are namespaced in the 'REST_KNOX' setting. Example settings.py #...snip... # These are the default values if none are set from datetime import timedelta from rest_framework.settings import api_settings KNOX_TOKEN_MODEL = 'knox.AuthToken' REST_KNOX = { 'SECURE_HASH_ALGORITHM': 'hashlib.sha512', 'AUTH_TOKEN_CHARACTER_LENGTH': 64, 'TOKEN_TTL': timedelta(hours=10), 'USER_SERIALIZER': 'knox.serializers.UserSerializer', 'TOKEN_LIMIT_PER_USER': None, 'AUTO_REFRESH': False, 'MIN_REFRESH_INTERVAL': 60, 'AUTH_HEADER_PREFIX': 'Token', 'EXPIRY_DATETIME_FORMAT': api_settings.DATETIME_FORMAT, 'TOKEN_MODEL': 'knox.AuthToken', } #...snip... KNOX_TOKEN_MODEL This is the variable used in the swappable dependency of the AuthToken model SECURE_HASH_ALGORITHM This is a reference to the class used to provide the hashing algorithm for token storage. Do not change this unless you know what you are doing By default, Knox uses SHA-512 to hash tokens in the database. hashlib.sha3_512 is an acceptable alternative setting for production use. Tests SHA-512 and SHA3-512 are secure, however, they are slow. This should not be a problem for your users, but when testing it may be noticeable (as test cases tend to use many more requests much more quickly than real users). In testing scenarios it is acceptable to use MD5 hashing ( hashlib.md5 ). MD5 is not secure and must never be used in production sites. AUTH_TOKEN_CHARACTER_LENGTH This is the length of the token that will be sent to the client. By default it is set to 64 characters (this shouldn't need changing). TOKEN_TTL This is how long a token can exist before it expires. Expired tokens are automatically removed from the system. The setting should be set to an instance of datetime.timedelta . The default is 10 hours () timedelta(hours=10) ). Setting the TOKEN_TTL to None will create tokens that never expire. Warning: setting a 0 or negative timedelta will create tokens that instantly expire, the system will not prevent you setting this. TOKEN_LIMIT_PER_USER This allows you to control how many valid tokens can be issued per user. If the limit for valid tokens is reached, an error is returned at login. By default this option is disabled and set to None -- thus no limit. USER_SERIALIZER This is the reference to the class used to serialize the User objects when successfully returning from LoginView . The default is knox.serializers.UserSerializer AUTO_REFRESH This defines if the token expiry time is extended by TOKEN_TTL each time the token is used. MIN_REFRESH_INTERVAL This is the minimum time in seconds that needs to pass for the token expiry to be updated in the database. AUTH_HEADER_PREFIX This is the Authorization header value prefix. The default is Token EXPIRY_DATETIME_FORMAT This is the expiry datetime format returned in the login view. The default is the DATETIME_FORMAT of Django REST framework. May be any of None , iso-8601 or a Python strftime format string. TOKEN_MODEL This is the reference to the model used as AuthToken . We can define a custom AuthToken model in our project that extends knox.AbstractAuthToken and add our business logic to it. The default is knox.AuthToken TOKEN_PREFIX This is the prefix for the generated token that is used in the Authorization header. The default is just an empty string. It can be up to CONSTANTS.MAXIMUM_TOKEN_PREFIX_LENGTH long. Constants knox.settings Knox also provides some constants for information. These must not be changed in external code; they are used in the model definitions in knox and an error will be raised if there is an attempt to change them. from knox.settings import CONSTANTS print(CONSTANTS.DIGEST_LENGTH) #=> 128 DIGEST_LENGTH This is the length of the digest that will be stored in the database for each token. MAXIMUM_TOKEN_PREFIX_LENGTH This is the maximum length of the token prefix.","title":"Settings"},{"location":"settings/#settings-knoxsettings","text":"Settings in Knox are handled in a similar way to the rest framework settings. All settings are namespaced in the 'REST_KNOX' setting. Example settings.py #...snip... # These are the default values if none are set from datetime import timedelta from rest_framework.settings import api_settings KNOX_TOKEN_MODEL = 'knox.AuthToken' REST_KNOX = { 'SECURE_HASH_ALGORITHM': 'hashlib.sha512', 'AUTH_TOKEN_CHARACTER_LENGTH': 64, 'TOKEN_TTL': timedelta(hours=10), 'USER_SERIALIZER': 'knox.serializers.UserSerializer', 'TOKEN_LIMIT_PER_USER': None, 'AUTO_REFRESH': False, 'MIN_REFRESH_INTERVAL': 60, 'AUTH_HEADER_PREFIX': 'Token', 'EXPIRY_DATETIME_FORMAT': api_settings.DATETIME_FORMAT, 'TOKEN_MODEL': 'knox.AuthToken', } #...snip...","title":"Settings knox.settings"},{"location":"settings/#knox_token_model","text":"This is the variable used in the swappable dependency of the AuthToken model","title":"KNOX_TOKEN_MODEL"},{"location":"settings/#secure_hash_algorithm","text":"This is a reference to the class used to provide the hashing algorithm for token storage. Do not change this unless you know what you are doing By default, Knox uses SHA-512 to hash tokens in the database. hashlib.sha3_512 is an acceptable alternative setting for production use.","title":"SECURE_HASH_ALGORITHM"},{"location":"settings/#tests","text":"SHA-512 and SHA3-512 are secure, however, they are slow. This should not be a problem for your users, but when testing it may be noticeable (as test cases tend to use many more requests much more quickly than real users). In testing scenarios it is acceptable to use MD5 hashing ( hashlib.md5 ). MD5 is not secure and must never be used in production sites.","title":"Tests"},{"location":"settings/#auth_token_character_length","text":"This is the length of the token that will be sent to the client. By default it is set to 64 characters (this shouldn't need changing).","title":"AUTH_TOKEN_CHARACTER_LENGTH"},{"location":"settings/#token_ttl","text":"This is how long a token can exist before it expires. Expired tokens are automatically removed from the system. The setting should be set to an instance of datetime.timedelta . The default is 10 hours () timedelta(hours=10) ). Setting the TOKEN_TTL to None will create tokens that never expire. Warning: setting a 0 or negative timedelta will create tokens that instantly expire, the system will not prevent you setting this.","title":"TOKEN_TTL"},{"location":"settings/#token_limit_per_user","text":"This allows you to control how many valid tokens can be issued per user. If the limit for valid tokens is reached, an error is returned at login. By default this option is disabled and set to None -- thus no limit.","title":"TOKEN_LIMIT_PER_USER"},{"location":"settings/#user_serializer","text":"This is the reference to the class used to serialize the User objects when successfully returning from LoginView . The default is knox.serializers.UserSerializer","title":"USER_SERIALIZER"},{"location":"settings/#auto_refresh","text":"This defines if the token expiry time is extended by TOKEN_TTL each time the token is used.","title":"AUTO_REFRESH"},{"location":"settings/#min_refresh_interval","text":"This is the minimum time in seconds that needs to pass for the token expiry to be updated in the database.","title":"MIN_REFRESH_INTERVAL"},{"location":"settings/#auth_header_prefix","text":"This is the Authorization header value prefix. The default is Token","title":"AUTH_HEADER_PREFIX"},{"location":"settings/#expiry_datetime_format","text":"This is the expiry datetime format returned in the login view. The default is the DATETIME_FORMAT of Django REST framework. May be any of None , iso-8601 or a Python strftime format string.","title":"EXPIRY_DATETIME_FORMAT"},{"location":"settings/#token_model","text":"This is the reference to the model used as AuthToken . We can define a custom AuthToken model in our project that extends knox.AbstractAuthToken and add our business logic to it. The default is knox.AuthToken","title":"TOKEN_MODEL"},{"location":"settings/#token_prefix","text":"This is the prefix for the generated token that is used in the Authorization header. The default is just an empty string. It can be up to CONSTANTS.MAXIMUM_TOKEN_PREFIX_LENGTH long.","title":"TOKEN_PREFIX"},{"location":"settings/#constants-knoxsettings","text":"Knox also provides some constants for information. These must not be changed in external code; they are used in the model definitions in knox and an error will be raised if there is an attempt to change them. from knox.settings import CONSTANTS print(CONSTANTS.DIGEST_LENGTH) #=> 128","title":"Constants knox.settings"},{"location":"settings/#digest_length","text":"This is the length of the digest that will be stored in the database for each token.","title":"DIGEST_LENGTH"},{"location":"settings/#maximum_token_prefix_length","text":"This is the maximum length of the token prefix.","title":"MAXIMUM_TOKEN_PREFIX_LENGTH"},{"location":"urls/","text":"URLS knox.urls Knox provides a url config ready with its three default views routed. This can easily be included in your url config: urlpatterns = [ #...snip... path(r'api/auth/', include('knox.urls')) #...snip... ] Note It is important to use the string syntax and not try to import knox.urls , as the reference to the User model will cause the app to fail at import time. The views would then accessible as: /api/auth/login -> LoginView /api/auth/logout -> LogoutView /api/auth/logoutall -> LogoutAllView they can also be looked up by name: reverse('knox_login') reverse('knox_logout') reverse('knox_logoutall')","title":"URLs"},{"location":"urls/#urls-knoxurls","text":"Knox provides a url config ready with its three default views routed. This can easily be included in your url config: urlpatterns = [ #...snip... path(r'api/auth/', include('knox.urls')) #...snip... ] Note It is important to use the string syntax and not try to import knox.urls , as the reference to the User model will cause the app to fail at import time. The views would then accessible as: /api/auth/login -> LoginView /api/auth/logout -> LogoutView /api/auth/logoutall -> LogoutAllView they can also be looked up by name: reverse('knox_login') reverse('knox_logout') reverse('knox_logoutall')","title":"URLS knox.urls"},{"location":"views/","text":"Views knox.views Knox provides three views that handle token management for you. LoginView This view accepts only a post request with an empty body. The LoginView accepts the same sort of authentication as your Rest Framework DEFAULT_AUTHENTICATION_CLASSES setting. If this is not set, it defaults to (SessionAuthentication, BasicAuthentication) . LoginView was designed to work well with Basic authentication, or similar schemes. If you would like to use a different authentication scheme to the default, you can extend this class to provide your own value for authentication_classes It is possible to customize LoginView behaviour by overriding the following helper methods: - get_context(self) , to change the context passed to the UserSerializer - get_token_ttl(self) , to change the token ttl - get_token_limit_per_user(self) , to change the number of tokens available for a user - get_user_serializer_class(self) , to change the class used for serializing the user - get_expiry_datetime_format(self) , to change the datetime format used for expiry - format_expiry_datetime(self, expiry) , to format the expiry datetime object at your convenience - create_token(self) , to create the AuthToken instance at your convenience Finally, if none of these helper methods are sufficient, you can also override get_post_response_data to return a fully customized payload. ...snip... def get_post_response_data(self, request, token, instance): UserSerializer = self.get_user_serializer_class() data = { 'expiry': self.format_expiry_datetime(instance.expiry), 'token': token } if UserSerializer is not None: data[\"user\"] = UserSerializer( request.user, context=self.get_context() ).data return data ...snip... When the endpoint authenticates a request, a json object will be returned containing the token key along with the actual value for the key by default. The success response also includes a expiry key with a timestamp for when the token expires. This is because USER_SERIALIZER setting is None by default. If you wish to return custom data upon successful authentication like first_name , last_name , and username then the included UserSerializer class can be used inside REST_KNOX settings by adding knox.serializers.UserSerializer Obviously, if your app uses a custom user model that does not have these fields, a custom serializer must be used. LogoutView This view accepts only a post request with an empty body. It responds to Knox Token Authentication. On a successful request, the token used to authenticate is deleted from the system and can no longer be used to authenticate. By default, this endpoint returns a HTTP 204 response on a successful request. To customize this behavior, you can override the get_post_response method, for example to include a body in the logout response and/or to modify the status code: ...snip... def get_post_response(self, request): return Response({\"bye-bye\": request.user.username}, status=200) ...snip... LogoutAllView This view accepts only a post request with an empty body. It responds to Knox Token Authentication. On a successful request, a HTTP 204 is returned and the token used to authenticate, and all other tokens registered to the same User account, are deleted from the system and can no longer be used to authenticate. The success response can be modified like the LogoutView by overriding the get_post_response method. Note It is not recommended to alter the Logout views. They are designed specifically for token management, and to respond to Knox authentication. Modified forms of the class may cause unpredictable results.","title":"Views"},{"location":"views/#views-knoxviews","text":"Knox provides three views that handle token management for you.","title":"Views knox.views"},{"location":"views/#loginview","text":"This view accepts only a post request with an empty body. The LoginView accepts the same sort of authentication as your Rest Framework DEFAULT_AUTHENTICATION_CLASSES setting. If this is not set, it defaults to (SessionAuthentication, BasicAuthentication) . LoginView was designed to work well with Basic authentication, or similar schemes. If you would like to use a different authentication scheme to the default, you can extend this class to provide your own value for authentication_classes It is possible to customize LoginView behaviour by overriding the following helper methods: - get_context(self) , to change the context passed to the UserSerializer - get_token_ttl(self) , to change the token ttl - get_token_limit_per_user(self) , to change the number of tokens available for a user - get_user_serializer_class(self) , to change the class used for serializing the user - get_expiry_datetime_format(self) , to change the datetime format used for expiry - format_expiry_datetime(self, expiry) , to format the expiry datetime object at your convenience - create_token(self) , to create the AuthToken instance at your convenience Finally, if none of these helper methods are sufficient, you can also override get_post_response_data to return a fully customized payload. ...snip... def get_post_response_data(self, request, token, instance): UserSerializer = self.get_user_serializer_class() data = { 'expiry': self.format_expiry_datetime(instance.expiry), 'token': token } if UserSerializer is not None: data[\"user\"] = UserSerializer( request.user, context=self.get_context() ).data return data ...snip... When the endpoint authenticates a request, a json object will be returned containing the token key along with the actual value for the key by default. The success response also includes a expiry key with a timestamp for when the token expires. This is because USER_SERIALIZER setting is None by default. If you wish to return custom data upon successful authentication like first_name , last_name , and username then the included UserSerializer class can be used inside REST_KNOX settings by adding knox.serializers.UserSerializer Obviously, if your app uses a custom user model that does not have these fields, a custom serializer must be used.","title":"LoginView"},{"location":"views/#logoutview","text":"This view accepts only a post request with an empty body. It responds to Knox Token Authentication. On a successful request, the token used to authenticate is deleted from the system and can no longer be used to authenticate. By default, this endpoint returns a HTTP 204 response on a successful request. To customize this behavior, you can override the get_post_response method, for example to include a body in the logout response and/or to modify the status code: ...snip... def get_post_response(self, request): return Response({\"bye-bye\": request.user.username}, status=200) ...snip...","title":"LogoutView"},{"location":"views/#logoutallview","text":"This view accepts only a post request with an empty body. It responds to Knox Token Authentication. On a successful request, a HTTP 204 is returned and the token used to authenticate, and all other tokens registered to the same User account, are deleted from the system and can no longer be used to authenticate. The success response can be modified like the LogoutView by overriding the get_post_response method. Note It is not recommended to alter the Logout views. They are designed specifically for token management, and to respond to Knox authentication. Modified forms of the class may cause unpredictable results.","title":"LogoutAllView"}]} \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index e2ead42776d2ff45afa9f3ec1b0d4d692dd107b7..99bb3ac9a22954c868cc63d79c83440fd59e5aff 100644 GIT binary patch delta 13 Ucmb=gXP58h;Ap7rnaExN039p@SpWb4 delta 13 Ucmb=gXP58h;Ar^RIFY>q03SpI!T