HOW TO MAKE A FULL FLEDGED REST API. with DJANGO OAUTH TOOLKIT

Similar documents
The simple but powerful elegance of Django REST Framework. start

Django OAuth Toolkit Documentation

django-rest-framework-datatables Documentation

Django-Select2 Documentation. Nirupam Biswas

Django REST Framework JSON API Documentation

Building APIs with Django and Django Rest Framework

django-oauth2-provider Documentation

django-rest-auth Documentation

Graphene Documentation

django-conduit Documentation

Tutorial: Building the Services Ecosystem

DjangoRestMultipleModels Documentation

drf-haystack documentation

WEB API. Nuki Home Solutions GmbH. Münzgrabenstraße 92/ Graz Austria F

Bambu API Documentation

Integrating with ClearPass HTTP APIs

django-autocomplete-light Documentation

django-permission Documentation

django-autocomplete-light Documentation

for Salesforce Question-to-Case Connector

Tangent MicroServices Documentation

django-ratelimit-backend Documentation

Beginner s Guide to Cordova and Mobile Application Development

silk Documentation Release 0.3 Michael Ford

Building a Django Twilio Programmable Chat Application

ForgeRock Access Management Customization and APIs

Build Mobile Cloud Apps Effectively Using Oracle Mobile Cloud Services (MCS)

Partner Center: Secure application model

REST API: Guide for Implementers

Using Twitter & Facebook API. INF5750/ Lecture 10 (Part II)

Canonical Identity Provider Documentation

C1: Define Security Requirements

Oracle APEX 18.1 New Features

django-openid Documentation

Using OAuth 2.0 to Access ionbiz APIs

Making a POST Request Using Informatica Cloud REST API Connector

Salesforce IoT REST API Getting Started Guide

Introduction to Kony Fabric

Mobile Procurement REST API (MOBPROC): Access Tokens

Single Sign-On for PCF. User's Guide

API Gateway. Version 7.5.1

Easily Secure your Microservices with Keycloak. Sébastien Blanc Red

Zimbra Collaboration Two-Factor Authentication

EXPERIENCES MOVING FROM DJANGO TO FLASK

Full Stack Web Developer Nanodegree Syllabus

Kinto Documentation. Release Mozilla Services Da French Team

Django File Picker Documentation

Django File Picker Documentation

django-sticky-uploads Documentation

GraphQL in Python and Django. Patrick

Django Synctool Documentation

Django Extras Documentation

django-baton Documentation

NIELSEN API PORTAL USER REGISTRATION GUIDE

PowerExchange for Facebook: How to Configure Open Authentication using the OAuth Utility

welcome to BOILERCAMP HOW TO WEB DEV

Web Messaging Configuration Guide Document Version: 1.3 May 2018

Advanced API Security

Infrastructure as Code: "pip install" your environment. Sebastian

OAuth securing the insecure

ReportPlus Embedded Web SDK Guide

Integration Guide. LoginTC

LFC - Lightning Fast CMS Documentation

Edge Foundational Training

How to use or not use the AWS API Gateway for Microservices

DreamFactory Security Guide

uick Start Guide 1. Install Oracle Java SE Development Kit (JDK) version or later or 1.7.* and set the JAVA_HOME environment variable.

Django REST Framework JSON API Documentation

GPII Security. Washington DC, November 2015

Django Groups Manager Documentation

Building the Modern Research Data Portal using the Globus Platform. Rachana Ananthakrishnan GlobusWorld 2017

Creating a REST API which exposes an existing SOAP Service with IBM API Management

Django Groups Manager Documentation

MAX Realtime messaging and activity stream engine. Carles Bruguera Víctor Fernández de Alba

PostgreSQL as REST API Server without coding. Priya

Developing Cross-Platform Native Apps with AppStudio for ArcGIS. Jo Fraley Erwin Soekianto

Best Practices: Authentication & Authorization Infrastructure. Massimo Benini HPCAC - April,

