Django doesn't create session cookie in cross-site json request - django

I want to make cross-site JavaScript call from third-party domain (in this case my desktop/localhost server) to my remote Django server hosted on my_domain.com/ and calling REST WS exposed on my_domain.com/msg/my_service with using session/cookies for storing session state.
But when I call this service (hosted on remote Django server) from my desktop browser or localhost Django server (JS is in index.html), Django doesn't create session cookie and on remote server are doesn't store session state. But when i call this service from Postman or from same localhost JS to localhost instance of same Django service it works and session is created.
My JS script in index.html which make call to WS send_message:
fetch('http://my_domain.com/ws/my_service', {
method:"POST",
credentials: 'include',
body:JSON.stringify(data)
})
.then(res => res.json())
.then(json => {
showResponse(json.message);
})
When I run this script from my desktop browser or my localhost server it runs correctly with cookies and sessions parameters.
Django my_service implementation view
#csrf_exempt
def my_service(request):
if request.method == "POST":
message_bstream= request.body
request.session.set_expiry(0)
message= json.loads(message_bstream)
out,sta=state_machine_response(message["message"],int(request.session["state"]))
request.session["state"] =sta
respo={"message":out}
response = HttpResponse(json.dumps(respo), content_type="application/json")
response.set_cookie(key='name', value='my_value', samesite='None', secure=True)
#return JsonResponse(respo, safe=False, status=200)
return response
else:
return HttpResponseNotFound ("Sorry this methode is not allowed")
Or I try generate response like
return JsonResponse(respo, safe=False, status=200)
My settings.py
INSTALLED_APPS = [
...
'corsheaders',
]
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
'http://localhost:8000',
)
CORS_ALLOWED_ORIGINS = [
'http://localhost:8000',
]
CSRF_TRUSTED_ORIGINS = [
'http://localhost:8000',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SAMESITE = 'None'
Please do you have any idea?

You can't save cookies from a third-party API call unless you use SameSite=None with the Secure option in the Set-Cookie header. You can achieve this for the sessionid and CSRF cookie with the following settings:
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SAMESITE = 'None'
In this case, you must use the HTTPS protocol scheme.
Another solution would be to use a proxy, which is helpful in a localhost development environment. This is an example using vue.js on the vue.config.js file:
const { defineConfig } = require('#vue/cli-service')
if (process.env.NODE_ENV == "development"){
module.exports = defineConfig({
transpileDependencies: true,
devServer: {
proxy: {
"^/api/": {
target: process.env.VUE_APP_BASE_URL,
changeOrigin: true,
logLevel: "debug",
pathRewrite: { "^/api": "/api" }
}
}
},
})
}
Some useful doc https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure

Related

CORS policy blocks XMLHttpRequest

With Ionic Angular running in on my localhost I made this call to my Django backend (running on different localhost):
test() {
return this.httpClient.get(endpoint + '/test', {
headers: { mode: 'no-cors' },
});
}
And on the backend side I have following code to respond:
#csrf_exempt
def test(request):
response = json.dumps({'success': True})
return HttpResponse(response, content_type='application/json', headers={'Access-Control-Allow-Origin': '*'})
I have also this in my settings.py file:
INSTALLED_APPS = [
...
'corsheaders',
]
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
]
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True
Still, I get this error message in my console:
Access to XMLHttpRequest at 'http://127.0.0.1:8000/test' from origin 'http://localhost:8100' has been blocked by CORS policy: Request header field mode is not allowed by Access-Control-Allow-Headers in preflight response.
What am I doing wrong?
You need to just add one more setting
CORS_ALLOW_ALL_HEADERS=True
Other than the above you do not need to set a header on each response. Just simply respond back with payload as
#csrf_exempt
def test(request):
response = json.dumps({'success': True})
return HttpResponse(response, content_type='application/json', headers={'Access-Control-Allow-Origin': '*'})

How to solve django and angular cors errors

I'm developing application and got this error:
Access to XMLHttpRequest at 'https://subdomain.domain.org/api/parks/?page_size=6&page_number=1' from origin ''https://subdomain.domain.org' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Django Config
setting.py:
INSTALLED_APPS = [
...
'corsheaders',
...
]
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
ALLOWED_HOSTS = ['app_name-backend.herokuapp.com']
CORS_ALLOWED_ORIGINS = [
'https://app_name-frontend.herokuapp.com',
'https://subdomain.domain.org',
]
CORS_ALLOW_ALL_ORIGINS = False
Angular Requests
service.ts:
getParks(filters: any=null, parameters:any=null): Observable<any> {
...
var httpHeaders = new HttpHeaders();
httpHeaders.set('Content-Type', 'application/json');
httpHeaders.set('Access-Control-Allow-Origin', '*');
var requestUrl = this.baseServiceUrl + this.serviceUrl;
return this.httpClient.get<any>(requestUrl, { params: httpParams, headers: this.httpHeaders })
.pipe(
...
),
catchError(this.handleError<Park[]>('Park getParks', []))
);
}
The front and back are hosted on heroku
Any idea how to fix it ?
Thanks in advance.

