├── .bumpversion.cfg ├── .editorconfig ├── .github └── workflows │ ├── python-release.yml │ └── python-test.yml ├── .gitignore ├── .travis.yml ├── CHANGES ├── LICENSE ├── Makefile ├── README.rst ├── docs ├── Makefile ├── _templates │ └── sidebar-intro.html ├── conf.py ├── index.rst ├── make.bat └── requirements.txt ├── pyproject.toml ├── setup.cfg ├── setup.py ├── src └── django_cognito_jwt │ ├── __init__.py │ ├── backend.py │ └── validator.py ├── tests ├── conftest.py ├── test_backend.py ├── test_validator.py ├── urls.py └── utils.py └── tox.ini /.bumpversion.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 0.0.4 3 | commit = true 4 | tag = true 5 | tag_name = {new_version} 6 | 7 | [bumpversion:file:setup.py] 8 | 9 | [bumpversion:file:docs/conf.py] 10 | 11 | [bumpversion:file:src/django_cognito_jwt/__init__.py] 12 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*.py] 4 | line_length = 79 5 | multi_line_output = 4 6 | balanced_wrapping = true 7 | known_first_party = django_cognito_jwt,tests 8 | use_parentheses = true 9 | 10 | [*.yml] 11 | indent_size = 2 12 | 13 | 14 | [Makefile] 15 | indent_style = tab 16 | indent_size = 4 17 | -------------------------------------------------------------------------------- /.github/workflows/python-release.yml: -------------------------------------------------------------------------------- 1 | name: Release to PyPi 2 | 3 | on: 4 | release: 5 | types: [created] 6 | 7 | jobs: 8 | release: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | - name: Set up Python 3.7 13 | uses: actions/setup-python@v1 14 | with: 15 | python-version: 3.7 16 | - name: Install build requirements 17 | run: python -m pip install wheel 18 | - name: Build package 19 | run: python setup.py sdist bdist_wheel 20 | - name: Publish package 21 | uses: pypa/gh-action-pypi-publish@master 22 | with: 23 | user: __token__ 24 | password: ${{ secrets.pypi_password }} 25 | -------------------------------------------------------------------------------- /.github/workflows/python-test.yml: -------------------------------------------------------------------------------- 1 | name: Python Tests 2 | 3 | on: [push] 4 | 5 | jobs: 6 | 7 | format: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v2 11 | - name: Set up Python 3.7 12 | uses: actions/setup-python@v1 13 | with: 14 | python-version: 3.7 15 | - name: Install dependencies 16 | run: pip install tox 17 | - name: Validate formatting 18 | run: tox -e format 19 | 20 | test: 21 | runs-on: ubuntu-latest 22 | strategy: 23 | max-parallel: 4 24 | matrix: 25 | tox_env: 26 | - py36-django22 27 | - py36-django30 28 | - py37-django22 29 | - py37-django30 30 | - py38-django22 31 | - py38-django30 32 | include: 33 | - python-version: 3.6 34 | tox_env: py36-django22 35 | - python-version: 3.6 36 | tox_env: py36-django30 37 | - python-version: 3.7 38 | tox_env: py37-django22 39 | - python-version: 3.7 40 | tox_env: py37-django30 41 | - python-version: 3.8 42 | tox_env: py38-django22 43 | - python-version: 3.8 44 | tox_env: py38-django30 45 | 46 | steps: 47 | - uses: actions/checkout@v2 48 | - name: Set up Python ${{ matrix.python-version }} 49 | uses: actions/setup-python@v1 50 | with: 51 | python-version: ${{ matrix.python-version }} 52 | - name: Install dependencies 53 | run: | 54 | python -m pip install --upgrade pip 55 | pip install tox tox-gh-actions 56 | - name: Test with tox 57 | run: tox -e ${{ matrix.tox_env }} 58 | - name: Prepare artifacts 59 | run: mkdir .coverage-data && mv .coverage.* .coverage-data/ 60 | - uses: actions/upload-artifact@master 61 | with: 62 | name: coverage-data 63 | path: .coverage-data/ 64 | 65 | coverage: 66 | runs-on: ubuntu-latest 67 | needs: [test] 68 | steps: 69 | - uses: actions/checkout@v2 70 | - uses: actions/download-artifact@master 71 | with: 72 | name: coverage-data 73 | path: . 74 | - name: Set up Python 3.7 75 | uses: actions/setup-python@v1 76 | with: 77 | python-version: 3.7 78 | - name: Install dependencies 79 | run: | 80 | python -m pip install --upgrade pip 81 | pip install tox 82 | - name: Prepare Coverage report 83 | run: tox -e coverage-report 84 | - name: Upload to codecov 85 | uses: codecov/codecov-action@v1.0.6 86 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.egg-info 2 | *.pyc 3 | .tox 4 | .coverage 5 | .coverage.* 6 | .eggs 7 | .cache 8 | .python-version 9 | .venv 10 | .idea/ 11 | 12 | /build/ 13 | /dist/ 14 | /docs/_build/ 15 | /htmlcov/ 16 | 17 | 18 | # Editors 19 | .idea/ 20 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | --- 2 | sudo: false 3 | language: python 4 | 5 | matrix: 6 | include: 7 | - python: 3.6 8 | env: TOXENV=py36-django111 9 | - python: 3.6 10 | env: TOXENV=py36-django20 11 | 12 | before_cache: 13 | - rm -rf $HOME/.cache/pip/log 14 | 15 | cache: 16 | directories: 17 | - $HOME/.cache/pip 18 | 19 | deps: 20 | - codecov 21 | 22 | install: 23 | - pip install tox codecov 24 | 25 | script: 26 | - tox -e $TOXENV 27 | 28 | after_success: 29 | - tox -e coverage-report 30 | - codecov 31 | 32 | notifications: 33 | email: false 34 | -------------------------------------------------------------------------------- /CHANGES: -------------------------------------------------------------------------------- 1 | 0.0.4 (2021-12-10) 2 | ================== 3 | - Replace ugettext and smart_text with proper functions for Django 4 compatibility 4 | 5 | 0.0.3 (2019-04-15) 6 | ================== 7 | - Added User model setting 8 | - Moved TokenValidator to separate method 9 | - Formatted all code with black 10 | 11 | 0.0.2 (2019-02-28) 12 | ================== 13 | - Added caching for Cognito public keys 14 | - Return 401 response for failed authentication attempts. 15 | - Increased test coverage 16 | - Improved readme 17 | 18 | 0.0.1 (2018-01-19) 19 | ================== 20 | - Created package 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 Lab Digital 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: install test upload docs 2 | 3 | 4 | install: 5 | pip install -e .[docs,test] 6 | 7 | test: 8 | py.test 9 | 10 | retest: 11 | py.test -vvv --lf 12 | 13 | coverage: 14 | py.test --cov=django_cognito_jwt --cov-report=term-missing --cov-report=html 15 | 16 | docs: 17 | $(MAKE) -C docs html 18 | 19 | release: 20 | rm -rf dist/* 21 | python setup.py sdist bdist_wheel 22 | twine upload dist/* 23 | 24 | format: 25 | isort --recursive src tests 26 | black src/ tests/ 27 | 28 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | .. start-no-pypi 2 | .. image:: https://github.com/labd/django-cognito-jwt/workflows/Python%20Tests/badge.svg 3 | :target: https://github.com/labd/django-cognito-jwt/workflows/Python%20Tests/ 4 | 5 | .. image:: http://codecov.io/github/LabD/django-cognito-jwt/coverage.svg?branch=master 6 | :target: http://codecov.io/github/LabD/django-cognito-jwt?branch=master 7 | 8 | .. image:: https://img.shields.io/pypi/v/django-cognito-jwt.svg 9 | :target: https://pypi.python.org/pypi/django-cognito-jwt/ 10 | 11 | .. image:: https://readthedocs.org/projects/django-cognito-jwt/badge/?version=latest 12 | :target: https://django-cognito-jwt.readthedocs.io/en/latest/?badge=latest 13 | :alt: Documentation Status 14 | .. end-no-pypi 15 | 16 | 17 | Django Cognito JWT 18 | ================== 19 | 20 | An Authentication backend for Django Rest Framework for AWS Cognito JWT tokens 21 | 22 | 23 | Installation 24 | ============ 25 | 26 | .. code-block:: shell 27 | 28 | pip install django-cognito-jwt 29 | 30 | Usage 31 | ===== 32 | 33 | Add the following lines to your Django ``settings.py`` file: 34 | 35 | .. code-block:: python 36 | 37 | COGNITO_AWS_REGION = '' # 'eu-central-1' 38 | COGNITO_USER_POOL = '' # 'eu-central-1_xYzaq' 39 | COGNITO_AUDIENCE = '' 40 | 41 | (Optional) If you want to cache the Cognito public keys between requests you can 42 | enable the ``COGNITO_PUBLIC_KEYS_CACHING_ENABLED`` setting (it only works if you 43 | have the Django ``CACHES`` setup to anything other than the dummy backend). 44 | 45 | .. code-block:: python 46 | 47 | COGNITO_PUBLIC_KEYS_CACHING_ENABLED = True 48 | COGNITO_PUBLIC_KEYS_CACHING_TIMEOUT = 60*60*24 # 24h caching, default is 300s 49 | 50 | Also update the rest framework settings to use the correct authentication backend: 51 | 52 | .. code-block:: python 53 | 54 | REST_FRAMEWORK = { 55 | 'DEFAULT_AUTHENTICATION_CLASSES': [ 56 | ... 57 | 'django_cognito_jwt.JSONWebTokenAuthentication', 58 | ... 59 | ], 60 | ... 61 | } 62 | 63 | 64 | 65 | Be sure you are passing the ID Token JWT from Cognito as the authentication header. 66 | Using the Access Token will work for authentication only but we're unable to use the `get_or_create_for_cognito` method with the Access Token. 67 | 68 | 69 | (Optional) If you want to use a different user model then the default DJANGO_USER_MODEL 70 | you can use the ``COGNITO_USER_MODEL`` setting. 71 | 72 | .. code-block:: python 73 | 74 | COGNITO_USER_MODEL = "myproject.AppUser" 75 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 16 | 17 | .PHONY: help 18 | help: 19 | @echo "Please use \`make ' where is one of" 20 | @echo " html to make standalone HTML files" 21 | @echo " dirhtml to make HTML files named index.html in directories" 22 | @echo " singlehtml to make a single large HTML file" 23 | @echo " pickle to make pickle files" 24 | @echo " json to make JSON files" 25 | @echo " htmlhelp to make HTML files and a HTML help project" 26 | @echo " qthelp to make HTML files and a qthelp project" 27 | @echo " applehelp to make an Apple Help Book" 28 | @echo " devhelp to make HTML files and a Devhelp project" 29 | @echo " epub to make an epub" 30 | @echo " epub3 to make an epub3" 31 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 32 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 33 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 34 | @echo " text to make text files" 35 | @echo " man to make manual pages" 36 | @echo " texinfo to make Texinfo files" 37 | @echo " info to make Texinfo files and run them through makeinfo" 38 | @echo " gettext to make PO message catalogs" 39 | @echo " changes to make an overview of all changed/added/deprecated items" 40 | @echo " xml to make Docutils-native XML files" 41 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 42 | @echo " linkcheck to check all external links for integrity" 43 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 44 | @echo " coverage to run coverage check of the documentation (if enabled)" 45 | @echo " dummy to check syntax errors of document sources" 46 | 47 | .PHONY: clean 48 | clean: 49 | rm -rf $(BUILDDIR)/* 50 | 51 | .PHONY: html 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | .PHONY: dirhtml 58 | dirhtml: 59 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 60 | @echo 61 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 62 | 63 | .PHONY: singlehtml 64 | singlehtml: 65 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 66 | @echo 67 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 68 | 69 | .PHONY: pickle 70 | pickle: 71 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 72 | @echo 73 | @echo "Build finished; now you can process the pickle files." 74 | 75 | .PHONY: json 76 | json: 77 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 78 | @echo 79 | @echo "Build finished; now you can process the JSON files." 80 | 81 | .PHONY: htmlhelp 82 | htmlhelp: 83 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 84 | @echo 85 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 86 | ".hhp project file in $(BUILDDIR)/htmlhelp." 87 | 88 | .PHONY: qthelp 89 | qthelp: 90 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 91 | @echo 92 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 93 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 94 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/django_cognito_jwt.qhcp" 95 | @echo "To view the help file:" 96 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django_cognito_jwt.qhc" 97 | 98 | .PHONY: applehelp 99 | applehelp: 100 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 101 | @echo 102 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 103 | @echo "N.B. You won't be able to view it unless you put it in" \ 104 | "~/Library/Documentation/Help or install it in your application" \ 105 | "bundle." 106 | 107 | .PHONY: devhelp 108 | devhelp: 109 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 110 | @echo 111 | @echo "Build finished." 112 | @echo "To view the help file:" 113 | @echo "# mkdir -p $$HOME/.local/share/devhelp/django_cognito_jwt" 114 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django_cognito_jwt" 115 | @echo "# devhelp" 116 | 117 | .PHONY: epub 118 | epub: 119 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 120 | @echo 121 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 122 | 123 | .PHONY: epub3 124 | epub3: 125 | $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3 126 | @echo 127 | @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3." 128 | 129 | .PHONY: latex 130 | latex: 131 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 132 | @echo 133 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 134 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 135 | "(use \`make latexpdf' here to do that automatically)." 136 | 137 | .PHONY: latexpdf 138 | latexpdf: 139 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 140 | @echo "Running LaTeX files through pdflatex..." 141 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 142 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 143 | 144 | .PHONY: latexpdfja 145 | latexpdfja: 146 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 147 | @echo "Running LaTeX files through platex and dvipdfmx..." 148 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 149 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 150 | 151 | .PHONY: text 152 | text: 153 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 154 | @echo 155 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 156 | 157 | .PHONY: man 158 | man: 159 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 160 | @echo 161 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 162 | 163 | .PHONY: texinfo 164 | texinfo: 165 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 166 | @echo 167 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 168 | @echo "Run \`make' in that directory to run these through makeinfo" \ 169 | "(use \`make info' here to do that automatically)." 170 | 171 | .PHONY: info 172 | info: 173 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 174 | @echo "Running Texinfo files through makeinfo..." 175 | make -C $(BUILDDIR)/texinfo info 176 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 177 | 178 | .PHONY: gettext 179 | gettext: 180 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 181 | @echo 182 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 183 | 184 | .PHONY: changes 185 | changes: 186 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 187 | @echo 188 | @echo "The overview file is in $(BUILDDIR)/changes." 189 | 190 | .PHONY: linkcheck 191 | linkcheck: 192 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 193 | @echo 194 | @echo "Link check complete; look for any errors in the above output " \ 195 | "or in $(BUILDDIR)/linkcheck/output.txt." 196 | 197 | .PHONY: doctest 198 | doctest: 199 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 200 | @echo "Testing of doctests in the sources finished, look at the " \ 201 | "results in $(BUILDDIR)/doctest/output.txt." 202 | 203 | .PHONY: coverage 204 | coverage: 205 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 206 | @echo "Testing of coverage in the sources finished, look at the " \ 207 | "results in $(BUILDDIR)/coverage/python.txt." 208 | 209 | .PHONY: xml 210 | xml: 211 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 212 | @echo 213 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 214 | 215 | .PHONY: pseudoxml 216 | pseudoxml: 217 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 218 | @echo 219 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 220 | 221 | .PHONY: dummy 222 | dummy: 223 | $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy 224 | @echo 225 | @echo "Build finished. Dummy builder generates no files." 226 | -------------------------------------------------------------------------------- /docs/_templates/sidebar-intro.html: -------------------------------------------------------------------------------- 1 |