OAuth and OpenID Connect (IN PLAIN ENGLISH)

webkitpony Documentation

django-dajax Documentation

[GSoC Proposal] Securing Airavata API

Securing APIs and Microservices with OAuth and OpenID Connect

fragapy Documentation

Creating a REST API which exposes an existing SOAP Service with IBM API Management

MIT AITI Python Software Development Lab DJ1:

Django MFA Documentation

Sentinet for Microsoft Azure SENTINET

Consuming Office 365 REST API. Paolo Pialorsi PiaSys.com

why? Give an app access to a resource managed by someone else, without giving the app your password. A valet key for the web Allen I.

DJOAuth2 Documentation

About 1. Chapter 1: Getting started with odata 2. Remarks 2. Examples 2. Installation or Setup 2. Odata- The Best way to Rest 2

7401ICT eservice Technology. (Some of) the actual examination questions will be more precise than these.

Randtronics Data Privacy Manager

Microsoft Graph API Deep Dive

PROCE55 Mobile: Web API App. Web API.

Protect Your API with OAuth 2. Rob Allen

MIGRATING MOBILE APPS. How to migrate Rollbase and OpenEdge Mobile Apps to the Telerik Platform

bzz Documentation Release Rafael Floriano and Bernardo Heynemann

Which compute option is designed for the above scenario? A. OpenWhisk B. Containers C. Virtual Servers D. Cloud Foundry

Azure Active Directory from Zero to Hero

Transcription:

HOW TO MAKE A FULL FLEDGED REST API with DJANGO OAUTH TOOLKIT

FEDERICO FRENGUELLI @synasius http://evonove.it

GOALS OAuth2 protected REST API with Django

WHY?

INTRODUCING the marvelous TIMETRACKER

ONCE UPON A TIME... one tool single project deploy once and everything is fine... (more or less)

THE TIMES THEY ARE A-CHANGIN'

Web UIs evolve Smarter Users Multiple Devices to Support

APPLICATION MITOSIS! timetracker-backend timetracker-web timetracker-android timetracker-ios timetracker-desktop (linux, win, osx) moreover...

SERVICES ARE CONNECTED! Third party service want your user's data!

WHAT'S IN THE BACKEND? A service that expose an amazing and reliable REST API

THE REAL APP TIMETRACKER timetracker-backend timetracker-web timetracker-android timetracker-ios timetracker-desktop (linux, max, osx)

UI RECIPE Gumby css framework Ember.js javascript framework jquery No matter what you use.. it's a pain in the ass!

BACKEND RECIPE Django Django REST Framework Django OAuth Toolkit

MODELS class Activity(models.Model): name = models.charfield(max_length=100) description = models.textfield(blank=true) class TimeEntry(models.Model): activity = models.foreignkey(activity) user = models.foreignkey(settings.auth_user_model) description = models.textfield(blank=true) start = models.datetimefield(blank=true, null=true) end = models.datetimefield(blank=true, null=true)

API ENDPOINTS Url Methods Semantic /api/activities/ GET, POST list, create /api/activities/<id>/ GET, PUT/PATCH, DELETE detail, update, remove /api/tracks/ GET, POST list, create /api/tracks/<id>/ GET, PUT/PATCH, DELETE detail, update, remove

DEEP INTO DRF IN 5 MINUTES

SERIALIZE DATA class ActivitySerializer(serializers.Serializer): pk = serializers.field() name = serializers.charfield(max_length=100) description = serializers.charfield(required=false) def restore_object(self, attrs, instance=none): if instance: # Update existing instance instance.name = attrs.get('name', instance.name) instance.description = attrs.get('description', instance.description) return instance # Create new instance return Activity(**attrs) serializer = ActivitySerializer(activity) serializer.data # {'pk': 1, 'name': u'timetracker', 'description': u'workin on time tracker'}

SIMPLIFY! MODEL SERIALIZER class ActivitySerializer(serializers.ModelSerializer): class Meta: model = Activity

