One-Time User Authentication with SMS Using Django and Twilio - django

I am writing a back-end in Django for a mobile app I am creating. I need to authenticate a user the first time they open the mobile app through SMS to verify it is a real person. What needs to happen is the following: user enters phone number in app, server then sends SMS message to user with authentication code, user then enters authentication code in app and server verifies that the code they entered in the app is the same one they received through SMS.
I need to use Twilio with my Django project. I just need to know what would be the best way to go about this? The front-end side of this (the mobile app) is not what I am asking about, I am asking about the code on the back-end that should be implemented. I am struggling to find up to date documentation for django-twilio integration that could do this.

Twilio evangelist and maintainer of django-twilio here.
What you're looking to build is something very easy to do, I can outline the steps for you here:
Create a Django model that stores a user's number and a generated passcode
When a new user is created, take their number and SMS them the code using the Twilio REST API
When they enter the passcode you sent them, cross reference it with the one stored in the database.
If the number is right: verify them, if not, tell them it is wrong and offer to send them an SMS again.

You can use django-passcode as an app in your project.
It exposes APIs to "register" a mobile number and "verify" through SMS based passcode. It uses mobile number and device id pair as unique. It also generates and returns a token for future authorization requests from mobile app. You can use Twilio or any other SMS api to send sms.
https://github.com/sgurminder/django-passcode
I appreciate your feedback for django-passcode

Disclaimer: I'm the maintainer of Django-phone-verify
What you're looking to accomplish is very easy with django-phone-verify app. It comes with Twilio already integrated and few endpoints which you can extend as per your use case.
This package aims at verifying if a phone number requested by a particular client belongs to them. It also takes care of ensuring that the same device provides the verification of passcode which intially requested a passcode to be sent, saving you a few hours of work.
This package also doesn't messes up with your current user model at all. You're free to use this package exactly for one thing: verifying phone numbers. Whether you do it for users, companies, etc. depends on your use-case.
It follows Unix philosphy of Do one thing; do it well
Installation
pip install django-phone-verify
Configuration
Add app to INSTALLED_APPS:
# In settings.py:
INSTALLED_APPS = [
...
'phone_verify',
]
Add settings in your settings.py file:
# Settings for phone_verify
PHONE_VERIFICATION = {
'BACKEND': 'phone_verify.backends.twilio.TwilioBackend',
'TWILIO_SANDBOX_TOKEN':'123456',
'OPTIONS': {
'SID': 'fake',
'SECRET': 'fake',
'FROM': '+14755292729'
},
'TOKEN_LENGTH': 6,
'MESSAGE': 'Welcome to {app}! Please use security code {otp} to proceed.',
'APP_NAME': 'Phone Verify',
'OTP_EXPIRATION_TIME': 3600 # In seconds only
}
Migrate the database:
python manage.py migrate
You get two endpoints (Check API docs), one for registration of phone number and other to verify the passcode. You may override verify endpoint to also create a user as described in the usage docs: https://github.com/CuriousLearner/django-phone-verify/blob/master/docs/usage.rst

Recently I was looking for any library or scheme to sign-in/sign-up users through sms (send sms code and then validate).
Short solution:
Create sms model to generate code for phone number
Send sms with code to client (for example, use twillio)
User got code. And send phone_number + code
Validate it. Response any useful information
Also:
You must to use async code or celery to send sms
Add sms lifetime (for example, 30 seconds)
Clean phone number to valid format
Get or create user by phone number
You may to use this library, for example:
https://github.com/a1k89/django-rest-sms-auth

Related

Is it possible to send data from a client to a server without the API being public?