Links

2 |

3 | 5 |

6 | 11 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # django-cognito-jwt documentation build configuration file, created by 4 | # sphinx-quickstart on Wed Aug 10 17:06:14 2016. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | # If extensions (or modules to document with autodoc) are in another directory, 16 | # add these directories to sys.path here. If the directory is relative to the 17 | # documentation root, use os.path.abspath to make it absolute, like shown here. 18 | # 19 | # import os 20 | # import sys 21 | # sys.path.insert(0, os.path.abspath('.')) 22 | 23 | # -- General configuration ------------------------------------------------ 24 | 25 | # If your documentation needs a minimal Sphinx version, state it here. 26 | # 27 | # needs_sphinx = '1.0' 28 | 29 | # Add any Sphinx extension module names here, as strings. They can be 30 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 31 | # ones. 32 | extensions = ['sphinx.ext.autodoc'] 33 | 34 | # Add any paths that contain templates here, relative to this directory. 35 | templates_path = ['_templates'] 36 | 37 | # The suffix(es) of source filenames. 38 | # You can specify multiple suffix as a list of string: 39 | # 40 | # source_suffix = ['.rst', '.md'] 41 | source_suffix = '.rst' 42 | 43 | # The encoding of source files. 44 | # 45 | # source_encoding = 'utf-8-sig' 46 | 47 | # The master toctree document. 48 | master_doc = 'index' 49 | 50 | # General information about the project. 51 | project = u'django-cognito-jwt' 52 | copyright = u'Y, Michael van Tellingen' 53 | author = u'Michael van Tellingen' 54 | 55 | # The version info for the project you're documenting, acts as replacement for 56 | # |version| and |release|, also used in various other places throughout the 57 | # built documents. 58 | # 59 | version = '0.0.4' 60 | release = version 61 | 62 | # The language for content autogenerated by Sphinx. Refer to documentation 63 | # for a list of supported languages. 64 | # 65 | # This is also used if you do content translation via gettext catalogs. 66 | # Usually you set "language" from the command line for these cases. 67 | language = None 68 | 69 | # There are two options for replacing |today|: either, you set today to some 70 | # non-false value, then it is used: 71 | # 72 | # today = '' 73 | # 74 | # Else, today_fmt is used as the format for a strftime call. 75 | # 76 | # today_fmt = '%B %d, %Y' 77 | 78 | # List of patterns, relative to source directory, that match files and 79 | # directories to ignore when looking for source files. 80 | # This patterns also effect to html_static_path and html_extra_path 81 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 82 | 83 | # The reST default role (used for this markup: `text`) to use for all 84 | # documents. 85 | # 86 | # default_role = None 87 | 88 | # If true, '()' will be appended to :func: etc. cross-reference text. 89 | # 90 | # add_function_parentheses = True 91 | 92 | # If true, the current module name will be prepended to all description 93 | # unit titles (such as .. function::). 94 | # 95 | # add_module_names = True 96 | 97 | # If true, sectionauthor and moduleauthor directives will be shown in the 98 | # output. They are ignored by default. 99 | # 100 | # show_authors = False 101 | 102 | # The name of the Pygments (syntax highlighting) style to use. 103 | pygments_style = 'sphinx' 104 | 105 | # A list of ignored prefixes for module index sorting. 106 | # modindex_common_prefix = [] 107 | 108 | # If true, keep warnings as "system message" paragraphs in the built documents. 109 | # keep_warnings = False 110 | 111 | # If true, `todo` and `todoList` produce output, else they produce nothing. 112 | todo_include_todos = False 113 | 114 | 115 | # -- Options for HTML output ---------------------------------------------- 116 | 117 | # The theme to use for HTML and HTML Help pages. See the documentation for 118 | # a list of builtin themes. 119 | # 120 | html_theme = 'alabaster' 121 | 122 | # Theme options are theme-specific and customize the look and feel of a theme 123 | # further. For a list of options available for each theme, see the 124 | # documentation. 125 | # 126 | # html_theme_options = {} 127 | html_theme_options = { 128 | 'github_user': 'LabD', 129 | 'github_banner': True, 130 | 'github_repo': 'django-cognito-jwt', 131 | 'travis_button': True, 132 | 'codecov_button': True, 133 | 'analytics_id': 'UA-75907833-X', 134 | } 135 | 136 | # Add any paths that contain custom themes here, relative to this directory. 137 | # html_theme_path = [] 138 | 139 | # The name for this set of Sphinx documents. 140 | # " v documentation" by default. 141 | # 142 | # html_title = u'django-cognito-jwt v0.0.4' 143 | 144 | # A shorter title for the navigation bar. Default is the same as html_title. 145 | # 146 | # html_short_title = None 147 | 148 | # The name of an image file (relative to this directory) to place at the top 149 | # of the sidebar. 150 | # 151 | # html_logo = None 152 | 153 | # The name of an image file (relative to this directory) to use as a favicon of 154 | # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 155 | # pixels large. 156 | # 157 | # html_favicon = None 158 | 159 | # Add any paths that contain custom static files (such as style sheets) here, 160 | # relative to this directory. They are copied after the builtin static files, 161 | # so a file named "default.css" will overwrite the builtin "default.css". 162 | html_static_path = ['_static'] 163 | 164 | # Add any extra paths that contain custom files (such as robots.txt or 165 | # .htaccess) here, relative to this directory. These files are copied 166 | # directly to the root of the documentation. 167 | # 168 | # html_extra_path = [] 169 | 170 | # If not None, a 'Last updated on:' timestamp is inserted at every page 171 | # bottom, using the given strftime format. 172 | # The empty string is equivalent to '%b %d, %Y'. 173 | # 174 | # html_last_updated_fmt = None 175 | 176 | # If true, SmartyPants will be used to convert quotes and dashes to 177 | # typographically correct entities. 178 | # 179 | # html_use_smartypants = True 180 | 181 | # Custom sidebar templates, maps document names to template names. 182 | # 183 | # html_sidebars = {} 184 | # Custom sidebar templates, maps document names to template names. 185 | html_sidebars = { 186 | '*': [ 187 | 'sidebar-intro.html', 188 | ] 189 | } 190 | 191 | 192 | # Additional templates that should be rendered to pages, maps page names to 193 | # template names. 194 | # 195 | # html_additional_pages = {} 196 | 197 | # If false, no module index is generated. 198 | # 199 | # html_domain_indices = True 200 | 201 | # If false, no index is generated. 202 | # 203 | # html_use_index = True 204 | 205 | # If true, the index is split into individual pages for each letter. 206 | # 207 | # html_split_index = False 208 | 209 | # If true, links to the reST sources are added to the pages. 210 | # 211 | # html_show_sourcelink = True 212 | 213 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 214 | # 215 | # html_show_sphinx = True 216 | 217 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 218 | # 219 | # html_show_copyright = True 220 | 221 | # If true, an OpenSearch description file will be output, and all pages will 222 | # contain a tag referring to it. The value of this option must be the 223 | # base URL from which the finished HTML is served. 224 | # 225 | # html_use_opensearch = '' 226 | 227 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 228 | # html_file_suffix = None 229 | 230 | # Language to be used for generating the HTML full-text search index. 231 | # Sphinx supports the following languages: 232 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' 233 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' 234 | # 235 | # html_search_language = 'en' 236 | 237 | # A dictionary with options for the search language support, empty by default. 238 | # 'ja' uses this config value. 239 | # 'zh' user can custom change `jieba` dictionary path. 240 | # 241 | # html_search_options = {'type': 'default'} 242 | 243 | # The name of a javascript file (relative to the configuration directory) that 244 | # implements a search results scorer. If empty, the default will be used. 245 | # 246 | # html_search_scorer = 'scorer.js' 247 | 248 | # Output file base name for HTML help builder. 249 | htmlhelp_basename = 'django_cognito_jwt-doc' 250 | 251 | # -- Options for LaTeX output --------------------------------------------- 252 | 253 | latex_elements = { 254 | # The paper size ('letterpaper' or 'a4paper'). 255 | # 256 | # 'papersize': 'letterpaper', 257 | 258 | # The font size ('10pt', '11pt' or '12pt'). 259 | # 260 | # 'pointsize': '10pt', 261 | 262 | # Additional stuff for the LaTeX preamble. 263 | # 264 | # 'preamble': '', 265 | 266 | # Latex figure (float) alignment 267 | # 268 | # 'figure_align': 'htbp', 269 | } 270 | 271 | # Grouping the document tree into LaTeX files. List of tuples 272 | # (source start file, target name, title, 273 | # author, documentclass [howto, manual, or own class]). 274 | latex_documents = [ 275 | (master_doc, 'django_cognito_jwt.tex', u'django-cognito-jwt Documentation', 276 | u'Michael van Tellingen', 'manual'), 277 | ] 278 | 279 | # The name of an image file (relative to this directory) to place at the top of 280 | # the title page. 281 | # 282 | # latex_logo = None 283 | 284 | # For "manual" documents, if this is true, then toplevel headings are parts, 285 | # not chapters. 286 | # 287 | # latex_use_parts = False 288 | 289 | # If true, show page references after internal links. 290 | # 291 | # latex_show_pagerefs = False 292 | 293 | # If true, show URL addresses after external links. 294 | # 295 | # latex_show_urls = False 296 | 297 | # Documents to append as an appendix to all manuals. 298 | # 299 | # latex_appendices = [] 300 | 301 | # It false, will not define \strong, \code, itleref, \crossref ... but only 302 | # \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added 303 | # packages. 304 | # 305 | # latex_keep_old_macro_names = True 306 | 307 | # If false, no module index is generated. 308 | # 309 | # latex_domain_indices = True 310 | 311 | 312 | # -- Options for manual page output --------------------------------------- 313 | 314 | # One entry per manual page. List of tuples 315 | # (source start file, name, description, authors, manual section). 316 | man_pages = [ 317 | (master_doc, 'django_cognito_jwt', u'django-cognito-jwt Documentation', 318 | [author], 1) 319 | ] 320 | 321 | # If true, show URL addresses after external links. 322 | # 323 | # man_show_urls = False 324 | 325 | 326 | # -- Options for Texinfo output ------------------------------------------- 327 | 328 | # Grouping the document tree into Texinfo files. List of tuples 329 | # (source start file, target name, title, author, 330 | # dir menu entry, description, category) 331 | texinfo_documents = [ 332 | (master_doc, 'django_cognito_jwt', u'django-cognito-jwt Documentation', 333 | author, 'django_cognito_jwt', 'One line description of project.', 334 | 'Miscellaneous'), 335 | ] 336 | 337 | # Documents to append as an appendix to all manuals. 338 | # 339 | # texinfo_appendices = [] 340 | 341 | # If false, no module index is generated. 342 | # 343 | # texinfo_domain_indices = True 344 | 345 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 346 | # 347 | # texinfo_show_urls = 'footnote' 348 | 349 | # If true, do not generate a @detailmenu in the "Top" node's menu. 350 | # 351 | # texinfo_no_detailmenu = False 352 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | =================== 2 | django-cognito-jwt 3 | =================== 4 | 5 | 6 | Installation 7 | ============ 8 | 9 | .. code-block:: shell 10 | 11 | pip install django-cognito-jwt 12 | 13 | Usage 14 | ===== 15 | 16 | Add the following lines to your Django ``settings.py`` file: 17 | 18 | .. code-block:: python 19 | 20 | COGNITO_AWS_REGION = '' # 'eu-central-1' 21 | COGNITO_USER_POOL = '' # 'eu-central-1_xYzaq' 22 | COGNITO_AUDIENCE = '' 23 | 24 | (Optional) If you want to cache the Cognito public keys between requests you can 25 | enable the ``COGNITO_PUBLIC_KEYS_CACHING_ENABLED`` setting (it only works if you 26 | have the Django ``CACHES`` setup to anything other than the dummy backend). 27 | 28 | .. code-block:: python 29 | 30 | COGNITO_PUBLIC_KEYS_CACHING_ENABLED = True 31 | COGNITO_PUBLIC_KEYS_CACHING_TIMEOUT = 60*60*24 # 24h caching, default is 300s 32 | 33 | Also update the rest framework settings to use the correct authentication backend: 34 | 35 | .. code-block:: python 36 | 37 | REST_FRAMEWORK = { 38 | 'DEFAULT_AUTHENTICATION_CLASSES': [ 39 | ... 40 | 'django_cognito_jwt.JSONWebTokenAuthentication', 41 | ... 42 | ], 43 | ... 44 | } 45 | 46 | 47 | 48 | Be sure you are passing the ID Token JWT from Cognito as the authentication header. 49 | Using the Access Token will work for authentication only but we're unable to use the `get_or_create_for_cognito` method with the Access Token. 50 | 51 | 52 | (Optional) If you want to use a different user model then the default DJANGO_USER_MODEL 53 | you can use the ``COGNITO_USER_MODEL`` setting. 54 | 55 | .. code-block:: python 56 | 57 | COGNITO_USER_MODEL = "myproject.AppUser" 58 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. epub3 to make an epub3 31 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 32 | echo. text to make text files 33 | echo. man to make manual pages 34 | echo. texinfo to make Texinfo files 35 | echo. gettext to make PO message catalogs 36 | echo. changes to make an overview over all changed/added/deprecated items 37 | echo. xml to make Docutils-native XML files 38 | echo. pseudoxml to make pseudoxml-XML files for display purposes 39 | echo. linkcheck to check all external links for integrity 40 | echo. doctest to run all doctests embedded in the documentation if enabled 41 | echo. coverage to run coverage check of the documentation if enabled 42 | echo. dummy to check syntax errors of document sources 43 | goto end 44 | ) 45 | 46 | if "%1" == "clean" ( 47 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 48 | del /q /s %BUILDDIR%\* 49 | goto end 50 | ) 51 | 52 | 53 | REM Check if sphinx-build is available and fallback to Python version if any 54 | %SPHINXBUILD% 1>NUL 2>NUL 55 | if errorlevel 9009 goto sphinx_python 56 | goto sphinx_ok 57 | 58 | :sphinx_python 59 | 60 | set SPHINXBUILD=python -m sphinx.__init__ 61 | %SPHINXBUILD% 2> nul 62 | if errorlevel 9009 ( 63 | echo. 64 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 65 | echo.installed, then set the SPHINXBUILD environment variable to point 66 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 67 | echo.may add the Sphinx directory to PATH. 68 | echo. 69 | echo.If you don't have Sphinx installed, grab it from 70 | echo.http://sphinx-doc.org/ 71 | exit /b 1 72 | ) 73 | 74 | :sphinx_ok 75 | 76 | 77 | if "%1" == "html" ( 78 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 79 | if errorlevel 1 exit /b 1 80 | echo. 81 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 82 | goto end 83 | ) 84 | 85 | if "%1" == "dirhtml" ( 86 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 87 | if errorlevel 1 exit /b 1 88 | echo. 89 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 90 | goto end 91 | ) 92 | 93 | if "%1" == "singlehtml" ( 94 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 95 | if errorlevel 1 exit /b 1 96 | echo. 97 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 98 | goto end 99 | ) 100 | 101 | if "%1" == "pickle" ( 102 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 103 | if errorlevel 1 exit /b 1 104 | echo. 105 | echo.Build finished; now you can process the pickle files. 106 | goto end 107 | ) 108 | 109 | if "%1" == "json" ( 110 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 111 | if errorlevel 1 exit /b 1 112 | echo. 113 | echo.Build finished; now you can process the JSON files. 114 | goto end 115 | ) 116 | 117 | if "%1" == "htmlhelp" ( 118 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 119 | if errorlevel 1 exit /b 1 120 | echo. 121 | echo.Build finished; now you can run HTML Help Workshop with the ^ 122 | .hhp project file in %BUILDDIR%/htmlhelp. 123 | goto end 124 | ) 125 | 126 | if "%1" == "qthelp" ( 127 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 128 | if errorlevel 1 exit /b 1 129 | echo. 130 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 131 | .qhcp project file in %BUILDDIR%/qthelp, like this: 132 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\django_cognito_jwt.qhcp 133 | echo.To view the help file: 134 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\django_cognito_jwt.ghc 135 | goto end 136 | ) 137 | 138 | if "%1" == "devhelp" ( 139 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 140 | if errorlevel 1 exit /b 1 141 | echo. 142 | echo.Build finished. 143 | goto end 144 | ) 145 | 146 | if "%1" == "epub" ( 147 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 148 | if errorlevel 1 exit /b 1 149 | echo. 150 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 151 | goto end 152 | ) 153 | 154 | if "%1" == "epub3" ( 155 | %SPHINXBUILD% -b epub3 %ALLSPHINXOPTS% %BUILDDIR%/epub3 156 | if errorlevel 1 exit /b 1 157 | echo. 158 | echo.Build finished. The epub3 file is in %BUILDDIR%/epub3. 159 | goto end 160 | ) 161 | 162 | if "%1" == "latex" ( 163 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 164 | if errorlevel 1 exit /b 1 165 | echo. 166 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 167 | goto end 168 | ) 169 | 170 | if "%1" == "latexpdf" ( 171 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 172 | cd %BUILDDIR%/latex 173 | make all-pdf 174 | cd %~dp0 175 | echo. 176 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 177 | goto end 178 | ) 179 | 180 | if "%1" == "latexpdfja" ( 181 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 182 | cd %BUILDDIR%/latex 183 | make all-pdf-ja 184 | cd %~dp0 185 | echo. 186 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 187 | goto end 188 | ) 189 | 190 | if "%1" == "text" ( 191 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 192 | if errorlevel 1 exit /b 1 193 | echo. 194 | echo.Build finished. The text files are in %BUILDDIR%/text. 195 | goto end 196 | ) 197 | 198 | if "%1" == "man" ( 199 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 200 | if errorlevel 1 exit /b 1 201 | echo. 202 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 203 | goto end 204 | ) 205 | 206 | if "%1" == "texinfo" ( 207 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 208 | if errorlevel 1 exit /b 1 209 | echo. 210 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 211 | goto end 212 | ) 213 | 214 | if "%1" == "gettext" ( 215 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 216 | if errorlevel 1 exit /b 1 217 | echo. 218 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 219 | goto end 220 | ) 221 | 222 | if "%1" == "changes" ( 223 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 224 | if errorlevel 1 exit /b 1 225 | echo. 226 | echo.The overview file is in %BUILDDIR%/changes. 227 | goto end 228 | ) 229 | 230 | if "%1" == "linkcheck" ( 231 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 232 | if errorlevel 1 exit /b 1 233 | echo. 234 | echo.Link check complete; look for any errors in the above output ^ 235 | or in %BUILDDIR%/linkcheck/output.txt. 236 | goto end 237 | ) 238 | 239 | if "%1" == "doctest" ( 240 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 241 | if errorlevel 1 exit /b 1 242 | echo. 243 | echo.Testing of doctests in the sources finished, look at the ^ 244 | results in %BUILDDIR%/doctest/output.txt. 245 | goto end 246 | ) 247 | 248 | if "%1" == "coverage" ( 249 | %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage 250 | if errorlevel 1 exit /b 1 251 | echo. 252 | echo.Testing of coverage in the sources finished, look at the ^ 253 | results in %BUILDDIR%/coverage/python.txt. 254 | goto end 255 | ) 256 | 257 | if "%1" == "xml" ( 258 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 259 | if errorlevel 1 exit /b 1 260 | echo. 261 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 262 | goto end 263 | ) 264 | 265 | if "%1" == "pseudoxml" ( 266 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 267 | if errorlevel 1 exit /b 1 268 | echo. 269 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 270 | goto end 271 | ) 272 | 273 | if "%1" == "dummy" ( 274 | %SPHINXBUILD% -b dummy %ALLSPHINXOPTS% %BUILDDIR%/dummy 275 | if errorlevel 1 exit /b 1 276 | echo. 277 | echo.Build finished. Dummy builder generates no files. 278 | goto end 279 | ) 280 | 281 | :end 282 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | -e .[docs] 2 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | 2 | [build-system] 3 | requires = ["setuptools>=40.6.0", "wheel"] 4 | build-backend = "setuptools.build_meta" 5 | 6 | [tool.coverage.run] 7 | branch = true 8 | source = ["django_cognito_jwt"] 9 | 10 | [tool.coverage.paths] 11 | source = ["src", ".tox/*/site-packages"] 12 | 13 | [tool.coverage.report] 14 | show_missing = true 15 | 16 | [tool.isort] 17 | line_length = 88 18 | multi_line_output = 3 19 | include_trailing_comma = true 20 | balanced_wrapping = true 21 | default_section = "THIRDPARTY" 22 | known_first_party = ["django_cognito_jwt", "tests"] 23 | use_parentheses = true 24 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [tool:pytest] 2 | minversion = 3.0 3 | strict = true 4 | testpaths = tests 5 | 6 | [wheel] 7 | universal = 1 8 | 9 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import find_packages, setup 2 | 3 | install_requires = [ 4 | "Django>=1.11", 5 | "cryptography", 6 | "djangorestframework", 7 | "pyjwt", 8 | "requests", 9 | ] 10 | 11 | docs_require = [ 12 | "sphinx>=1.4.0", 13 | ] 14 | 15 | tests_require = [ 16 | "coverage[toml]==5.0.3", 17 | "pytest==5.3.5", 18 | "pytest-django==3.8.0", 19 | "pytest-cov==2.8.1", 20 | "pytest-responses==0.4.0", 21 | # Linting 22 | "isort[pyproject]==4.3.21", 23 | "flake8==3.7.9", 24 | "flake8-imports==0.1.1", 25 | "flake8-blind-except==0.1.1", 26 | "flake8-debugger==3.1.0", 27 | ] 28 | 29 | setup( 30 | name="django-cognito-jwt", 31 | version="0.0.4", 32 | description="Django backends for AWS Cognito JWT", 33 | long_description=open("README.rst", "r").read(), 34 | url="https://github.com/LabD/django-cognito-jwt", 35 | author="Michael van Tellingen", 36 | author_email="m.vantellingen@labdigital.nl", 37 | install_requires=install_requires, 38 | extras_require={"docs": docs_require, "test": tests_require,}, 39 | use_scm_version=True, 40 | entry_points={}, 41 | package_dir={"": "src"}, 42 | packages=find_packages("src"), 43 | include_package_data=True, 44 | license="MIT", 45 | classifiers=[ 46 | "Development Status :: 5 - Production/Stable", 47 | "Environment :: Web Environment", 48 | "Framework :: Django", 49 | "Framework :: Django :: 1.11", 50 | "License :: OSI Approved :: MIT License", 51 | "Programming Language :: Python", 52 | "Programming Language :: Python :: 3", 53 | "Programming Language :: Python :: 3.6", 54 | "Programming Language :: Python :: 3.7", 55 | "Programming Language :: Python :: 3.8", 56 | ], 57 | zip_safe=False, 58 | ) 59 | -------------------------------------------------------------------------------- /src/django_cognito_jwt/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.0.4" 2 | 3 | from .backend import JSONWebTokenAuthentication # noqa 4 | -------------------------------------------------------------------------------- /src/django_cognito_jwt/backend.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from django.apps import apps as django_apps 4 | from django.conf import settings 5 | from django.utils.encoding import force_str 6 | from django.utils.translation import gettext as _ 7 | from rest_framework import exceptions 8 | from rest_framework.authentication import BaseAuthentication, get_authorization_header 9 | 10 | from django_cognito_jwt.validator import TokenError, TokenValidator 11 | 12 | logger = logging.getLogger(__name__) 13 | 14 | 15 | class JSONWebTokenAuthentication(BaseAuthentication): 16 | """Token based authentication using the JSON Web Token standard.""" 17 | 18 | def authenticate(self, request): 19 | """Entrypoint for Django Rest Framework""" 20 | jwt_token = self.get_jwt_token(request) 21 | if jwt_token is None: 22 | return None 23 | 24 | # Authenticate token 25 | try: 26 | token_validator = self.get_token_validator(request) 27 | jwt_payload = token_validator.validate(jwt_token) 28 | except TokenError: 29 | raise exceptions.AuthenticationFailed() 30 | 31 | USER_MODEL = self.get_user_model() 32 | user = USER_MODEL.objects.get_or_create_for_cognito(jwt_payload) 33 | return (user, jwt_token) 34 | 35 | def get_user_model(self): 36 | user_model = getattr(settings, "COGNITO_USER_MODEL", settings.AUTH_USER_MODEL) 37 | return django_apps.get_model(user_model, require_ready=False) 38 | 39 | def get_jwt_token(self, request): 40 | auth = get_authorization_header(request).split() 41 | if not auth or force_str(auth[0].lower()) != "bearer": 42 | return None 43 | 44 | if len(auth) == 1: 45 | msg = _("Invalid Authorization header. No credentials provided.") 46 | raise exceptions.AuthenticationFailed(msg) 47 | elif len(auth) > 2: 48 | msg = _( 49 | "Invalid Authorization header. Credentials string " 50 | "should not contain spaces." 51 | ) 52 | raise exceptions.AuthenticationFailed(msg) 53 | 54 | return auth[1] 55 | 56 | def get_token_validator(self, request): 57 | return TokenValidator( 58 | settings.COGNITO_AWS_REGION, 59 | settings.COGNITO_USER_POOL, 60 | settings.COGNITO_AUDIENCE, 61 | ) 62 | 63 | def authenticate_header(self, request): 64 | """ 65 | Method required by the DRF in order to return 401 responses for authentication failures, instead of 403. 66 | More details in https://www.django-rest-framework.org/api-guide/authentication/#custom-authentication. 67 | """ 68 | return "Bearer: api" 69 | -------------------------------------------------------------------------------- /src/django_cognito_jwt/validator.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | import jwt 4 | import requests 5 | from django.conf import settings 6 | from django.core.cache import cache 7 | from django.utils.functional import cached_property 8 | from jwt.algorithms import RSAAlgorithm 9 | 10 | 11 | class TokenError(Exception): 12 | pass 13 | 14 | 15 | class TokenValidator: 16 | def __init__(self, aws_region, aws_user_pool, audience): 17 | self.aws_region = aws_region 18 | self.aws_user_pool = aws_user_pool 19 | self.audience = audience 20 | 21 | @cached_property 22 | def pool_url(self): 23 | return "https://cognito-idp.%s.amazonaws.com/%s" % ( 24 | self.aws_region, 25 | self.aws_user_pool, 26 | ) 27 | 28 | @cached_property 29 | def _json_web_keys(self): 30 | response = requests.get(self.pool_url + "/.well-known/jwks.json") 31 | response.raise_for_status() 32 | json_data = response.json() 33 | return {item["kid"]: json.dumps(item) for item in json_data["keys"]} 34 | 35 | def _get_public_key(self, token): 36 | try: 37 | headers = jwt.get_unverified_header(token) 38 | except jwt.DecodeError as exc: 39 | raise TokenError(str(exc)) 40 | 41 | if getattr(settings, "COGNITO_PUBLIC_KEYS_CACHING_ENABLED", False): 42 | cache_key = "django_cognito_jwt:%s" % headers["kid"] 43 | jwk_data = cache.get(cache_key) 44 | 45 | if not jwk_data: 46 | jwk_data = self._json_web_keys.get(headers["kid"]) 47 | timeout = getattr(settings, "COGNITO_PUBLIC_KEYS_CACHING_TIMEOUT", 300) 48 | cache.set(cache_key, jwk_data, timeout=timeout) 49 | else: 50 | jwk_data = self._json_web_keys.get(headers["kid"]) 51 | 52 | if jwk_data: 53 | return RSAAlgorithm.from_jwk(jwk_data) 54 | 55 | def validate(self, token): 56 | public_key = self._get_public_key(token) 57 | if not public_key: 58 | raise TokenError("No key found for this token") 59 | 60 | try: 61 | jwt_data = jwt.decode( 62 | token, 63 | public_key, 64 | audience=self.audience, 65 | issuer=self.pool_url, 66 | algorithms=["RS256"], 67 | ) 68 | except ( 69 | jwt.InvalidTokenError, 70 | jwt.ExpiredSignatureError, 71 | jwt.DecodeError, 72 | ) as exc: 73 | raise TokenError(str(exc)) 74 | return jwt_data 75 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | import copy 2 | 3 | import pytest 4 | from django.conf import settings 5 | 6 | 7 | def pytest_configure(): 8 | settings.configure( 9 | COGNITO_AWS_REGION="eu-central-1", 10 | COGNITO_USER_POOL="bla", 11 | COGNITO_AUDIENCE="my-client-id", 12 | INSTALLED_APPS=["django.contrib.auth", "django.contrib.contenttypes"], 13 | MIDDLEWARE_CLASSES=[], 14 | CACHES={ 15 | "default": { 16 | "BACKEND": "django.core.cache.backends.locmem.LocMemCache", 17 | "LOCATION": "unique-snowflake", 18 | } 19 | }, 20 | DATABASES={ 21 | "default": {"ENGINE": "django.db.backends.sqlite3", "NAME": "db.sqlite"} 22 | }, 23 | ROOT_URLCONF="urls", 24 | ) 25 | 26 | 27 | def _private_to_public_key(private_key): 28 | data = copy.deepcopy(private_key) 29 | del data["d"] 30 | return data 31 | 32 | 33 | @pytest.fixture() 34 | def jwk_private_key_one(): 35 | return { 36 | "kty": "RSA", 37 | "d": ( 38 | "YKOGWFXP3-wWK1OqrKVoTQ5gjkLJPfn2V2ia1tWZ2Ety20W9fpcQmNuS8U" 39 | "bkl86laVergyup8mE0ZpymxXeNRBYI9MrB_k9DCvpnbxW-S3RN8lT1CxZY" 40 | "oUPK8spaO5V5StMfZFesAbwhVIK_flp1NUynM3BkRZ-rRPaDS1Ynz-Z8ag" 41 | "oFAoz3sf946JitajgIyAJUF8wy8j-heXYdOHXeHebBZPvr5bET8hPxapmG" 42 | "gr2_JpKYQbzJ1Emnn1RlTRqdaUWLLKf-XaiemlB2TLNq5YKg-Cr5yIBfro" 43 | "gjhGwh0yGXbuTXzn0QWR3MYoAU9BxHq9vzl-X1ZcF1GqPqOBPigQ" 44 | ), 45 | "e": "AQAB", 46 | "use": "sig", 47 | "kid": "key-one", 48 | "alg": "RS256", 49 | "n": ( 50 | "iN7iEEFIhcXYFg0ZxvB_etEwN9-ZgA2-g-WzTpcG2qLKjj2rDr80rGPY7I" 51 | "fXaEDppME9ZcN-Mw8oUxSBUIllMNpE9dA0XUhuklFDDiF02FShj2jwua-A" 52 | "k3ORMIgf2ujGPO-b1rkmEKc6TFu_w5jfum9eocaVVIdqYr2j9mG1UCqI0m" 53 | "d-JuGOZi1_f4hp67Qbve_Bzh_3yvQWsTegFNjp55-MzUX-VZ-IEYqhuzaV" 54 | "70t0rnnqFrYgnPqrwo03MOGHUhSJTyg0vBO4S-FoW0e8YKVU1CIOClCuiB" 55 | "qsjkpRBst1DG9094K_PRFcEszIlwt1NUHDMGQV1gHg3zebXxKumQ" 56 | ), 57 | } 58 | 59 | 60 | @pytest.fixture() 61 | def jwk_public_key_one(jwk_private_key_one): 62 | return _private_to_public_key(jwk_private_key_one) 63 | 64 | 65 | @pytest.fixture() 66 | def jwk_private_key_two(): 67 | return { 68 | "kty": "RSA", 69 | "d": ( 70 | "G0-8DUpJmbgnYLVCkKTx481skS7DRS4HZlpwHaqzYZn97tVz9sZ_wJmYK1" 71 | "ejaZ_n2K6474zutmx2_XOXNdJJkxdbmi_HwF7V0Ha3R-kPiOUcL0FMI2vC" 72 | "DOjXN8zQG42GYRq1bcrXRBJbSQQK70SiXesv5v1krB0LLr1P8aQTtQw70h" 73 | "xO1avoeeueKhfHET8tIzVlvXz5s4N0s1fH1C-9Z82vTsqyMo51aBqFjPfB" 74 | "Yc0k-AjrrQsVqmvWAXW-7nTiBRdMkZ8Jes1rNnJWYliGmepZbOBQRqEu-I" 75 | "epvAujPdVSsSnQa1zgRKVOgH4KEGVfVtoNY3HoQGaZ5GhiD5BHgQ" 76 | ), 77 | "e": "AQAB", 78 | "use": "sig", 79 | "kid": "key-two", 80 | "alg": "RS256", 81 | "n": ( 82 | "hvHv4nocfMqZB6e-paozbjr9MaCqOmOtoiiUEwvBPbXgrBH2-MpkzsV_A7" 83 | "OzcMc1R8UMoLE4k4QedFCwM3HwC8CrasH3qkd0GPJA0py1Toa8w7v5TB5e" 84 | "WmGpi_eBjRQcEyq9xVUE637oIfSmgp3U0QOp4px7FpNw8QhP9eMTUnSo_u" 85 | "vsN-dASz4h1U-fBVktT-9yfPBbjq7BER3OjIuVlRAFrptK8xdG1XZtzxdC" 86 | "6O9CGneDwKDcJS-43PGzjyaz4YIRPBPxysZ0veyKxpD-AcC-qAPf0EWdQG" 87 | "6ik-2wNn-5FIHm01MGNcnh6ntuoyZefA3FRjlvuDrwhz2joE6iqw" 88 | ), 89 | } 90 | 91 | 92 | @pytest.fixture() 93 | def jwk_public_key_two(jwk_private_key_two): 94 | return _private_to_public_key(jwk_private_key_two) 95 | 96 | 97 | @pytest.fixture() 98 | def cognito_well_known_keys(responses, jwk_public_key_one, jwk_public_key_two): 99 | jwk_keys = {"keys": [jwk_public_key_one]} 100 | responses.add( 101 | responses.GET, 102 | "https://cognito-idp.eu-central-1.amazonaws.com/bla/.well-known/jwks.json", 103 | json=jwk_keys, 104 | status=200, 105 | ) 106 | -------------------------------------------------------------------------------- /tests/test_backend.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from django.conf import settings 3 | from django.contrib.auth import get_user_model 4 | from django.test import Client 5 | from rest_framework import status 6 | from rest_framework.exceptions import AuthenticationFailed 7 | from utils import create_jwt_token 8 | 9 | from django_cognito_jwt import backend 10 | 11 | USER_MODEL = get_user_model() 12 | 13 | 14 | def test_authenticate_no_token(rf): 15 | request = rf.get("/") 16 | auth = backend.JSONWebTokenAuthentication() 17 | assert auth.authenticate(request) is None 18 | 19 | 20 | def test_authenticate_valid( 21 | rf, monkeypatch, cognito_well_known_keys, jwk_private_key_one 22 | ): 23 | token = create_jwt_token( 24 | jwk_private_key_one, 25 | { 26 | "iss": "https://cognito-idp.eu-central-1.amazonaws.com/bla", 27 | "aud": settings.COGNITO_AUDIENCE, 28 | "sub": "username", 29 | }, 30 | ) 31 | 32 | def func(payload): 33 | return USER_MODEL(username=payload["sub"]) 34 | 35 | monkeypatch.setattr( 36 | USER_MODEL.objects, "get_or_create_for_cognito", func, raising=False 37 | ) 38 | 39 | request = rf.get("/", HTTP_AUTHORIZATION=b"bearer %s" % token.encode("utf8")) 40 | auth = backend.JSONWebTokenAuthentication() 41 | user, auth_token = auth.authenticate(request) 42 | assert user 43 | assert user.username == "username" 44 | assert auth_token == token.encode("utf8") 45 | 46 | 47 | def test_authenticate_invalid(rf, cognito_well_known_keys, jwk_private_key_two): 48 | token = create_jwt_token( 49 | jwk_private_key_two, 50 | { 51 | "iss": "https://cognito-idp.eu-central-1.amazonaws.com/bla", 52 | "aud": settings.COGNITO_AUDIENCE, 53 | "sub": "username", 54 | }, 55 | ) 56 | 57 | request = rf.get("/", HTTP_AUTHORIZATION=b"bearer %s" % token.encode("utf8")) 58 | auth = backend.JSONWebTokenAuthentication() 59 | 60 | with pytest.raises(AuthenticationFailed): 61 | auth.authenticate(request) 62 | 63 | 64 | def test_authenticate_error_segments(rf): 65 | request = rf.get("/", HTTP_AUTHORIZATION=b"bearer randomiets") 66 | auth = backend.JSONWebTokenAuthentication() 67 | 68 | with pytest.raises(AuthenticationFailed): 69 | auth.authenticate(request) 70 | 71 | 72 | def test_authenticate_error_invalid_header(rf): 73 | request = rf.get("/", HTTP_AUTHORIZATION=b"bearer") 74 | auth = backend.JSONWebTokenAuthentication() 75 | 76 | with pytest.raises(AuthenticationFailed): 77 | auth.authenticate(request) 78 | 79 | 80 | def test_authenticate_error_spaces(rf): 81 | request = rf.get("/", HTTP_AUTHORIZATION=b"bearer random iets") 82 | auth = backend.JSONWebTokenAuthentication() 83 | 84 | with pytest.raises(AuthenticationFailed): 85 | auth.authenticate(request) 86 | 87 | 88 | def test_authenticate_error_response_code(): 89 | client = Client() 90 | resp = client.get("/", HTTP_AUTHORIZATION=b"bearer random iets") 91 | 92 | assert resp.status_code == status.HTTP_401_UNAUTHORIZED 93 | -------------------------------------------------------------------------------- /tests/test_validator.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from utils import create_jwt_token 3 | 4 | from django_cognito_jwt import validator 5 | 6 | 7 | def test_validate_token(cognito_well_known_keys, jwk_private_key_one): 8 | token = create_jwt_token( 9 | jwk_private_key_one, 10 | { 11 | "iss": "https://cognito-idp.eu-central-1.amazonaws.com/bla", 12 | "aud": "my-audience", 13 | "sub": "username", 14 | }, 15 | ) 16 | auth = validator.TokenValidator("eu-central-1", "bla", "my-audience") 17 | auth.validate(token) 18 | 19 | 20 | def test_validate_token_error_key(cognito_well_known_keys, jwk_private_key_two): 21 | token = create_jwt_token( 22 | jwk_private_key_two, 23 | { 24 | "iss": "https://cognito-idp.eu-central-1.amazonaws.com/bla", 25 | "aud": "my-audience", 26 | "sub": "username", 27 | }, 28 | ) 29 | auth = validator.TokenValidator("eu-central-1", "bla", "my-audience") 30 | with pytest.raises(validator.TokenError): 31 | auth.validate(token) 32 | 33 | 34 | def test_validate_token_error_aud(cognito_well_known_keys, jwk_private_key_one): 35 | token = create_jwt_token( 36 | jwk_private_key_one, 37 | { 38 | "iss": "https://cognito-idp.eu-central-1.amazonaws.com/bla", 39 | "aud": "other-audience", 40 | "sub": "username", 41 | }, 42 | ) 43 | auth = validator.TokenValidator("eu-central-1", "bla", "my-audience") 44 | 45 | with pytest.raises(validator.TokenError): 46 | auth.validate(token) 47 | 48 | 49 | @pytest.mark.parametrize( 50 | "is_cache_enabled,responses_calls", [(None, 2), (False, 2), (True, 1)] 51 | ) 52 | def test_validate_token_caching( 53 | cognito_well_known_keys, 54 | jwk_private_key_one, 55 | settings, 56 | responses, 57 | is_cache_enabled, 58 | responses_calls, 59 | ): 60 | if is_cache_enabled is not None: 61 | settings.COGNITO_PUBLIC_KEYS_CACHING_ENABLED = is_cache_enabled 62 | 63 | token = create_jwt_token( 64 | jwk_private_key_one, 65 | { 66 | "iss": "https://cognito-idp.eu-central-1.amazonaws.com/bla", 67 | "aud": "my-audience", 68 | "sub": "username", 69 | }, 70 | ) 71 | auth = validator.TokenValidator("eu-central-1", "bla", "my-audience") 72 | auth.validate(token) 73 | assert len(responses.calls) == 1 74 | 75 | auth_again = validator.TokenValidator("eu-central-1", "bla", "my-audience") 76 | auth_again.validate(token) 77 | assert len(responses.calls) == responses_calls 78 | -------------------------------------------------------------------------------- /tests/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | from rest_framework.decorators import api_view, authentication_classes 3 | from rest_framework.response import Response 4 | 5 | from django_cognito_jwt import JSONWebTokenAuthentication 6 | 7 | 8 | @api_view(http_method_names=["GET"]) 9 | @authentication_classes((JSONWebTokenAuthentication,)) 10 | def sample_view(request): 11 | return Response({"hello": "world"}) 12 | 13 | 14 | urlpatterns = [url(r"^$", sample_view, name="sample_view")] 15 | -------------------------------------------------------------------------------- /tests/utils.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | import jwt 4 | from jwt.algorithms import RSAAlgorithm 5 | 6 | 7 | def create_jwt_token(private_key, payload): 8 | key = json.dumps(private_key) 9 | key_id = private_key["kid"] 10 | 11 | secret = RSAAlgorithm.from_jwk(key) 12 | return jwt.encode(payload, secret, algorithm="RS256", headers={"kid": key_id}) 13 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py{36,37,38}-django{22,30} 3 | 4 | 5 | [gh-actions] 6 | python = 7 | 3.6: py36 8 | 3.7: py37 9 | 3.8: py38 10 | 11 | [testenv] 12 | commands = coverage run --source django_cognito_jwt --parallel -m pytest {posargs} 13 | deps = 14 | django22: Django>=2.2,<2.3 15 | django30: Django>=3.0,<3.1 16 | extras = test 17 | 18 | [testenv:coverage-report] 19 | basepython = python3.7 20 | deps = coverage[toml] 21 | skip_install = true 22 | commands = 23 | coverage combine 24 | coverage xml 25 | coverage report 26 | 27 | [testenv:format] 28 | basepython = python3.7 29 | deps = 30 | black 31 | isort[toml] 32 | skip_install = true 33 | commands = 34 | isort --recursive --check-only src tests 35 | black --check src/ tests/ 36 | 37 | --------------------------------------------------------------------------------