API ENDPOINTS VIEWS What do we need? respect REST semantic user authentication permissions checks (also object level permission) pagination response and request formatting it's a lot of stuff!

KEEP CALM AND USE DRF!

SETTINGS REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.sessionauthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.isauthenticated', ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.jsonrenderer', ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.jsonparser', ) }

APIVIEW class ActivityList(APIView): """ List all activities, or create a new activity. """ def get(self, request, format=none): activities = Activity.objects.all() serializer = ActivitySerializer(activities, many=true) return Response(serializer.data) def post(self, request, format=none): serializer = ActivitySerializer(data=request.DATA) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.http_201_created) return Response(serializer.errors, status=status.http_400_bad_request) urlpatterns = patterns('', url(r'^api/activities/$', ActivityList.as_view()), #... )

SIMPLIFY! GENERIC CLASS BASED VIEWS class ActivityList(generics.ListCreateAPIView): queryset = Activity.objects.all() serializer_class = ActivitySerializer class ActivityDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Activity.objects.all() serializer_class = ActivitySerializer class TimeEntryList(generics.ListCreateAPIView): queryset = TimeEntry.objects.all() serializer_class = TimeEntrySerializer class TimeEntryDetail(generics.RetrieveUpdateDestroyAPIView): queryset = TimeEntry.objects.all() serializer_class = TimeEntrySerializer

LAZY DEVS? VIEWSETS class ActivityViewSet(viewsets.ModelViewSet): model = Activity class TimeEntryViewSet(viewsets.ModelViewSet): model = TimeEntry router = routers.defaultrouter() router.register(r'activities', ActivityViewSet) router.register(r'tracks', TimeEntryViewSet) urlpatterns = patterns('', url(r'^api/', include(router.urls)), )

BONUS! BUILTIN BROWSABLE API

HOW DO YOUR CLIENTS AUTHENTICATE? AND WHAT IF A THIRD PARTY APP WANTS TO ACCESS YOUR USER'S DATA??

PROBLEMS Store the user password in the app The app has a full access to user account User has to change his password to revoke the access Compromised apps expose the user password Reference: http://www.slideshare.net/aaronpk/an-introduction-to-oauth2

THE OAUTH2 AUTHORIZATION FRAMEWORK How does it work?

USE CASE

ACTORS Resource Owner: The User Resource Server: Timetracker API Authorization Server: The same as the Resource Server Client: Songify App

STEPS Client registers with the Authorization Server The Authorization Server provides client id and client secret Client directs the Resource Owner to an authorization server via its user-agent The Authorization Server authenticates the Resource Owner and obtains authorization The Authorization Server directs the Resource Owner back to the client with the authorization code The Client exchange the authorization code for a token The token is used by the Client to authenticate requests

DJANGO OAUTH TOOLKIT Django 1.4, 1.5, 1.6, 1.7 Python2 & Python3 built on top of oauthlib https://github.com/evonove/django-oauth-toolkit

DOT AND DJANGO INSTALLED_APPS += ('oauth2_provider',) urlpatterns += patterns('', url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')), ) Create a protected endpoint from oauth2_provider.views.generic import ProtectedResourceView class ApiEndpoint(ProtectedResourceView): def get(self, request, *args, **kwargs): return HttpResponse('Protected with OAuth2!')

BATTERIES INCLUDED builtin views to register developer apps form view for user authorization

INTEGRATES WITH DRF REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.ext.rest_framework.oauth2authentication', ) }

LET'S TEST IT! Authorization endpoint http://localhost:8000/o/authorize?response_type=code&client_id=&redirect_uri=ht Exchange the code curl -X POST -d "grant_type=authorization_code&code= &redirect_uri=http://example.com/" http://:@localhost:8000/o/token/ Unauthenticated access curl http://localhost:8000/api/activities/ Authenticated access curl -H "Authorization: Bearer " http://localhost:8000/api/activities/

FUTURE PLANS OAuth1 support OpenID connector NoSQL storages support HELP NEEDED

THANKS