Using HTTPS with your Flask app

Using HTTPS is extremely important for your web applications. It has become even more important now that browsers like Chrome and services like Google are starting to shame websites that don't use it. If you are receiving data from users (e.g. emails, password, credit card information), you must use HTTPS if you want to provide them with some peace of mind.

If you want to learn more about HTTPS as a technology, you can read this.

This article shows how to enable HTTPS for your Flask applications running in a Linux server using nginx.

The domain name

The first step is to get a domain name. I recommend using Namecheap because they have good prices and generally seem like a nice bunch.

Decide on a domain name that you like, and purchase it! You can (or should) use WHOIS protection so your details are not available to the public.

Setting up Cloudflare

Once you've purchased the domain, we can set up Cloudflare.

Cloudflare is a service that sits in front of your domain. Whenever a user tries to access your domain, they will first go through Cloudflare. This means Cloudflare can do things like protect against denial of service attacks, speed things up via caches, and more.

One of the things it can do it allow you to use SSL by providing an SSL certificate if you use them.

When you log into Namecheap, you can manage your existing domain. Here you can change DNS settings. You'll need to use Cloudflare's DNS servers for Cloudflare to work.

Setting up DNS

  1. Log into Cloudflare.
  2. Select your domain.
  3. Go to the DNS tab in the menu.
  4. Halfway down the page, you'll see a section called "Cloudflare Nameservers".
  5. Keep the page open and log into Namecheap.
  6. Select "Manage" your domain.
  7. Under the "Domain" tab, find the "Nameservers" section.
  8. In the dropdown, select "Custom DNS".
  9. Enter there the addresses found in the Cloudflare page, one per field.

What we've done now is told Namecheap that we won't be using them at all for any domain-level traffic. Instead, we're going to use Cloudflare's servers for that.

We must now go back to the page we had open in Cloudflare, and in the "DNS Records" section, we will add our server.

Add an A record. The Name must be equal to your domain (e.g. jslvtr.com). The IPv4 Address must be equal to your server's IP address (which you can get from DigitalOcean if you are hosting there). Leave the TTL as Automatic, and you're ready to go!

You should now be able to access your server at http://yourdomain.tld. For this to work, it may take up to a few hours while DNS caches expire and changes propagate.

If you want to enable http://www.yourdomain.tld, all you have to do is add another record: CNAME, Name should be www and Domain name should be your domain name (e.g. jslvtr.com).

We still don't have HTTPS enabled though. Let's do that now.

Getting an SSL certificate

Before setting up for HTTPS, make sure your domain and associated web application works well. Access your domain name, and test the app using Postman if necessary.

When you're confident it is all working, go to the Cloudflare page and select the "Crypto" tab in the menu.

You may have to access this page using Google Chrome, as other browsers may not be able to generate the SSL certificates.

In the section "Origin Certificates", press the "Create Certificate" button. Here, you should see your domain name and a validity period (by default, 15 years). Press "Next", and you'll see your certificate created.

Don't close the window, and open a console that lets you log in to your server where you are hosting the web application.

Create a directory (e.g. /var/www/ssl/) where to store your SSL certificate. Here, create two files:

  • yourdomain.tld.key
  • yourdomain.tld.pem

In them, paste each of the contents of the fields in Cloudflare as they suggest in their instructions.

Setting up nginx

Now that you've got the SSL certificate (signed by Cloudflare) and you've created the files in your server, we are ready to tell Nginx to use them to encrypt the communications with the clients.

All we have to do is go to the web application's nginx config file (which currently might look like this):

