Bobcares

NGINX Flask AUTH | Beginners Guide

by | Apr 23, 2024

Let’s discuss the basic auth between NGINX and Flask app. As part of our Server Management Service, Bobcares provides answers to all of your questions.

Basic Auth between NGINX and Flask

In this article, we’ll explain the setup and usage of authentication between the frontend Nginx proxy and the backend Flask app.

1. Backend Authentication:

The backend uses Flask-BasicAuth, where authentication details are setup within the Flask app. Here’s the relevant section of the Flask app (flask-app/app.py):

from flask import Flask
from flask_basicauth import BasicAuth

app = Flask(__name__)
basic_auth = BasicAuth(app)

app.config['BASIC_AUTH_USERNAME'] = 'bob'
app.config['BASIC_AUTH_PASSWORD'] = 'matrix'

@app.route('/secret')
@basic_auth.required
def secret_view():
return 'authorized'

In this setup:

BASIC_AUTH_USERNAME is ‘bob’.

BASIC_AUTH_PASSWORD is ‘matrix’.

The /secret route is protected and requires authentication using Flask-BasicAuth.

2. Frontend Proxy:

The frontend, managed by Nginx, employs basic authentication to protect access. Here’s the Nginx setup (nginx/nginx-flask.conf):

server {
listen 80;
server_name _;

location / {
auth_basic "Restricted access to this site";
auth_basic_user_file /etc/nginx/passwords;
proxy_pass http://flask-app:5000;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Authorization "Basic am9objptYXRyaXg=";
}
}

3. Usage: To deploy the stack and test authentication, we must run the following steps.

i. Initially, we must clone the repository and go to the directory:

git clone https://github.com/ruanbekker/flask-basic-auth-nginx
cd flask-basic-auth-nginx

ii. Then, build and start the containers:

docker-compose up --build -d

iii. Now, we make requests to test authentication:

To make a request without authentication:

curl http://localhost:8080

Now, to make a request with authentication (non-protected route):

curl -u "nginxuser:password" http://localhost:8080/welcome

To make a request with authentication (protected route on the backend):

curl -u "nginxuser:password" http://localhost:8080/secret

These steps will now setup an authentication between the frontend Nginx proxy and the backend Flask app.

[Want to learn more? Reach out to us if you have any further questions.]

Conclusion

With this setup, NGINX will prompt users for authentication before allowing access to the Flask.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Never again lose customers to poor
server speed! Let us help you.