I'm currently trying to make an account signup page for a small project I'm working on and I don't know how to send data back to the server (I'm using the Flask framework) without also allowing everyone to send data. Let's say that I've set up an API endpoint on /createAccount. I can then send POST requests to that endpoint: {"username": "test", "password": "test"}. The web server will then handle that request by inserting that data into a database and responding with 201. The problem is, anybody would be able to send these requests, and I only want users to be able to register through the login page, and not by making an API call. Is there any way of doing this?
Edit: I've given this problem a bit more thought and I think that the only API that is difficult to secure is the signup API. When a user has created an account, I can just assign them an API key, which they will send to the API every time they want to make a request, which means that an account is required to make API calls. If a certain key is making too many requests, they can be rate limited or temporarily banned from making further requests. The problem with the signup API however, is that there is no information by witch a request sender could be identified. I could use the IP address, but that can be changed and wouldn't really help if multiple IPs are spamming the API at the same time. Is there a way I can identify non-registered users?
Short answer: no.
You have to check data to make sure the account being created is something legit and not trash data to fill your database or any other malicious intents.
This is the reason you usually have to confirm an account clicking on a confirmation link sent to your mail: this way the app is sure that your account is legit.
You could also check info on the front end, but that is never as secure as back end checking, because of your concern in the question: in the end, anyone who gets to know your endpoints could potentially send direct requests to your server with whatever data they wanted.
Assuming you have a trusted source of registrations, an if that source can make an ssh connection to the server where your Flask app is running, an alternative to trying to lock down a registration API is to provide a command line script to do the registration.
The trusted source does something like
ssh someuser#youripaddress /path/to/register.py "username" "password" "other info"
If you use a Flask custom command you can share model definitions db configuration.

What does 'secret_key' stand for in webapp2 framework?

I am just playing around with google app engine, webapp2, and python; I am just building a small toy app for fun. A small side note, using ndb for google app engine datastore.
With building a small webapp, comes sessions.
I was reading the webapp2 documentation on sessions, as well as the most popular threads on this website on how to setup sessions. What I don't get about this process is this small piece of code in the config.
config = {}
config['webapp2_extras.sessions'] = {
'secret_key': 'my-super-secret-key',
}
I am pretty new to web development. However, building other smaller apps with this same framework, I done the following to build somewhat secured hashed cookies.
user_key = user_key.id()
user_cookie = self.request.cookies.get('user_cookie', None)
and
self.response.headers.add_header('Set-Cookie','user=%s|%s' % (user_cookie, hash_string(user_cookie)))
self.write('Thank you for sigining up! And, welcome %s' % user.name)
Is that what the first bit of code above for the config is trying to accomplish?
In other words what is this secret key for?
Also, lets say I want to set the 'sessions' cookie to the user id.
Would the code below be the correct way to do this?
self.session[name] = user_key.id()
session_info = self.session.get(name)
Thank you.
The secret_key is used by the server to digitally sign the cookie data that you are reading when you are calling self.request.cookies.get('user_cookie', None).
The cookies are continually passed from client to server along with the digital signature. When the client presents the cookie values to the server with each request it does so with the digital signature given by the server. Each time the server signs the current cookie values, if the signature passed in by the client does not match the current server values the server knows the parameters of the cookie have been tampered with. This guards against a malicious client trying to impersonate another user or otherwise perform an unauthorised action.
This scheme only works if the key is only known to the server, otherwise any client could also sign cookies that the server would accept. Hence secret_key.
The default signature algorithm in webapp2 is HMAC-SHA1.
Also, quickly, when I look at the cookie set by instantiating sessions, it is an extremely long string
This is the code that the server uses to authenticate a cookie if you are curious. You'll notice that the cookie is base64 encoded json document.
Now I suppose that the value of secret_key can then be any string that you'd like it to be, correct?
As they spell out from RFC 2104 on this security thread any string of 20 or more randomly chosen bytes should do for HMAC-SHA1.
Also, lets say I want to set the 'sessions' cookie to the user id
I think this is probably the example you are looking for.

Mirror API send timeline item to particular user