server {  
    listen 80;

    server_name localhost;
    .
    .
    .

And we are going to change those lines to the following:

server {  
    listen 443 default_server;

    server_name jslvtr.com; # Replace with your domain

    ssl on;
    ssl_certificate /var/www/ssl/yourdomain.tld.pem;
    ssl_certificate_key /var/www/ssl/yourdomain.tld.key;

At the bottom of the file, we are also going to add another block, to make sure that port 80 is still accessible (that is, your site without HTTPS):

server {  
    listen 80;
    server_name jslvtr.com;
    rewrite ^/(.*) https://jslvtr.com/$1 permanent;
}

Remember to change jslvtr.com to your domain name where appropriate.

What this will do is allow users to connect to your domain using port 80 (HTTP), but then will immediately redirect them to the HTTPS version (port 443), for added security.


Make sure to test now that your site works well using HTTPS! If you encounter any problems, you can always revert the nginx changes and go back to using port 80. That way, your site will be accessible as normal, without using HTTPS.

Connecting to Linux servers

I’ve mentioned before how if you are deploying your application to a server, it will most likely be Linux. It is therefore important that you are able to connect to your Linux server and understand how that connection works.

This post is part of the "what is sudo?" series, which aims to help understand Linux and text consoles.

Remember when you rent a server, what you are renting is a real computer. When you connect to it, you are connecting to a computer, and so it behaves just like your desktop would.

If you don't currently have a server but you want one, you can follow this guide.

Connecting to a server is usually done in one of two ways:

  • Username and password; or
  • SSH keys.

In all cases, you would log in using the following command from your computer:

ssh <user>@<ip>  

If the user you are trying to log in as does not have a valid SSH key, then you will be prompted for a password. If the user you are trying to log in as has a valid SSH key, then the log in will just work, without the need for a password.

Username and password

This is the least secure of the two methods, because it relies on nobody else knowing your username and password. However, it does not require much set up and allows you to access the server from anywhere, as long as you know the username and password.

SSH keys

This is more secure, but it relies on nobody stealing your computer or your private keys.

SSH keys work on a per-login basis. Lets say you create an account in your server called jose. You can then put an SSH key into that account that will let you log in from your computer directly into that account, without using a password. The SSH key will not work for other accounts.

In your server, SSH keys are in the ~/.ssh/ folder, where, as you already know, ~ is the user’s home folder.

Generating SSH keys

From your computer, you can generate SSH keys using the command below (if you are using Mac or Linux):

$ ssh-keygen
Generating public/private rsa key pair.  
Enter file in which to save the key (/Users/yourname/.ssh/id_rsa):  
Enter passphrase (empty for no passphrase):  
Enter same passphrase again:  
Your identification has been saved in id_rsa.  
Your public key has been saved in id_rsa.pub.  
The key fingerprint is:  
(long number here)
The key's randomart image is:  
(random art here)

I would suggest just accepting the default file, and then enter a passphrase (a password) that you will remember. This is a way to secure your SSH key so that even if someone gains access to your computer, they still won’t be able to use the SSH key.

If you are using Windows, install https://git-for-windows.github.io, and then you will be able to run the command above from a program called "Git Shell".

Adding SSH keys to your server

Login to the server using username and password. Then, copy the contents of the SSH key file (in the example above, /Users/yourname/.ssh/id_rsa) and then:

vi ~/.ssh/authorized_keys  

Then, press i and paste the contents of your SSH key.

Now your SSH key will be accepted by that user in that server. Next time you connect to the server, you won't be asked for a password.

Contents of files and introduction to Vi

Let’s talk about reading and modifying files.

This post is part of the "what is sudo?" series, which aims to help understand Linux and text consoles.

The cat command

Using the cat command, you can view the text contents of a file:

cat my_file.txt  

You can also use cat to append to a file, and to overwrite a file.

The code below appends “Hello, world” to the file my_file.txt.

cat >> my_file.txt  
Hello, world

[CTRL+C]

The code below overwrites my_file.txt with the words “Hello, world”.

cat > my_file.txt  
Hello, world

[CTRL+C]

The vi command

Note, sometimes this command is vim (for vi “improved”).

Vi is a text editor. You can open files, edit them, and save them.

It is powerful, but it takes some getting used to.

Open files like so:

vi my_file.txt  

Here’s a quick list of commands:

  • i gets you into ‘Insert’ mode. Think of this as your normal text editor mode, where you can write characters, use your backspace, etc…
  • v gets you into Visual mode, where you can select characters.
  • V gets you into Visual (line) mode, where you can select lines.
  • ESC gets you out of any mode.
  • While not in a mode, :w saves the file to disk.
  • While not in a mode, :q quits the current file.

You can chain the last two commands like so: :wq, so save and quit.

If you want to learn how to use Vi well, I recommend this: http://vim-adventures.com

A word on programs

A common misconception is that things like mkdir, rm or adduser are different from things you install in your system (e.g. postgresql, or mongod).

They are not.

All of them are programs. Some already come installed, and others you have to install yourself. They are not “magically built-in”.

You can find out where a program executable lives using the which program:

$ which mkdir
/bin/cd
$ which which
/usr/bin/which

However, there are some built-in commands in the Bourne Again SHell (BASH). They are not very many:

  • alias;
  • cd;
  • wait;
  • and a few others

If you try executing which cd, chances are it will not be found, because it is using the built-in command, as opposed to a program.

Some built-in commands, such as kill, are sometimes overwritten by the distribution.

It is important that you know which commands are available to you. Some consoles may not use BASH, and so the cd command might not be available. An example of this is the Windows console, which uses chdir instead.

Most Linux distributions use BASH, so you won’t have a problem with that.

Getting help

Most Linux distributions come with a very handy program called man. You can use this program to get the help pages of many other programs.

For example, execute the following command:

man mkdir  

You can even get the help pages on BASH built-in commands:

man cd  

It was a short blog post today, but the key thing to remember is that the commands you are executing in your console are really programs which have been installed in your system. They can be un-installed, they can be overwritten, or they can just not be there yet.

You can install programs such as man and other programs that you might expect to already be there. We'll get to package managers in the next post!

Basic Linux console commands

Just like navigating a desktop, it is important to be able to navigate a console.

This post is part of the "what is sudo?" series, which aims to help understand Linux and text consoles.

Dealing with files

Every folder in a system except the root folder is inside another folder. This other folder is the parent folder. The root folder, or top-most folder, is the folder that contains everything in your system.

The root folder is: /.

Some users in your system have associated "home" folders. You can think of this folder as where a user would normally put their own "Documents", "Photos", etc.

Whenever you use a system, you must be logged in as a specific user. Let's find out what your current user is.

Open a console, and type the following command:

whoami  

This will tell you the name of the user you are currently logged in as.

Next, lets navigate to your user's "home" folder:

cd ~  

The cd command performs a change directory command. The ~ folder is the current user's "home" folder.

Creating files and folders

To create a folder, we use the mkdir command.
To create an empty file, we use the touch command.

# This creates a folder 'documents' inside your home folder.
mkdir ~/documents

# This creates an empty file 'hello.txt' in the documents folder.
touch ~/documents/hello.txt  

If we want to create a folder inside another folder, neither of which exist:

mkdir -p ~/documents/work/journal  

This creates a folder called 'work', and then a folder called 'journal' inside it. If we omit the -p, then it gives an error because it attempts to create the 'journal' folder inside a folder that doesn’t yet exist ('work').

Deleting files and folders

Finally, lets look at deleting. We delete using the rm command.

# This deletes the file 'hello.txt'
rm ~/documents/hello.txt  
# This deletes the folder 'work', including everything it contains
rm -rf ~/documents/work  

The -rf argument is required in order to delete folders. This is because we want to delete everything inside the folder, as well as the folder. The r stands for "recursive", which tells the rm command to go into each sub-folder and delete everything in it. The f argument attempts to delete files even if they are not owned by the currently logged in user.

Review

  • whoami shows the currently logged in user.
  • cd [args] changes directory to another directory.
  • mkdir [-p] [args] creates a directory.
  • touch [args] creates an empty file.
  • rm [-rf] [args] removes a file or directory.