Django saml2 login missing session variables

For my Django application, I am trying to enable SSO using Djangosaml2 and following are the versions I am using
djangosaml2==1.2.0
pysaml2==7.0.0
djangorestframework==3.12.2
Django==3.1.7
python==3.8
My saml2_settings is as follows
from os import path
import saml2
import saml2.saml
from app.local_settings import SERVER_URL
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'djangosaml2.backends.Saml2Backend',
)
SAML_SESSION_COOKIE_NAME = 'saml_session'
SAML_ATTRIBUTE_MAPPING = {
'username': ('username', ),
'email': ('email', ),
'first_name': ('first_name', ),
'last_name': ('last_name', ),
}
BASEDIR = path.dirname(path.abspath(__file__))
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
LOGIN_URL = '/saml2/login/'
LOGOUT_URL = '/saml2/logout/'
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SAML_CREATE_UNKNOWN_USER = True
SAML_SERVER_URL = '10.23.1.114'
SAML_ENABLED = True
# MIDDLEWARE.append('djangosaml2.middleware.SamlSessionMiddleware')
SAML_CONFIG = {
# full path to the xmlsec1 binary programm
'xmlsec_binary': '/usr/bin/xmlsec1',
# your entity id, usually your subdomain plus the url to the metadata view
'entityid': path.join(SAML_SERVER_URL, 'saml2/metadata'),
# directory with attribute mapping
'attribute_map_dir': path.join(BASEDIR, 'attribute_maps'),
# this block states what services we provide
'service': {
# we are just a lonely SP
'sp' : {
'name': 'Dummy app',
'allow_unsolicited': True,
'authn_requests_signed': True,
'force_authn': True,
'want_response_signed': True,
'want_assertions_signed': True,
'logout_requests_signed': True,
'name_id_format_allow_create': False,
'endpoints': {
# url and binding to the assetion consumer service view
# do not change the binding or service name
'assertion_consumer_service': [
(path.join(SAML_SERVER_URL, 'saml2/acs/'),
saml2.BINDING_HTTP_POST),
],
# url and binding to the single logout service view
# do not change the binding or service name
'single_logout_service': [
(path.join(SAML_SERVER_URL, 'saml2/ls/'),
saml2.BINDING_HTTP_REDIRECT),
(path.join(SAML_SERVER_URL, 'saml2/ls/post/'),
saml2.BINDING_HTTP_POST),
],
},
},
},
# where the remote metadata is stored, local, remote or mdq server.
# One metadatastore or many ...
'metadata': {
'local': [path.join(BASEDIR, 'idp_metadata.xml')]
},
# Signing
'key_file': path.join(BASEDIR, 'samlkey.key'), # private part
'cert_file': path.join(BASEDIR, 'samlcert.pem'), # public part
# own metadata settings
'contact_person': [
{'given_name': '--',
'company': '--',
'email_address': '--',
'contact_type': '--'}
],
# you can set multilanguage information here
'organization': {
'name': [('--', 'en')],
'display_name': [('--', 'en')],
'url': [('--', 'en')],
},
"valid_for": 24
}
My middleware is as follows:
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.security.SecurityMiddleware',
'user_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',
'app.middleware.APPMiddleware',
'djangosaml2.middleware.SamlSessionMiddleware'
]
With the above mentioned settings I am facing a couple of issues
After successfully authenticating from my SSO server by the time the request reaches my /login Url both the request.session and request.saml_session variables are getting reset and I am getting a complete new session ID. And also I am missing the saml_session attributes due to this issue. I did add a debug point in the djangosaml2 views and in there just before returning the response I could see the attributes present. But for some reason by the time the request reaches my app, its getting reset.
When I try to logout on saml2/logout, I am seeing the following error:
'NoneType' object has no attribute 'name_qualifier'
I cant seem to find what I am missing here. I have tried all I could think of but stuck. Any help is greatly appreciated. Thanks in advance.
I ended up doing the following two things, then it started working for me
Downgraded the djangosaml2 and pysaml version to 0.19.0 and 4.9.0 respectively.
For HTTPS connection, added SESSION_COOKIE_SECURE = True and for dev i.e. run server cases, SESSION_COOKIE_SECURE = False in your settings.py
I was migrating Django from 1.1 to 3.1. Your codebase actually fixed my issue. I added the SESSION_SERIALIZER in my saml/config.py:
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
And added SamlSessionMiddleware in settings.py:
djangosaml2.middleware.SamlSessionMiddleware
My issue was:
'WSGIRequest' object has no attribute 'saml session'

Looking for some help on Django authentication with Angular login page

