Part 2 - protect your APIs

    We start where we left the part 1 of the tutorial: you have an authorization server and we want it to provide an API to access some kind of resources. We don’t need an actual resource, so we will simply expose an endpoint protected with OAuth2: let’s do it in a class based view fashion!

    Django OAuth Toolkit provides a set of generic class based view you can use to add OAuth behaviour to your views. Open your views.py module and import the view:

    That’s it, our API will expose only one method, responding to GET requests. Now open your urls.py and specify the URL this view will respond to:

    You will probably want to write your own application views to deal with permissions and access control but the ones packaged with the library can get you started when developing the app.

    Time to make requests to your API.

    For a quick test, try accessing your app at the url /api/hello with your browser and verify that it responds with a 403 (in fact no HTTP_AUTHORIZATION header was provided). You can test your API with anything that can perform HTTP requests, but for this tutorial you can use the online . Just fill the form with the URL of the API endpoint (i.e. http://localhost:8000/api/hello if you’re on localhost) and the access token coming from the . Going in the Django admin and get the token from there is not considered cheating, so it’s an option.

    Part 3 of the tutorial will show how to use an access token to authenticate users.