I want to display my documentation (a single-page application built with React) only after authentication with my backend.
My configuration :
Nginx acts as a reverse proxy for the backend (Django) and serves static files like single-page-applications.
Django, the backend, identifies the user and makes a request to Nginx using X-Accel-Redirect.
So I proceed as follows:
1) Authentication on Django
views.py
def get_doc(request):
if request.method == 'POST':
form = PasswordForm(request.POST)
if form.is_valid():
if form.cleaned_data['password'] == 'foo':
response = HttpResponse()
response['Content-Type'] = ''
response['X-Accel-Redirect'] = '/docs-auth/'
return response
else:
return HttpResponse("Wrong password")
else:
form = PasswordForm()
return render(request, 'docs/form.html', {'form': form})
urls.py
urlpatterns = [
path('docs/', views.get_doc, name='documentation'),
]
2) Nginx serves the single-page application
upstream backend {
server web:8000;
}
server {
location = /favicon.ico {access_log off;log_not_found off;}
...
location /docs {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
proxy_pass http://backend;
}
location /docs-auth/ {
internal;
alias /home/foo/docs/;
index index.html;
try_files $uri $uri/ /docs/index.html;
}
location / {
alias /home/foo/landing_page/;
error_page 404 /404.html;
index index.html;
try_files $uri $uri/ =404;
}
}
My problem is that the index.html file is served to the user but then the browser requests to access CSS and Javascript files are blocked because the browser cannot access the internal url.
Do you have any ideas to solve my problem?
I am also open to another way to serve a single-page application after backend authentication.
Thanks a lot.
You want to use the auth_request tag to make your life easier. Here is an example that you will need to retrofit unto your config. You could make your whole server require auth my just moving the auth_request tag to the top level outside of location
server {
...
location /docs {
auth_request /docs-auth;
...// Add your file redering here
}
location = /docs-auth {
internal;
proxy_pass http://auth-server;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-URI $request_uri;
}
}
I'm now deploying django projects on CentOS and have a problem with X-Accel-Redirect for protected file serving.
Here is my nginx.conf
server
{
listen 80;
server_name example;
index index.html index.htm index.php;
root /www/server/example;
charset UTF-8;
access_log /var/log/nginx/myproject_access.log;
error_log /var/log/nginx/myproject_error.log;
client_max_body_size 75M;
location /public/ {
root /www/wwwroot/myproject/;
}
location /media/ {
root /www/wwwroot/myproject/;
internal;
}
location / {
include uwsgi_params;
uwsgi_pass django;
}
...
}
Of course, protected files are on /www/wwwroot/myproject/media.
And corresponding python view file is following.
class ProtectedView(generics.GenericAPIView):
permission_classes = [IsAuthenticated]
def get(self, request, id, target):
file_name = "1.png"
response = HttpResponse()
response["X-Accel-Redirect"] = "/media/{0}".format(file_name)
response["Content-Disposition"] = "attachment; filename={0}".format(file_name)
return response
But server returns 404 error.
And the myproject_error.log is like this.
[error] 24570#0: *5 open() "/www/server/example/media/1.png" failed (2: No such file or directory), client: 174.11.13.81, server: example, request: "GET /protected-view/ HTTP/1.1", upstream: "uwsgi://0.0.0.0:8008", host: "40.1.12.23"
Maybe location /media/ {} block is not working. What problem? I have changed the permission but not working.
PS: I'm using django rest framework.
my main view is,
def main(request):
if request.user.is_authenticated:
return render(request,'main/main.html',{'use':use,'query':query,'noter':noter,'theme':request.user.profile.theme})
else:
return redirect('home')
the home page is responsible for serving login form is
def home(request):
if request.user.is_authenticated:
return redirect('main')
else:
return render(request,'home.html')
the "home.html" uses ajax to submit login page
$(document).ready(function(){
$('#form2').submit(function(event){
event.preventDefault();
$('#username_error').empty();
$("#password_error").empty();
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
var formdata={
'username':$('input[name=username2]').val(),
'password':$('input[name=loginpassword]').val(),
};
$.ajax({
type:'POST',
url:'/Submit/logging',
data:formdata,
dataType:'json',
encode:true,
headers:{
"X-CSRFToken": csrftoken
},
})
.done(function(data){
if(!data.success){//we will handle error
if (data.password){
$('#password_error').text(data.password);
}
if(data.Message){
$('#password_error').text("You can't login via pc");
}
blocker();
return false;
}
else{
window.location='/';
}
});
event.preventDefault();
});
this configuration is working fine but main page keeps redirecting to home.html even when though user is already logged in. I'm using nginx server whose configuration is
server {
server_name host.me www.host.me;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/username/projectname;
}
location /media/ {
root /home/username/projectname/appname;
}
location / {
include proxy_params;
proxy_pass http://unix:/home/username/projectname/projectname.sock;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/www.host.me/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/www.host.me/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}server {
if ($host = www.host.me) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = host.me) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
server_name host.me www.host.me;
return 404; # managed by Certbot
}
Edit 1
The urls of corresponding views are,
path('home',views.home,name='home'),
path('',views.main,name='main'),
path('Submit/logging',views.Loging,name='Loging'),
while my view for performing login is
def Loging(request):
if request.user_agent.is_pc:
return JsonResponse({'Message':'pc'})
else:
username1=request.POST['username']
print(username1)
username=username1.lower()
password=request.POST['password']
print(password)
user=authenticate(request,username=username,password=password)
if user is not None:
login(request,user)
return JsonResponse({'success':True})
else:
return JsonResponse({'password':'The user credentials do not exist in our database'})
Also if a user tries to access website from another url endpoint(say mywebsite.me/another) & already authenticated , then it will lead to the correct view which means login is performed correctly.
Question says it almost all.
E.g. changing default url (http://127.0.0.1:8000) to a custom (https://api.example.com/v1)
I'm using HyperlinkedModels and everything seems to work properly in development. Moving the app to another server with custom url is giving me problems.
How do I change the default url:
To a custom one, let's say:
https://api.example.org/v1/
You are mixing two questions in one:
How to run django-rest-framework project on a different domain
How to change URL path of API
To answer the first one I'd say, "Just do it". Django's reverse uses request's domain to build absolute URL.
UPDATE: don't forget to pass Host header from nginx/apache. Below is a sample nginx config:
server {
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://127.0.0.1:8000;
}
}
The second (path, mount point) is set in the urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from quickstart import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^v1/', include(router.urls)), # <-------------- HERE
]
I am looking to use Flower (https://github.com/mher/flower) to monitor my Celery tasks in place of the django-admin as reccomended in their docs (http://docs.celeryproject.org/en/latest/userguide/monitoring.html#flower-real-time-celery-web-monitor). However, because I am new to this I am a little confused about the way Flower's page is only based on HTTP, and not HTTPS. How can I enable security for my Celery tasks such that any old user can't just visit the no-login-needed website http://flowerserver.com:5555 and change something?
I have considered Celery's own documentation on this, but they unfortunately there is no mention of how to secure Flower's api or web ui. All it says: [Need more text here]
Thanks!
Update: My question is in part a duplicate of here: How do I add authentication and endpoint to Django Celery Flower Monitoring?
However, I clarify his question here by asking how to run it using an environment that includes nginx, gunicorn, and celery all on the same remote machine. I too am wondering about how to set up Flower's outside accessible url, but also would prefer something like https instead of http if possible (or some way of securing the webui and accessing it remotely). I also need to know if leaving Flower running is a considerable security risk for anyone who may gain access to Flower's internal API and what the best way for securing this could be, or if it should just be disabled altogether and used just on an as-needed basis.
You can run flower with --auth flag, which will authenticate using a particular google email:
celery flower --auth=your.email#gmail.com
Edit 1:
New version of Flower requires couple more flags and a registered OAuth2 Client with Google Developer Console:
celery flower \
--auth=your.email#gmail.com \
--oauth2_key="client_id" \
--oauth2_secret="client_secret" \
--oauth2_redirect_uri="http://example.com:5555/login"
oauth2_redirect_uri has to be the actual flower login url, and it also has to be added to authorized redirect url's in Google Development Console.
Unfortunately this feature doesn't work properly in current stable version 0.7.2, but it is now fixed in development version 0.8.0-dev with this commit.
Edit 2:
You can configure Flower using basic authentication:
celery flower --basic_auth=user1:password1,user2:password2
Then block 5555 port for all but localhost and configure reverse proxy for nginx or for apache:
ProxyRequests off
ProxyPreserveHost On
ProxyPass / http://localhost:5555
Then make sure proxy mod is on:
sudo a2enmod proxy
sudo a2enmod proxy_http
In case you can't set it up on a separate subdomain, ex: flower.example.com (config above), you can set it up for example.com/flower:
run flower with url_prefix:
celery flower --url_prefix=flower --basic_auth=user1:password1,user2:password2
in apache config:
ProxyPass /flower http://localhost:5555
Of course, make sure SSL is configured, otherwise there is no point :)
I have figured out it using proxy on Django side https://pypi.org/project/django-revproxy/. So Flower is hidden behind Django auth which is more flexible than basic auth. And you don't need rewrite rule in NGINX.
Flower 0.9.5 and higher
URL prefix must be moved into proxy path: https://github.com/mher/flower/pull/766
urls.py
urlpatterns = [
FlowerProxyView.as_url(),
...
]
views.py
class FlowerProxyView(UserPassesTestMixin, ProxyView):
# `flower` is Docker container, you can use `localhost` instead
upstream = 'http://{}:{}'.format('flower', 5555)
url_prefix = 'flower'
rewrite = (
(r'^/{}$'.format(url_prefix), r'/{}/'.format(url_prefix)),
)
def test_func(self):
return self.request.user.is_superuser
#classmethod
def as_url(cls):
return re_path(r'^(?P<path>{}.*)$'.format(cls.url_prefix), cls.as_view())
Flower 0.9.4 and lower
urls.py
urlpatterns = [
re_path(r'^flower/?(?P<path>.*)$', FlowerProxyView.as_view()),
...
]
views.py
from django.contrib.auth.mixins import UserPassesTestMixin
from revproxy.views import ProxyView
class FlowerProxyView(UserPassesTestMixin, ProxyView):
# `flower` is Docker container, you can use `localhost` instead
upstream = 'http://flower:5555'
def test_func(self):
return self.request.user.is_superuser
I wanted flower on a subdirectory of my webserver, so my nginx reverse proxy configuration looked like this:
location /flower/ {
proxy_pass http://localhost:5555/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Protocol $scheme;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_http_version 1.1;
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
}
Now I can get to flower (password-protected) via www.example.com/flower
Most of this is derived from the Flower documentation page about configuring an nginx reverse proxy:
http://flower.readthedocs.org/en/latest/reverse-proxy.html
I followed #petr-přikryl's approach using a proxy view. However I couldn't get it to verify authentication (I don't think test_func is ever called). Instead I chose to embed this in the Django Admin views and use AdminSite.admin_view() (as described here) to wrap the view with Django Admin authentication.
Specifically, I made the following changes:
# Pipfile
[packages]
...
django-revproxy="*"
# admin.py
class MyAdminSite(admin.AdminSite):
# ...
def get_urls(self):
from django.urls import re_path
# Because this is hosted in the root `urls.py` under `/admin` this
# makes the total prefix /admin/flower
urls = super().get_urls()
urls += [
re_path(
r"^(?P<path>flower.*)$",
self.admin_view(FlowerProxyView.as_view()),
)
]
return urls
# views.py
from __future__ import annotations
from django.urls import re_path
from revproxy.views import ProxyView
class FlowerProxyView(ProxyView):
# Need `/admin/` here because the embedded view in the admin app drops the
# `/admin` prefix before sending the URL to the ProxyView
upstream = "http://{}:{}/admin/".format("localhost", 5555)
Lastly, we need to make sure that --url_prefix is set when running flower, so I set it to run like this in our production and dev environments:
celery flower --app=my_app.celery:app --url_prefix=admin/flower
To offload the django app, I suggest you use the X-Accel-Redirect header in order to use nginx to proxy the Flower server. It goes as follow:
the user requests the flower path (e.g. /task)
nginx proxy_pass the request to your app, as usual
your django app chooses to accept or reject the request (e.g. based on authentification)
if your app accepts the request, it returns a response with X-Accel-Redirect HTTP-header together with a string of an internal location, i.e. a path that cannot be accessed directly by the user
nginx intercepts the response instead of forwarding it to the user and uses it as a new path with the possibility this time to access internal locations, in our case the Flower server
If the request is rejected, simply do not use X-Accel-Redirect and handle the case as any other rejected request you'd implement.
nginx.conf:
upstream celery_server {
server /var/run/celery/flower.sock;
}
upstream app_server {
server /var/run/gunicorn/asgi.sock;
}
server {
listen 80;
location /protected/task {
internal; # returns 404 if accessed directly
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_pass http://celery_server/task;
}
location / {
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $server_name;
proxy_pass http://app_server;
}
}
views.py:
from django.contrib.admin.views.decorators import staff_member_required
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
class XAccelRedirectResponse(HttpResponse):
def __init__(self, path, *args, **kwargs):
super().__init__(*args, **kwargs)
self['X-Accel-Redirect'] = '/protected' + path
del self['Content-Type'] # necessary
# I chose to only allow staff members, i.e. whose who can access the admin panel
#staff_member_required
#csrf_exempt
def task_app(request, path):
query_str = request.META['QUERY_STRING'] # you must keep the query string
return XAccelRedirectResponse(f'/task/{path}?{query_str}')
urls.py:
from django.urls import re_path
from app import views
urlpatterns = [
re_path('task/(?P<path>.*)', views.task_app, name='task'),
]
Flower
It is important to change the url-prefix of Flower:
celery flower --unix-socket="/var/run/celery/flower.sock" --url-prefix="task"
Yep there's not auth on flower, since it's just talking to the broker, but if you run it over SSL then basic auth should be good enough.
How would HTTP and HTTPS affect Celery security? What user logins are you referring to?
Flower monitors to a Celery queue by attaching to the workers. When setting up Flower you need to provide connection string [broker]://[user_name]:[password]#[database_address]:[port]/[instance]. User name and password are the credential to log into the database of your choice.
If you're referring to this login, wouldn't simply disable/remove their logins be suffice?
This is a reply to Petr Přikryl's post. django-revproxy fails to work on my Django 4.1.x project. I am encountering error AttributeError: 'HttpResponse' object has no attribute '_headers'. Many others are facing the same issue. brianmay in the issue thread claims, "I think this project is basically dead, sorry."
I went with a different library to serve as a workaround.
Install django-proxy
This is what my code looks like.
# urls.py
from django.urls import re_path
from myapp.views import flower
urlpatterns = [
re_path("flower/(?P<path>.*)", flower),
]
# views.py
from django.views.decorators.csrf import csrf_exempt
from proxy.views import proxy_view
#csrf_exempt
def flower(request, path):
extra_requests_args = {}
remoteurl = f"http://localhost:5555/flower/" + path
return proxy_view(request, remoteurl, extra_requests_args)
Then run celery with
$ celery --app myproject flower --loglevel INFO --url_prefix=flower
You can then view it in your browser, served through Django, at http://localhost:8000/flower/.
Additional notes:
--url_prefix= is important because this will allow the proxy to serve the static files that flower requests.
If you are using docker compose, then you will likely need to change the hostname in the remoteurl string in the flower function to reflect the same of the service. For example, my service is appropriately called flower in my docker-compose.yaml file. Therefore, I would change the string from f"http://localhost:5555/flower/" to f"http://flower:5555/flower/"