I have an angular login page that sends an Ajax request to my django server (listening on a separate port from the angular application), and I am able to log my user in but a session cookie is not getting returned in the response for the client to store in the angular app. Here is what my backend settings.py looks like the for authentication specific stuff:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',]
# Here are the session specific settings
SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_AGE = 1800 # The age of session cookies, in seconds
CORS_ORIGIN_ALLOW_ALL = True
And here is my login view function that is hooked up to my login path:
#csrf_exempt
#require_POST
def login_view(request: HttpRequest):
payload = request.body.decode()
body = json.loads(payload)
username = body['username']
password = body['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)# Log the user in
return HttpResponse('Success')
else:
return HttpResponseBadRequest()
I am trying to used cookie/ session based authentication so that if the user closes the page and relaunches it before the session time has expired, it will direct them back to the landing page, and for a specific input select field only certain options are supposed to be returned based on the user, and that would need to be handled via the session authentication. Is there something that is not correct in my settings file?
Try to set SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE to False, maybe because your request is insecure
Django CSRF Cookie Not Set

Redirect is not allowed for a preflight request

I have this problem where i get the response when trying to use a rest api: "Access to fetch at 'https://kollektivet.app:8082/api/login/' from origin 'https://kollektivet.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request."
Picture of response when trying to fetch
This happens when i try any of the rest api's I am using. From what i have read, this error means I am trying to re-direct, which I am not.
The backend is Django and looks like this:
#csrf_exempt
#api_view(["POST"])
#permission_classes((AllowAny,))
def register(request,):
password = request.data.get("password", "")
email = request.data.get("email", "")
if not email and not password and not email:
return Response(
data={
"message": "username, password and email is required to register a user"
},
status=status.HTTP_400_BAD_REQUEST
)
new_user = User.objects.create_user(
email=email, password=password
)
return Response(status=status.HTTP_201_CREATED)
And the front-end is in react which looks like this:
createUser(event) {
event.preventDefault();
let data = {
name: this.state.name,
password: this.state.password,
repeatPassword: this.state.repeatPassword,
email: this.state.email
};
if (this.state.name !== '' && this.state.password !== '' && this.state.email !== '' && this.checkPasswords()) {
console.log('name', this.state.name, 'password ', this.state.password, 'email ', this.state.email);
fetch("https://kollektivet.app:8082/api/register/", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
mode: "cors",
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
this.setState({message: "Du er nå registrert! For å aktivere din konto trykk på linken som vi har sendt til deg på epost"});
this.setState({name: ""});
this.setState({password: ""});
this.setState({repeatPassword: ""});
this.setState({email: ""});
}
}
I Do have this is the Django settings file:
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_HEADERS = (
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
)
I am running this on apache2 if this is relevant.
The port 8082 is also closed. Does this need to be open when it is on the same server?
Thanks!
You're being redirected to site.site.comapi/register/
Do you have some other middleware that does this? Maybe in Apache config?
Note it's a 301 so your browser has cached this response and will now always redirect there even if your rove the code that resulted in this redirect, or even if you stop Django from running.
So you will need to also clear your redirect cache in the browser.
This is why I don't like 301 responses. 302 are much more polite.
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
"corsheaders.middleware.CorsMiddleware",
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
In settings.py, if I arrange my MIDDLEWARE array like this, it will work fine.
But if I move corsheaders.middleware.CorsMiddleware to the last line, that error will occur
Just writing my story here in case anybody may have the same issue as mine.
Basically, this is a server end issue, so no need to change anything at the front end.
For this error message, it indicated that the OPTIONS requests got a
response with the status code in either 301 Moved Permanently", "307
Temporary Redirect", or "308 Permanent Redirect".
Please check your requested URL with the 'location' attribute from the OPTIONS response, see if they are the same or not.
For me, the issue was my request URL is **"https://server.com/getdata"**
but the URL I set on the server was **"https://server.com/getdata/"**
then the server give me an 308 to correct it with the '/', this works for POST, GET and HEAD, but not OPTIONS.
I'm using flask, flask_restful and the flask_cors.
use this will also solve this redirect issue for me.
app.url_map.strict_slashes = False
I had the same problem until I discovered that the redirect was caused by the Django internationalization framework, where all urls get a i18n url extension such as /en/path_to_resource when actually path_to_resource was requested. The internationalization framework achieves this through a 302 redirect.
The solution to this problem is to keep the rest-api urls outside the section with the i18n_patterns. The resulting urls.py might then look like
urlpatterns = [
path('i18n/', include('django.conf.urls.i18n')),
path('rest/', include(('rest.urls', 'rest'), namespace='rest')),
]
urlpatterns += i18n_patterns(
path('admin/', admin.site.urls),
path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'),
path('my_app/', include(('my_app.urls', 'my_app'), namespace='my_app')),
)