|
| 1 | +Identity for a Django Web API |
| 2 | +============================= |
| 3 | + |
| 4 | +.. include:: app-vs-api.rst |
| 5 | + |
| 6 | +Prerequisite |
| 7 | +------------ |
| 8 | + |
| 9 | +Create a hello world web project in Django. |
| 10 | + |
| 11 | +You can use |
| 12 | +`Django's own tutorial, part 1 <https://docs.djangoproject.com/en/5.0/intro/tutorial01/>`_ |
| 13 | +as a reference. What we need are basically these steps: |
| 14 | + |
| 15 | +#. ``django-admin startproject mysite`` |
| 16 | +#. ``python manage.py migrate`` (Optinoal if your project does not use a database) |
| 17 | +#. ``python manage.py runserver localhost:5000`` |
| 18 | + |
| 19 | +#. Now, add a new `mysite/views.py` file with an `index` view to your project. |
| 20 | + For now, it can simply return a "hello world" page to any visitor:: |
| 21 | + |
| 22 | + from django.http import JsonResponse |
| 23 | + def index(request): |
| 24 | + return JsonResponse({"message": "Hello, world!"}) |
| 25 | + |
| 26 | +Configuration |
| 27 | +------------- |
| 28 | + |
| 29 | +#. Install dependency by ``pip install identity[django]`` |
| 30 | + |
| 31 | +#. Create an instance of the :py:class:`identity.django.Auth` object, |
| 32 | + and assign it to a global variable inside your ``settings.py``:: |
| 33 | + |
| 34 | + import os |
| 35 | + from identity.django import Auth |
| 36 | + AUTH = Auth( |
| 37 | + client_id=os.getenv('CLIENT_ID'), |
| 38 | + ...=..., # See below on how to feed in the authority url parameter |
| 39 | + ) |
| 40 | + |
| 41 | + .. include:: auth.rst |
| 42 | + |
| 43 | + |
| 44 | +Django Web API protected by an access token |
| 45 | +------------------------------------------- |
| 46 | + |
| 47 | +#. In your web project's ``views.py``, decorate some views with the |
| 48 | + :py:func:`identity.django.ApiAuth.authorization_required` decorator:: |
| 49 | + |
| 50 | + from django.conf import settings |
| 51 | + |
| 52 | + @settings.AUTH.authorization_required(expected_scopes={ |
| 53 | + "your_scope_1": "api://your_client_id/your_scope_1", |
| 54 | + "your_scope_2": "api://your_client_id/your_scope_2", |
| 55 | + }) |
| 56 | + def index(request, *, context): |
| 57 | + claims = context['claims'] |
| 58 | + # The user is uniquely identified by claims['sub'] or claims["oid"], |
| 59 | + # claims['tid'] and/or claims['iss']. |
| 60 | + return JsonResponse( |
| 61 | + {"message": f"Data for {claims['sub']}@{claims['tid']}"} |
| 62 | + ) |
| 63 | + |
| 64 | + |
| 65 | +All of the content above are demonstrated in |
| 66 | +`this django web app sample <https://github.com/Azure-Samples/ms-identity-python-webapi-django>`_. |
| 67 | + |
| 68 | + |
| 69 | +API for Django web projects |
| 70 | +--------------------------- |
| 71 | + |
| 72 | +.. autoclass:: identity.django.ApiAuth |
| 73 | + :members: |
| 74 | + :inherited-members: |
| 75 | + |
| 76 | + .. automethod:: __init__ |
| 77 | + |
0 commit comments