I need to send timeline item to particular subscribed user using Mirror API. I have the user's email id. How can I achive this?
Thanks
Update:
I have GDK app, companion app(which runs on Android mobile device) and Mirror API app. Both GDK app and companion paired via Bluetooth. My use case is I have to send timeline item to uesr if he reached particular location. We are using ibeacon to check user's location. When user reached that particular area, companion app detect it(via bluetooth) and send request to mirror app then mirror app will add timeline item to user's glass. Here my question is how to add the timeline item to one particular user?(not to all subscribed users) And what parameter should I pass to mirror app from companion app?(I was thinking to send the user's email id)
The user will have needed to log into your service using OAuth2 and have granted specific permission for you to access their timeline using the role https://www.googleapis.com/auth/glass.timeline. You should request "offline" access so you will receive both an auth token and a refresh token, which you can use to get a new auth token after an hour.
You will need this auth token when you send a card to the timeline, which also serves as an identifier in this case. Having their email id is not enough, and you don't need it.
See https://developers.google.com/glass/develop/mirror/authorization for some code samples and details.
Update:
So it sounds like you have the following overall work flow:
User creates an account on your website (which is where the Mirror API app is hosted). As part of this, they authorize access to their Glass and either give you their email address or authorize you to get it via Google's API.
You'll store this information (auth_token and refresh_token) in a data store somewhere, indexed against their email address.
They will also install your app on their phone, and it has access to the email address as well.
When the mobile app detects an ibeacon marker it is interested in, it connects to your web service and sends the email address and location.
Your web service looks up the email address, gets the access token to authenticate the connection to the Mirror service, and sends a message to Glass with the location information.
This is a generally reasonable workflow, but there are a couple of important points to make:
The Mirror API is well tuned to sending things to just one person at a time. You sound worried about sending bulk results, but as long as you use the auth token for just one user, it will send it to just that user.
You're using the email address as an index to the entire user account. While this is simple to implement, this is not the best solution, since it means that anyone who has a person's email address and the URL for the endpoint of your service can fake locations. You may consider this an acceptable risk given how you're using the location information (sending it back to the user), but you need to think about how the service could be misused.
You can mitigate the risk in a couple of potential ways:
Instead of an easily guessable email address, you can create and use some other userid which the user will need to enter when they first setup the companion app.
The first time (and only the first time) the app wants to connect to the service, it creates and sends a random secret string which it will use as a password and the web service could store this random string. Afterwards, the companion app would need to send this string along with the email address.
Depending on your needs, you could cut out the webapp completely and have the companion app use the Mirror API directly. This would leave the auth tokens on the phone and would greatly reduce the potential chance to have someone spoof your user. It does have a significant downside - although you can use it to send cards to Glass, it becomes more difficult to get responses from Glass back to the companion device.
As I understand your question and comments above, your user has already authenticated with your Mirror API based application, so you already have the required credentials (auth/refresh tokens). Your companion Android application detects a condition (user in a particular area) and sends a request to your remote endpoint in your Mirror API based application.
The companion app, when sending the request to the remote endpoint, needs to send a common piece of information that can be used to identify that user in your Mirror API app. In this case, you're saying you're sending the users email id.
To send a timeline card to only that particular user, I would take the email id that the companion application has sent, query your database to return the credentials that you saved when the user authenticated originally with your Mirror API based app and then use that to create an authenticated Mirror API request that inserts the timeline item for only that user. I don't know what your Mirror API app is written in, but a basic example in Python might take the following form:
# You sent along the email address
userid = notification['MyCompEmailId']
# set timeline card body
timelinecard_body = {
'notification': {'level': 'DEFAULT'},
'text': "You found a beacon!",
'menuItems': [{'action': 'DELETE'}]
}
# Look up the user in our database and
# get their credentials
#
# _credentials_for_user() basically does a "WHERE userid = 'something'" query
user_credentials = _credentials_for_user(userid).get()
# Create a Mirror API service with some credentials.
authed_mirror_service = build('mirror', 'v1', http=user_credentials.authorize(httplib2.Http()))
# Send a timeline card
authed_mirror_service.timeline().insert(body=timelinecard_body).execute()

Choosing the right place to write logic in a client/api/server solution

I'm currently designing a solution with this pretty standard pattern:
1 web-app using Django (it hosts the one and only DB)
1 client mobile app using AngularJS
This client app uses a REST API (implemented on the Django Server with Tastypie) to get and set data.
As a beginner in these architectures, I'm just asking myself where the logic should go and I'd like to use a simple example case to answer my concerns:
On the mobile client App, a client is asked to subscribe by entering only an email address in a form.
a) If the address is unused, inscription is done (stuff is written on the DB).
b) If the address is used, an error is raised, and the user is asked to try again.
What is the workflow to perform these simple operations?
I'm asking for example how to compare the entered e-mail address in the mobile app with the existing e-mail adresses in my DB:
Should I GET the list of all email adresses from the server, then perform the logic in my client app to state if the entered address already exists ? This seems really a bad way to do because getting lots of elements isn't performant with web services, and client should not be able to see all email adresses.
Should I send the entered e-mail address to the server and let it make the comparison? But if yes, how am I supposed to send the data? As far as I know, PUT/POST are made to write in the DB, not to just send data to server to analyse it and proceed some logic.
I have the feeling I am clearly missing something here...
Thanks a lot for help.
PUT and POST are designed to be used to create and update resources. The server may or may not have a database behind it. It might use a local filesystem, or it might handle anything in memory. It's none of the client's business. It is certainly common to have business logic on most servers which provide APIs.
Use PUT/POST to send up the email address to the server. The server checks to see if the email address is (a) valid, and (b) allowed. If it fails either check, return a relevant response to the client as documented in the RFC. I would go with 403 Forbidden, which indicates a problem with the data being sent up to the server. Use the entity in the response to detail what the problem was with the request.
I had done similar thing in a angular web app,
I have disabled the submit button, and added a check availability button beside the email field.
I have send the email to server and checked if it already exist and got the result to client,
then asked the user to enter an alternate email if not valid or enable the form's submit button
Alternatively
when the user leaves the email field, You can send the email to a service that validates the email, and get the response, and show a message that this email already exist and disable the submit, or enable the submit button otherwise

