Debian Codegraph @

docs/spa.rst

raw
1 Working with Single Page Applications
2 ======================================
3 `Single Page Applications (SPAs)`_ are a popular model for both separating
4 user interface from application/backend code as well as providing a responsive
5 user experience. Angular and Vue are popular JavaScript frameworks for writing SPAs.
6 An added benefit is that the UI can be developed completely independently (in a separate repo)
7 and take advantage of the latest JavaScript packing and bundling technologies that are
8 evolving rapidly, and not make the Flask application have to deal with things
9 like Flask-Webpack or webassets.
10
11 For the purposes of this application note - this implies:
12
13 * The user interface code is delivered by some other means than the Flask application.
14 In particular this means that there are no opportunities to inject context/environment
15 via a templating language.
16
17 * The user interface interacts with the backend Flask application via JSON requests
18 and responses - not forms. The external (json/form) API is described `here`_
19
20 .. _here: _static/openapi_view.html
21
22 * SPAs are still browser based - so they have the same security vulnerabilities as
23 traditional html/form-based applications.
24
25 * SPAs handle all routing/redirection via code, so redirects need context.
26
27 Configuration
28 ~~~~~~~~~~~~~
29 An example configuration:
30
31 .. code-block:: python
32
33 # no forms so no concept of flashing
34 SECURITY_FLASH_MESSAGES = False
35
36 # Need to be able to route backend flask API calls. Use 'accounts'
37 # to be the Flask-Security endpoints.
38 SECURITY_URL_PREFIX = '/api/accounts'
39
40 # Turn on all the great Flask-Security features
41 SECURITY_RECOVERABLE = True
42 SECURITY_TRACKABLE = True
43 SECURITY_CHANGEABLE = True
44 SECURITY_CONFIRMABLE = True
45 SECURITY_REGISTERABLE = True
46 SECURITY_UNIFIED_SIGNIN = True
47
48 # These need to be defined to handle redirects - these are part of the apps UI
49 # As defined in the API documentation - they will receive the relevant context
50 SECURITY_POST_CONFIRM_VIEW = "/confirmed"
51 SECURITY_CONFIRM_ERROR_VIEW = "/confirm-error"
52 SECURITY_RESET_VIEW = "/reset-password"
53 SECURITY_RESET_ERROR_VIEW = "/reset-password-error"
54 SECURITY_LOGIN_ERROR_VIEW = "/login-error"
55 SECURITY_POST_OAUTH_LOGIN_VIEW = "/post-oauth-login"
56 SECURITY_POST_OAUTH_VERIFY_VIEW = "/post-oauth-verify"
57 SECURITY_VERIFY_ERROR_VIEW = "/verify-error"
58 SECURITY_REDIRECT_BEHAVIOR = "spa"
59
60 # CSRF protection is critical for all session-based browser UIs
61
62 # enforce CSRF protection for session / browser - but allow token-based
63 # API calls to go through
64 SECURITY_CSRF_PROTECT_MECHANISMS = ["session", "basic"]
65 SECURITY_CSRF_IGNORE_UNAUTH_ENDPOINTS = True
66
67 # Send Cookie with csrf-token. This is the default for Axios and Angular.
68 SECURITY_CSRF_COOKIE_NAME = "XSRF-TOKEN"
69 WTF_CSRF_CHECK_DEFAULT = False
70 WTF_CSRF_TIME_LIMIT = None
71
72 # In your app
73 # Enable CSRF on all api endpoints.
74 flask_wtf.CSRFProtect(app)
75
76 # Initialize Flask-Security
77 user_datastore = SQLAlchemyUserDatastore(db, User, Role)
78 security = Security(app, user_datastore)
79
80 # Optionally define and set unauthorized callbacks
81 security.unauthz_handler(<your unauth handler>)
82
83 When in development mode, the Flask application will run by default on port 5000.
84 The UI might want to run on port 8080. In order to test redirects you need to set:
85
86 .. code-block:: python
87
88 SECURITY_REDIRECT_HOST = 'localhost:8080'
89
90 .. tip::
91 The `logout` endpoint doesn't take a body - be sure to add `content_type="application/json"`
92 header to your POST("/logout") request so that no redirection is done.
93
94 Client side authentication options
95 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
96 Depending on your SPA architecture and vision you can choose between cookie or token based authentication.
97
98 For both there is more documentation and some examples. In both cases, you need to understand and handle :ref:`csrf_topic` concerns.
99
100 Security Considerations
101 ~~~~~~~~~~~~~~~~~~~~~~~~
102 Static elements such as your UI should be served with an industrial-grade web server - such
103 as `Nginx`_. This is also where various security measures should be handled such as injecting
104 standard security headers such as:
105
106 * ``Strict-Transport-Security``
107 * ``X-Frame-Options``
108 * ``Content Security Policy``
109 * ``X-Content-Type-Options``
110 * ``X-XSS-Protection``
111 * ``Referrer policy``
112
113 There are a lot of different ways to host a SPA as the JavaScript part itself is quit easily hosted from any static
114 webserver. A couple of deployment options and their configurations will be describer here.
115
116 Nginx
117 ~~~~~
118 When serving a SPA from a Nginx webserver the Flask backend, with Flask-Security, will probably be served via
119 Nginx's reverse proxy feature. The JavaScript is served from Nginx itself and all calls to a certain path will be routed
120 to the reversed proxy. The example below routes all http requests to *"/api/"* to the Flask backend and handles all other
121 requests directly from JavaScript. This has a couple of benefits as all the requests happen within the same domain so you
122 don't have to worry about `CORS`_ problems::
123
124 server {
125 listen 80;
126 server_name www.example.com;
127
128 #access_log /var/log/nginx/host.access.log main;
129
130 root /usr/share/nginx/html;
131 index index.html;
132
133 location / {
134 try_files $uri $uri/ /index.html;
135 }
136
137 # Location of assets folder
138 location ~ ^/(static)/ {
139 gzip_static on;
140 gzip_types text/plain text/xml text/css text/comma-separated-values
141 text/javascript application/x-javascript application/atom+xml;
142 expires max;
143 }
144
145 # redirect server error pages to the static page /50x.html
146 # 400 error's will be handled from the SPA
147 error_page 500 502 503 504 /50x.html;
148 location = /50x.html {
149 }
150
151 # route all api requests to the flask app, served by gunicorn
152 location /api/ {
153 proxy_pass http://localhost:8080/api/;
154 }
155
156 # OR served via uwsgi
157 location /api/ {
158 include ..../uwsgi_params;
159 uwsgi_pass unix:/tmp/uwsgi.sock;
160 uwsgi_pass_header AUTHENTICATION-TOKEN;
161 }
162 }
163
164 .. note:: The example doesn't include SSL setup to keep it simple and still suitable for a more complex kubernetes setup
165 where Nginx is often used as a load balancer and another Nginx with SSL setup runs in front of it.
166
167 Amazon lambda gateway / Serverless
168 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
169 Most Flask apps can be deployed to Amazon's lambda gateway without much hassle by using `Zappa`_.
170 You'll get automatic horizontal scaling, seamless upgrades, automatic SSL certificate renewal and a very cheap way of
171 hosting a backend without being responsible for any infrastructure. Depending on how you design your app you could
172 choose to host your backend from an api specific domain: e.g. *api.example.com*. When your SPA deployment structure is
173 capable of routing the AJAX/XHR request from your JavaScript app to the separate backend; use it. When you want to use
174 the backend from another e.g. *www.example.com* you have some deal with some `CORS`_ setup as your browser will block
175 cross-domain POST requests. There is a Flask package for that: `Flask-CORS`_.
176
177 The setup of CORS is simple:
178
179 .. code-block:: python
180
181 CORS(
182 app,
183 supports_credentials=True, # needed for cross domain cookie support
184 resources="/*",
185 allow_headers="*",
186 origins="https://www.example.com",
187 expose_headers="Authorization,Content-Type,Authentication-Token,XSRF-TOKEN",
188 )
189
190 You can then host your JavaScript app from an S3 bucket, with or without Cloudfront, GH-pages or from any static webserver.
191
192 Some background material:
193
194 * Specific to `S3`_ but easily adaptable.
195
196 * `Flask-Talisman`_ - useful if serving everything from your Flask application - also
197 useful as a good list of things to consider.
198
199 .. _Single Page Applications (SPAs): https://en.wikipedia.org/wiki/Single-page_application
200 .. _Nginx: https://www.nginx.com/
201 .. _S3: https://www.savjee.be/2018/05/Content-security-policy-and-aws-s3-cloudfront/
202 .. _Flask-Talisman: https://pypi.org/project/flask-talisman/
203 .. _CORS: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
204 .. _Flask-CORS: https://github.com/corydolphin/flask-cors
205 .. _Zappa: https://github.com/Miserlou/Zappa