Saturday, February 1, 2014

Flask, Facebook Canvas App, localhost and SSL


If you're developing a facebook canvas app with Flask, then you're asked to provide URLs for your app. Initially I used myapp.herokuapp.com address for http and https. But I realized that for testing local changes, I'd like to use localhost.

When I give localhost, it says it's not SSL supported. Then I had to create SSL certificates and install pyopenssl to use them. See: http://kracekumar.com/post/54437887454/ssl-for-flask-local-development

But what I saw was that connection was untrusted and I could not Add an Exception. I learned that browsers do not trust localhost for SSL. So I had to create an alias for my herokuapp. Added the following line to /etc/hosts

127.0.0.1 myapp.herokuapp.com

And set the canvas url as myapp.herokuapp.com for http and https.

Now when the app starts, tries to load https://myapp.herokuapp.com. It loads https://127.0.0.1:443 which is listened by the Flask app:

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 443))
    app.run('0.0.0.0', debug=True, port=port, ssl_context=('/home/user/projects/myapp/server.crt', '/home/user/projects/myapp/server.key'))

This way I could overcome the SSL localhost problem for facebook canvas apps.

UPDATE: If you don't want to run the app as root,  just forward port 443 to 3000 and listen 3000 port with the following command as root:

iptables -t nat -A OUTPUT -p tcp --dport 443 -j REDIRECT --to-port 3000

and to cancel it:

iptables -t nat -D OUTPUT -p tcp --dport 443 -j REDIRECT --to-port 3000

Note that forwarding 443, you won't be able to connect SSL web sites throughout your pc.

Maybe using vagrant could be more elegant.

1 comment:

myfondillusion said...

Hello. I am trying to do something similar. I am trying to create a facebook app using localhost but I am having some trouble with it. I have created my own self signed certificate and have tried changing the host name. But none of that seems to solve the problem. My canvas facebook page still doesn't load. I am not sure where I am going wrong, I would appreciate any help/advice that you have. Many thanks.