OAuth2, Django-RestFramework and iOS RestKit
Recently I implemented an OAuth2 authentication scheme on a REST API, I couldn’t find any nice examples of how to use this in iOS, so here’s what I did.
Django OAuth2 provider
To get Django RestFramework to play nicely, we need to configure a couple of things. First, install
pip install django-oauth2-provider
And add it to your
Add the routes to your urls:
And create the tables
Now you can create a client, with a token and secret in the admin. You’ll need this info later for the authentication part.
As I wanted to still be able to use my Basic Authentication, I appended the OAuth class to the default authenticators. This is not necessary, but I wanted the change to be backwards compatible. Be aware that this might be a security issue (as you can work around the OAuth2 authentication), so be aware of that.
And you’re all set. You should now be able to call the token endpoint with your credentials:
and get a token in return:
Add AFOAuth2Client to your CocoaPods file:
AFOAuth2Client is a simple layer on top of AFNetworking, so it’s quite easy to setup, once you know how.
In your App Delegate (or wherever you want to check the given credentials, say a LoginViewController), add this:
API_SECRET are the credentials you created in the backend. The endpoint path should be good if you followed along.
Now, whenever you make a RestKit call, it will use the token you requested above. The only pitfall I noticed is that this call is asynchronous, so you need to check if there already is a token available, before calling any other request. I ended up pushing a message to my MasterView, which refreshed the tableview using the new token.