Securing API's with Multi Factor Authentication - django

I want to secure my API with Multi-factor-Authentication on top of Auth Token/JWT. I have been searching but couldn't find any package that can work with drf. I am thinking to write my own django app. Any comments on what should be the architecture ?
One solution that comes to my mind is to introduce the token base architecture.If a user is accessing the mfa secured api then the request instance should be saved alongside a token and a sms should be sent to his mobile (In case of mobile as mfa) and response should be a that token. Then another request should be made to a mfa endpoint with token and mfa-code. Once verified, We would take his previous request object and complete the request.

Related

Validating jwt token in REST api

I have a doubt regarding the jwt token validation done by the REST api and was not able to find a simple yes/no answer. Assume that everything is being transferred over HTTPS.
I have the following setup
React app
REST API
AWS Cognito that handles the user registration/login
When a user wants to login, then the React app would call the AWS Cognito api and validate the credentials. If valid, Cognito will send back a jwt token (that will contain the necessary meta data) that can be passed to the REST API. Now I see two options
the backend verifies that the jwt token was not altered using the rfc spec. If valid, the api extracts the necessary meta data and continues to process the request
The backend verifies the validity of the jwt token, but also calls the Cognito service to verify the metadata in the token.
I think that since everything is handled over HTTPS and the fact that its hard create a valid token then the first point is enough. There is no need to have an extra call over the wire. Am I wrong ?
Found the following question from softwareengineering.stackexchange.com which pretty much answers my question. Link
The local validation of the JWT token is enough when the token was created with asymmetric encryption.

Secure authentication between ReactJS and Django

