I'm trying to use #csrf_protect in my services by following Cross Site Request Forgery protection article but it is not working for me.
This is my settings file
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
]
and this is how I'm Acquiring the token
var csrftoken = Cookies.get('csrftoken');
And this is how I'm configuring the $http provider with the cookie and header names:
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
But when I call any service, it returns 403 forbidden error. Any Idea what I'm missing or doing wrong?
Any kind of help will be appreciated.
Related
Can't figure out what's wrong with my Django DRF api endpoint. I'm getting a CORS error
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://127.0.0.1:8000/api/. (Reason: CORS
header ‘Access-Control-Allow-Origin’ missing). Status code: 200.
Problem is, I followed every step online to fix this.
I've installed 'django-cors-headers'
Added corsheaders app to INSTALLED_APPS above rest_framework
and the app that includes api endpoint.
Added cors middleware to the top of the middleware list in
settings.py
Added 'CORS_ALLOWED_ORIGINS = ('http://localhost:3000' # React
app) (Also tried with CORS_ORIGIN_ALLOW = True)
Quadruple-checked that API POST request includes a trailing slash.
Nothing seems to fix it. Am I forgetting something? Thanks for any help.
This is my settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'rest_framework',
'core.apps.CoreConfig',
]
CORS_ALLOWED_ORIGINS = (
'http://localhost:3000', # for localhost (REACT Default)
)
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.common.CommonMiddleware',
]
Not sure how revelant it is, but If I send POST request from insomnia, it works fine, but from React, it doesn't, this is my react request just in case:
const postSomeData = async () => {
const res = await axios.post(
"http://127.0.0.1:8000/api/",
{ promptQuery: "pls just work already" },
{
headers: {
"Content-Type": "application/json",
},
}
);
};
Thank you!
The code looks fine ,it seems middleware order issue. Would you try putting corsheader middle between sessionmiddleware and commonmiddleware ..
something like this :
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware', #here
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
since the order of middleware matters.
I Have implemented oauth2 login for users in a django app using the msal library following this guide https://medium.com/#madhok.simran8/how-to-setup-azure-oauth-2-0-sso-in-django-with-microsoft-graph-api-d2639b8f7e36.
However Im not able to set the request.user variable right, which in turn means i cant check if request.user.is_authenticated.
I believe this should be solved using the proper middleware, but Im not sure how to set it up.
This is my current middleware:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
I have read relevant question and understand what is cors.
I followed each step.
Install
pip install django-cors-headers
Add
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'a9.core.access.middleware.AccessMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
INSTALLED_APPS = ['corsheaders','otree']
And
python3 manage.py migrate
However, I still get the error:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.1
Is there something I am missing to make it work correctly?
Using 127.0.0.1 NOT localhost did the trik.
I have recently implemented Social Login to my Django site (which is working), but have encountered an issue where if I create a superuser using the terminal that superuser login does not work.
Middleware Section of Settings.py
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django_babel.middleware.LocaleMiddleware',
'graphql_jwt.middleware.JSONWebTokenMiddleware',
'saleor.core.middleware.discounts',
'saleor.core.middleware.google_analytics',
'saleor.core.middleware.country',
'saleor.core.middleware.currency',
'saleor.core.middleware.site',
'saleor.core.middleware.taxes',
'social_django.middleware.SocialAuthExceptionMiddleware',
'impersonate.middleware.ImpersonateMiddleware']
Authentication part of Settings.py
AUTHENTICATION_BACKENDS = [
'saleor.account.backends.facebook.CustomFacebookOAuth2',
'saleor.account.backends.google.CustomGoogleOAuth2',
'graphql_jwt.backends.JSONWebTokenBackend',
'django.contrib.auth.backends.ModelBackend']
Any help is really appreciated
MIDDLEWARE_CLASSES = (
'django.middleware.gzip.GZipMiddleware',
'htmlmin.middleware.HtmlMinifyMiddleware',
'django.middleware.http.ConditionalGetMiddleware',
'johnny.middleware.LocalStoreClearMiddleware',
'johnny.middleware.QueryCacheMiddleware',
'announce.middleware.AnnounceCookieMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.transaction.TransactionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'giaola.middleware.ForceDefaultLanguageMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'mediagenerator.middleware.MediaMiddleware',
'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
'minidetector.Middleware',
# Uncomment the next line for simple clickjacking protection:
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'breadcrumbs.middleware.BreadcrumbsMiddleware',
'achievements.middleware.AutoAchievementChecker',
)
These are all my middleware and I'm not entirely sure they're in the correct order.
I have my doubts about GZip and HTMLmin being at the top with caching following after them but middleware has always been my weakpoint in Django.
"ForceDefaultLanguageMiddleware" is just to enforce the language, like so:
def process_request(self, request):
if request.META.has_key('HTTP_ACCEPT_LANGUAGE'):
del request.META['HTTP_ACCEPT_LANGUAGE']
Any input would be more than appreciated.