RESTful user authentication service

Hey folks, this seems to have been discussion fairly often but I want to make a simple, watered down question around doing authentication with RESTful services. The scenario is as follows:
There is a system that houses registered users for an application. The system exposes a RESTful API for accessing these users.
There is a front-end application that has a login form. The application can either be internal, or external.
The front-end application needs to use the data in the User system to authenticate a user.
The question now is how to authenticate a user whose credentials (username/password) are entered in the client application against the data in the User system such that it is secure and performant? For the sake of this question, suppose the client application is internal to some sort of Intranet but the applications will not reside on the same machine and may only communicate through the service.
I understand the idea of having the application being "hypermedia driven" but we should be able to provide filtering/searching services. For example, consider the resources and API as below:
http://example.com/users
GET - retrieves all users (paged, hypermedia driven)
POST - creates new user
PUT/DELETE not supported
http://example.com/users/[id]
GET - returns a full representation of a user with id = {id}
PUT - updates user, takes in any predefined media type
DELETE - deletes the user (with appropriate authorization)
POST not supported
Based on the above, my idea would be have the client application GET on the user listing, filtering by username. The service will return the hashed password and salt to the client, the client will perform the authentication.
Thoughts?
If I understand your question correctly, you are looking to implement a generic service that will handle authentication, so that you can re-use it for different applications.
I suggest you take a look at OAuth which has been built for precisely this problem domain.
Passing the username and the salt back is unnecessary and a real security risk.
Perhaps you could consider this approach:
Have the client pass the username and password to the server via Basic Authentication
The server fetches the encrypted password for the username along wiht the salt
The server encrypts the given password using some encryption method, using the salt to assist the algorithm (Ruby code follows):
def User.authenticate(login, password)
ok = false
user = User.find_by_login(login)
if user
#
# user contains the salt, it isn't passed from the client
#
expected_password = hash_password(password, user.salt)
ok = (user.password == expected_password)
end
return ok
end
There are multiple places to use this kind of approach but I like to do it in Rack.
Last point, do it all on a HTTPS connection
Stormpath
Stormpath company dedicated to providing a user login management API and service for developers. They use a REST JSON approach.
There are some other companies that seem to dabble in this new area of authentication-as-a-service, but Stormpath is the only one I know of that is dedicated to it.
First, you don't want the client to perform the authentication, as it then would be trivial to write a client that breaks into your service.
Instead, just use an authentication mechanism like HTTP Basic or HTTP Digest.
Note that if you're using Java, the Restlet framework provides interceptors, called Guards, which support these and other mechanisms. I highly recommend Restlet.
Mozilla Persona
Since this question was posted, the Mozilla Foundation (the maker of the Firefox browser) has taken on the problem of simple user authentication. Their solution is Mozilla Persona, "a sign-in system for the Web". Designed to be easy for users and for developers. The user's identity is an email address. See Wikipedia article.
Update
Mozilla has basically given up work on Persona but not quite killed the project.