Been reading and watching quite a bit, and asking a lot of questions regarding ReactJS and Django.
This particularly helped me to understand the the flow of data from Django REST Framework to ReactJS and from ReactJS to Django REST Framework.
Django Forms and Authentication with Front-end Framework (AngularJS/ReactJS)
However, the one thing I am trying to understand is authentication to the Django REST Framework. I understand from the documentation that it has built in authentication. Since this is sensitive data, I would obviously want it protected people retrieving it just by going to http://www.my_site.com/info/api.
I would need to setup ReactJS to be the only thing that can request data from the API whether that is through a key or username/password credentials. I am just curious how this is handled? Obviously I don't want that hard coded in ReactJS because it will compile with the rest of ReactJS.
Here's how I'd approach it: I'd use a JSON Web Token (JWT) for authentication and authorization.
You'd use your back-end to protect ALL API requests from invalid JWT's except for routes where a user won't have a token (ie, registration/log-in pages).
Here's how the flow of the application will go:
A new user registers to your app with standard credentials such as email and password.
Your back-end will create a new user, sign a new JWT token (usually with the user's ID). You'll probably use a third-party library to sign/verify tokens (I don't have experience in the Django community but I am sure a quick Google search will give you answers). Your back-end will send back this token. This is the only time the back-end will receive email, passwords or any other sensitive information on registration.
From this point on React will only use this token for authorization. React will save this token somewhere (ie, localStorage) and send this token along with the other parts of a request to the API routes you created with your back-end. You'll send this token in the authorization headers in the request.
Your back-end will validate this token using a third-party library. If it's invalid the request stops and an unauthorized error is returned. If it's valid the request continues.
This achieves the following:
Your API routes are protected against unauthenticated users
Each request to your API is verified for authorized users which protects anyone from requesting any part of your API.
You can further solidify this by only allowing requests for users to modify their own data. For example, protect Suzy's profile from being modified by people other than herself by only allowing her token with her ID to modify her account/data.
Important Note- Your backend will never save these tokens in storage. It will verify the token on each request. Read more about JSON Web Tokens (JWT) and how it works.
Django Rest Framework has built-in token authentication and a third party package for JWT Token Auth.
If you the standard token auth would work for you, then it could be pretty simple with drf-redux-auth. If you need JWT for some reason, as suggested by Keith above, you could easily fork the above...

Django - Temporarily save request token for OAuth 1.0a flow

The Twitter OAuth 1.0a flow requires authenticated request token to be exchanged with access token at consumer or client side after user has authenticated.
The problem that I'm facing is that generating access token needs authenticated request token, request token secret and verifier but the response from the oauth/authentication api doesn't have request token secret. So how do I temporarily save request token secret from oauth/request_token api call so that I can use it in oauth/access_token api call.
I found some solutions from my explorations like Running a Cache server (Memcached, Redis) or using django session feature. But they all seem to be overkill for this task.
I hope to find a simpler solution.
I'm sure you long ago figured this out, but just for future goolers: I decided to a go a more low tech route and create an OAuth token class which includes fields for the fetched and access token. Basically I take the fetched token, store it, then recall it when accessing (as it's in a different view) and then save the access token. Once (if) that's successful than I delete the fetched token.
There's likely a more glamorous way to do this, but if you're clever with your naming convention you can easily keep them straight (i.e. add a CharField for provider and just save the fetched token as twitter_fetched, and the access token as just twitter).
This has the added benefit of allowing you to create an OAuth1 or OAuth1Session from the stored access token.

Securing Restful Web Services with OAuth2 with JWT

Hi i am new to Apache cxf rest API security side.I want to rest API which have good security with authorization.I found Apache cxf gives Ouath2 security features(http://cxf.apache.org/docs/jax-rs-oauth2.html).So And i need to use json web token(http://jwt.io/) to send to API for authorization.Simply i need to use secured line for send request to rest API.So far i have simple design.
And my REST api have CRUD Operations to database.I thought send JWT as Access token in request header.And API side verify the user and send data back to user.I have two questions.First one is Is this the best design for this kind of application.And second one is if this is best way how to generate Tokens and is that we need to keep those tokens in server side.
Yes it's a good design
I can explain it with github web api's
Authorize
First u validate urself for using API by sending client id and callback url in request (here u specify access level ie.scope) and u receive a code
Access_token
Then u exchange this code for access token (this time with client secret included in req parameter)
This access token received is used for all future calls made by u on behalf of user
Nd ya u store this token and refresh token at server
https://developer.github.com/v3/oauth/#web-application-flow
Although this is specific to github , similar flow follows for twitter , linked in and slightly different for facebook web api's

Generate an OAuth2 token in a view

Let's say I have an AngularJS application that consumes the REST API of a Django application.
The Django application has got a built-in OAuth2 provider that can be called to retrieve an access token and use the protected endpoints of the API. This provider is using django-oauth-toolkit.
Let's assume there is a registered client with "password" grant type, so that the end users only need to provide their credentials in the front-end in order to get an access token from the back-end.
At some point we want to add some support for social networks login and we decide to use python-social-auth (PSA) to that end. Here is the workflow I want to achieve:
The user logs in on Facebook from the front-end (via the Facebook SDK) and we get an access token back from the OAuth2 provider of Facebook.
We send the Facebook token to an endpoint of our REST API. This endpoint uses the Facebook token and django-social-auth to authenticate the user in our Django application (basically matching a Facebook account to a standard account within the app).
If the authentication succeeds, the API endpoint requests an access token from the OAuth2 provider for this newly authenticated user.
The Django access token is sent back to the front-end and can be used to access the REST API in exactly the same way that a regular user (i.e. logged in with his credentials) would do.
Now my problem is: how do I achieve step 3? I first thought I would register a separate OAuth2 client with Client Credentials Grant but then the generated token is not user-specific so it does not make sense. Another option is to use the TokenAuthentication from DRF but that would add too much complexity to my project. I already have an OAuth server and I don't want to set up a second token provider to circumvent my problem, unless this is the only solution.
I think my understanding of PSA and django-oauth-toolkit is not deep enough to find the best way of reaching my goal, but there must be a way. Help!
I managed to get something working using urllib2. I can't speak towards whether or not this is good practice, but I can successfully generate an OAuth2 token within a view.
Normally when I'd generate an access token with cURL, it'd look like this:
curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/
So we're tasked with making urllib2 accomplish this. After playing around for some bit, it is fairly straightforward.
import urllib, urlib2, base64, json
# Housekeeping
token_url = 'http://localhost:8000/auth/token/'
data = urllib.urlencode({'grant_type':'password', 'username':<username>, 'password':<password>})
authentication = base64.b64encode('%s:%s' % (<client_id>, <client_secret>))
# Down to Business
request = urllib2.Request(token_url, data)
request.add_header("Authorization", "Basic %s" % authentication)
access_credentials = urllib2.urlopen(request)
json_credentials = json.load(access_credentials)
I reiterate, I do not know if this is in bad practice and I have not looked into whether or not this causes any issues with Django. AFAIK this will do this trick (as it did for me).