I know that this problem is occurs many times here. But none of them has working for me right now. I've been struggling in this error since I change the protocol of my app to https using apache2 and LetsEncrypt. I try the configurations in settings but it doesn't solve the problem.
# settings.py
CSRF_COOKIE_DOMAIN = ".myapp.ml"
CSRF_COOKIE_SECURE = True
CSRF_USE_SESSIONS = True
SESSION_COOKIE_SECURE = True
Ofcourse in every forms with POST method required that I have has {% csrf_token %} in there. It also shows in request data. This errors occurs in Log in and Sign Up forms.
Inside the app after I add csrf_exempt in login and signup, I use DRF and when I make requests like POST, DELETE, PUT etc... It only shows the error {"detail":"CSRF Failed: Referer checking failed - no Referer."}
Here is my apache2 configuration file:
<IfModule mod_ssl.c>
<VirtualHost *:443>
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
ServerName www.myapp.ml
ServerAdmin webmaster#localhost
DocumentRoot /var/www/html
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
Alias /app /home/app/app-src/static_root
<Directory /home/app/app-src/static_root>
Require all granted
</Directory>
Alias /media /home/app/app-src/media
<Directory /home/app/app-src/media>
Require all granted
</Directory>
<Directory /home/app/app-src/Project>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIScriptAlias / /home/app/app-src/Project/wsgi.py
WSGIDaemonProcess Project python-path=/home/app/app-src python-home=/home/app/app-src/venv
WSGIProcessGroup Project
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
WSGIPassAuthorization On
SSLCertificateFile /etc/letsencrypt/live/www.myapp.ml/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/www.myapp.ml/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>
NOTE: That is only occuring when I use the HTTPS protocol.
UPDATE
I start to find the bug here and I found it on my OWN HTML FILE! I Literally forgot that one of my meta tags set the referrer to no-referrer so I just replace it with origin then everything works fine.
Related
I know this question has been asked several times, but I am all out of ideas and have been reading everywhere about this.
I am running Ubuntu 17.04 and Apache 2.4.25 to host a web server. I have generated my own SSL certificate. Since doing this, I am unable to view any images over SSL. Currently, I can confirm the path is working, the file is in tact and URL is correct, as I can access this typing the http URL into my browser.
If I go to the web inspector whilst loading my site, if I click on any image it gives me a 404 error.
How do I get these images to load over SSL.
My apache2 config is:
<VirtualHost *:80>
ServerName localhost
ServerAdmin info#****.com
DocumentRoot /var/www/****.com/pay
Redirect /secure https://****.com/
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
<VirtualHost *:443>
SSLEngine On
SSLCertificateFile /etc/ssl/certs/****.com.crt
SSLCertificateKeyFile /etc/ssl/private/****.com.key
SSLCACertificateFile /etc/ssl/certs/ca-certificates.crt
SetEnv SECRET_KEY ****
SetEnv PUBLISHABLE_****
ServerAdmin info#****.com
ServerName www.****.com
DocumentRoot /var/www/****.com/pay/static
WSGIDaemonProcess webtool threads=5 python-path=/var/www/****.com/pay
WSGIScriptAlias / /var/www/****.com/pay/webtool.wsgi
EnableMMAP off
EnableSendfile off
<Directory /var/www/****.com/pay>
Options +ExecCGI
WSGIProcessGroup webtool
WSGIApplicationGroup %{GLOBAL}
WSGIScriptReloading On
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
and I have a python script running to do my routes:
import os
import stripe
import cgi
print "Context-type: text/html"
from flask import Flask, render_template, request, redirect, send_from_directory
from flask import request
from flask import json
stripe_keys = {
'secret_key': os.environ['SECRET_KEY'],
'publishable_key': os.environ['PUBLISHABLE_KEY']
}
stripe.api_key = stripe_keys['secret_key']
app = Flask(__name__, static_url_path='')
#app.route('/')
def index():
return render_template('index.html', key=stripe_keys['publishable_key'])
#app.route("/hello")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(host="127.0.0.1", port="5050")
#app.route("/charge", methods=['POST'])
def charge():
# Amount in cents
amount = 500
customer = stripe.Customer.create(
email=request.form['stripeEmail'],
source=request.form['stripeToken']
)
charge = stripe.Charge.create(
customer=customer.id,
receipt_email=request.form['stripeEmail'],
amount=amount,
currency='usd',
description='Donation'
)
return render_template('charge.html', amount=amount)
I cannot work out if I need to set a route in my python script to allow images to be fetched, or I am missing something else.
I am calling the image in my index.html file with:
with the 'img' folder being in the same location as index.html. Please help.
Your image requests are being sent to WSGI, if you want Apache to handle them, you'll have to "undo" the WSGIScriptAlias of /.
I'm not a WSGI user, but it seems like you could block this from
running conditionally by putting this in your vhost:
RewriteEngine ON
RewriteRule ^/img/ - [L]
Even though this is a no-op, it should block this part of WSGi from running.
I had my API working well, but with DJango serving the entire document root, behind Apache. The team has decided they have some pieces that they want to serve out of the root (non-API) via apache directly, so I'm pushing the DJango WSGI reference from / to /api.
From:
WSGIScriptAlias / /opt/org/myproj/myapp/wsgi.py
To:
WSGIScriptAlias /api/ /opt/org/myproj/myapp/wsgi.py
The main urls.py went from:
urlpatterns = patterns('',
url(r'^api/', include(router.urls)),
to:
urlpatterns = patterns('',
url(r'^', include(router.urls)),
The problem is, when I hit the webserver at /api/ I do get the router URLs, but when I try to hit one of the actual URLs, I'm getting a 404. It's not actually dealing with any of the sub-URL references.
Hitting /api/ correctly gives:
{
address: "https://172.17.100.7/api/address/",
chassis: "https://172.17.100.7/api/chassis/",
configurationfile: "https://172.17.100.7/api/configurationfile/",
job: "https://172.17.100.7/api/job/",
node: "https://172.17.100.7/api/node/",
operatingsystem: "https://172.17.100.7/api/operatingsystem/"
}
Hitting /api/address gives:
Not Found
The requested URL /api/address/ was not found on this server.
Apache/2.2.22 (Debian) Server at 172.17.100.7 Port 443
Can someone provide some insight into how the URLs are supposed to be referenced in such a case? I thought this was going to be a pretty simple change, but I'm at a loss.
EDIT: Here's the full apache config.
WSGIScriptAlias /api/ /opt/org/myproj/myapp/wsgi.py
<VirtualHost *:80>
ServerAdmin webmaster#localhost
DocumentRoot /var/www
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</VirtualHost>
<VirtualHost *:443>
ServerAdmin webmaster#localhost
DocumentRoot /opt/org/myproj/root
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /opt/org/myproj/root/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
Alias /repo /opt/myorg/myproj/repo/
<Directory /opt/hp/moonshot/repo/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
ErrorLog /opt/myorg/myproj/logs/error.log
LogLevel warn
CustomLog /opt/myorg/myproj/logs/access.log combined
<Directory /opt/myorg/myproj/myapp>
<Files wsgi.py>
Order deny,allow
Allow from all
</Files>
</Directory>
# SSL Options
SSLEngine on
SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
<FilesMatch "\.(cgi|shtml|phtml|php)$">
SSLOptions +StdEnvVars
</FilesMatch>
BrowserMatch "MSIE [2-6]" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0
BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown
</VirtualHost>
From memory, use:
WSGIScriptAlias /api/ /opt/org/myproj/myapp/wsgi.py/api/
Put your Django stuff back to how it was.
This will only intercept sub url of '/api/' but the WSGI application will still think it is at the root of the site.
I am trying to get django to work on apache with mod_wsgi. My djang.wsgi code is:
import os, sys
sys.path.append('C:/djcode/mysite')
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
And my configuration in 'httpd' is:
Alias /static/ "C:/djcode/mysite/static/"
<Directory C:/djcode/mysite/static/>
Order deny,allow
Allow from all
</Directory>
WSGIScriptAlias / C:/djcode/mysite/apache/django.wsgi
<Directory C:/djcode/mysite/apache>
Order deny,allow
Allow from all
</Directory>
Alias /files/ "C:/djcode/mysite/files/"
<Directory C:/djcode/mysite/files/>
Order deny,allow
Allow from all
</Directory>
In the folder 'files' are files where I read data (not databases) which are used to output in templates.
The urls.py code is as follows:
urlpatterns = patterns('',
('^all/$', all),
('^(sport)/$', gen),
('^(teknology)/$', gen),
...
When I start Apache, localhost, the message is "It works!". But when I try localhost/all' or localhost/mysite or localhost/mysite/all, the browser says "The requested URL /all was not found on this server`. I can not understand where does it fail
Where is the definition or class for all? It's technically the controller. Can you post it?
This line routes it:
('^all/$', all)
But we don't know what all is.
Please make sure, you have the VirtualHost configuration correctly setup in the httpd.conf file. Try using localhost first (as the ServerName) and see if it works.
Am running with Python 2.7, Apache + mod_wsgi on CentOS 6.3
Things work fine when I am on localhost. However, when I run the code on a vm in Azure, I do not see the session information being persisted across pages.
Basically in my views, I have something like:
#frontend.route('/')
def index():
session['foo'] = 'bar'
print session['foo']
return redirect(url_for("frontend.page2"))
#frontend.route('page2')
def page2():
print session
The print output is:
bar
<SecureCookieSession {}>
My wsgi configuration for apache is:
WSGISocketPrefix /var/run/wsgi
<VirtualHost *:80>
ServerName example.com
ServerAlias example.com
WSGIDaemonProcess myproj threads=5 processes=5
WSGIScriptAlias / /home/mydir/myproj/apache/myproj.wsgi
<Directory /home/mydir/myproj>
WSGIScriptReloading On
WSGIProcessGroup myproj
WSGIApplicationGroup %{GLOBAL}
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
I have the secret_key set:
app.secret_key = os.urandom(24)
I have tried with both setting SERVER_NAME but it doesn't help:
app.config['SERVER_NAME'] = 'example.com'
Any ideas on how I can debug this more?
Thanks!
Don't use app.secret_key = os.urandom(24)!
You're supposed to enter a static value here, not read from os.urandom each time. You've probably misunderstood the example in the docs, it shows you how you can read random data from os.urandom, but it also clearly states:
Just take that thing and copy/paste it into your code and you’re done
If you read it at runtime, then each of your worker processes will have a different secret key! That means if a request is handled by a different worker, the session will break because the cookie is signed with the wrong secret key.
Running Django 1.2.5 on a Linux server with Apache2 and for some reason Django seems like it cannot store CSRF or Session cookies. Therefore when I try to login to the Django admin it gives me a CSRF verification error upon submitting the login form. Has anyone come up against this and found a solution?
I AM able to make a valid post when i try this at the url of my VPS that was provided by my host. Example: vps123.hostdomain.com/admin/ and for that domain the cookies DO get set. However, when I go to www.sitedomain.com/admin/ and try to login I get a CSRF 403 error saying the cookie is not there and when I check in my browsers cookies they are not set.
I have tried setting the following in my settings file:
SESSION_COOKIE_DOMAIN = 'www.sitedomain.com'
CSRF_COOKIE_DOMAIN = 'www.sitedomain.com'
Also tried:
SESSION_COOKIE_DOMAIN = 'vps123.hostdomain.com'
CSRF_COOKIE_DOMAIN = 'vps123.hostdomain.com'
I have 'django.middleware.csrf.CsrfViewMiddleware' added to my MIDDLEWARE_CLASSES in settings.py and there is a CSRF token in the form and it shows up in the POST.
I have cookies enabled. I have tried this on multiple browsers and machines.
There is a varnish proxy server sitting in front of www.sitedomain.com that I think may be part of the problem. Anyone with experience using proxy servers and Django may be able to shed some light on that.
My apache2 config:
NameVirtualHost *:80
<VirtualHost *:80>
ServerName www.sitedomain.com
ServerAlias www.sitedomain.com
<Location "/">
Options FollowSymLinks
SetHandler python-program
PythonInterpreter nzsite
PythonHandler django.core.handlers.modpython
PythonDebug On
PythonPath "['/var/www/django_projects', '/var/www', '/usr/lib/python2.6/dist-packages'] + sys.path"
SetEnv DJANGO_SETTINGS_MODULE project_one.settings
</Location>
<location "/phpmyadmin">
SetHandler None
</location>
</VirtualHost>
<VirtualHost *:80>
ServerName othersite.sitedomain.com
ServerAlias othersite.sitedomain.com
<Location "/">
Options FollowSymLinks
SetHandler python-program
PythonInterpreter ausite
PythonHandler django.core.handlers.modpython
PythonDebug On
PythonPath "['/var/www/django_projects', '/var/www', '/usr/lib/python2.6/dist-packages'] + sys.path"
SetEnv DJANGO_SETTINGS_MODULE project_two.settings
</Location>
<location "/phpmyadmin">
SetHandler None
</location>
</VirtualHost>
The problem was that I have a Varnish Proxy server in front of my site. Varnish was taking requests and stripping cookies from them. To fix this I had to have the company that is managing the Varnish Server add '/admin' to a list of exceptions so that cookies could be passed. Sorry I can't shed more light on how the Varnish process works.
Are you including the {{csrf_token}} in your form template?
<form autocomplete="off" method="post" action="{% url auth_login %}">{% csrf_token %}
{{form|as_p}}
<input type='submit' />
</form>
And including the middleware?
'django.middleware.csrf.CsrfViewMiddleware',
From your edit, at a guess, it might have something to do with the VirtualHost configuration in Apache (if your provider is using apache). Here is an edited version of one of my apache configurations.
<VirtualHost *:80>
ServerName www.domain.com
WSGIProcessGroup my-django-site
WSGIScriptAlias / /path-to-my-django-site/wsgi/production.wsgi
Alias /media /path-to-my-django-site/media
</VirtualHost>
It may be the case that the server name within apache has to match the domain name you are hitting the box at, along with the *_COOKIE_DOMAIN settings in your Django configuration. I'm not sure if you'll be able to change this though. Might be worth speaking to your provider if no other answers yield a win.
Are you updating your template data with the csrf info?
from django.core.context_processors import csrf
def index(request)
data = {"listitems": items}
data.updates(csrf(request))
return render_to_response('template.html', data)