HTTPS in local environment for Angular + Flask project.



Sometimes it is important to run project in local environment with HTTPS. For example when you use third party authentication system in our app. In my case I prefer to have local instance similar as mush as possible to the production. Moreover, it’s easy to implement.

First what you need is the ssl key. You can follow this article to create it
https://devcenter.heroku.com/articles/ssl-certificate-self

Create your ssl key in ./key project folder. Finally it should look like this

[dmnbrest@~/Documents/myPython/blog2/project/key]$ ls
server.crt server.csr server.key

Add HTTPS support to the FLASK:

Update init section in your backend server file (./backend/app.py) this way
if __name__ == "__main__":
    context = ('./key/server.crt', './key/server.key')
    app.run(ssl_context=context, host='0.0.0.0', debug=True)

But now we need to run backend with other command
python ./backend/app.py

This time you should see this output in console (line: Running on ...):
(project-RO4ptYog) bash-3.2$ python ./backend/app.py 
 * Tip: There are .env or .flaskenv files present. Do "pip install python-dotenv" to use them.
 * Serving Flask app "app" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on https://0.0.0.0:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Tip: There are .env or .flaskenv files present. Do "pip install python-dotenv" to use them.
 * Debugger is active!
 * Debugger PIN: 230-651-600


Add HTTPS support to the ANGULAR:

Update "start" script in package.json with this value:

"start": "cd ./frontend && ng serve --ssl true --ssl-key \"../key/server.key\" --ssl-cert \"../key/server.crt\" --public-host \"https://localhost:4200\" --disable-host-check",

and restart angular. Now you should see https://localhost:4200/ in the output.

chunk {main} main.js, main.js.map (main) 50.6 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 270 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 10.1 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 4.09 MB [initial] [rendered]
Date: 2020-03-10T08:53:16.195Z - Hash: ee144b1f785e02a75a1a - Time: 8775ms
** Angular Live Development Server is listening on localhost:4200, open your browser on https://localhost:4200/ **
「wdm」: Compiled successfully.

The last step is to modify home template to reference angular from right source. Replace all http://localhost:4200 with https://localhost:4200

PS: Don't forget to add your new ./key folder to .gitignore


Comments

Popular posts from this blog

Salesforce Authentication 2 (Token Validation and Refresh)

User authentification with Flask-Login