Windows authentication with Django and Angular? - django

I am trying to implement the single sign-on using Angular, Django, IIS server.
In IIS windows authentication is enabled.
Angular intercepter code :
intercept(req: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {
console.log("in intercept")
req = req.clone({
withCredentials: true });
return next.handle(req); }
Django settings.py:
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.auth.middleware.RemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',]
AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.RemoteUserBackend',)
CORS_ORIGIN_ALLOW_ALL = True
ALLOWED_HOSTS = ["*"]
Getting error:
(IP-address) 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.

Try this configuration in settings.py
CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_CREDENTIALS = True # This one is required when you are using withCredentials: true

The problem will lie in the Django setup, please have a look at this link: https://stackoverflow.com/a/38162454/4587598
If at first try won't work, strip all settings.py and setup from scratch, firstly checking if CORS issue does not occur and afterwards add authentication complexity.

try django-cors-headers
pip install django-cors-headers
And set it up
In your settings.py
INSTALLED_APPS = (
...
'corsheaders',
...
)
You will also need to add a middleware class to listen in on responses:
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
CorsMiddleware should be placed as high as possible, especially before any middleware that can generate responses such as Django's CommonMiddleware
CORS_ORIGIN_ALLOW_ALL = True

Related

Access to fetch at **link** from origin 'http://localhost:3000' has been blocked by CORS policy

I'm trying to exchange the authorization code for an access token for a Google Calendar integration. I was following Using OAuth 2.0 for Web Server Applications. The examples shown there were for Flask, but I'm using Django. The problem is, I can't redirect to authorization_url because it says
Access to fetch at link from origin 'http://localhost:3000' 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.
#api_view(['GET'])
def authorize(request):
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
CLIENT_SECRETS_FILE,
scopes=SCOPES)
flow.redirect_uri = 'http://localhost:3000/'
authorization_url, state = flow.authorization_url(
access_type='offline',
include_granted_scopes='true')
response = redirect(authorization_url)
return response
However in my settings.py I have:
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
"http://127.0.0.1:3000",]
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
'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',
]
You can have a look at this package: https://pypi.org/project/django-cors-headers/
So you can try to add the origin to "Trusted Origins" in Django settings:
CSRF_TRUSTED_ORIGINS = ['www.something.com']
or like that, for all origins (do not recommend):
CORS_ALLOW_ALL_ORIGINS = True

cors policy error : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin

I have installed django-cors-headers and this is settings.py :
ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS","").split()
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.auth.middleware.RemoteUserMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
and also :
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True
but i got this error in chrome consloe:
Access to XMLHttpRequest at 'https://event-alpha.mizbans.com/api/meetings/?memory=0' from origin 'https://alpha.mizbans.com' 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.
I had a similar issue and it was all about CORS_ALLOW_ALL_ORIGINS. It turns out it doesn't work well with something else (sorry don't remember what anymore, maybe authentication). So i Had to add specific origins. This is my entire setup:
# CORS SETUP
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
'http://localhost:4200',
'http://127.0.0.1:4200'
]
CSRF_COOKIE_HTTPONLY = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = 'None'
CSRF_COOKIE_SAMESITE = 'None'
For me it works now with this combination.

CORS issue with react and django-rest-framework

I'm using react on the frontend side and Django on the backend. I using django-cors-headers
for managing CORS in my Django app.
I have added the package in INSTALLED_APPS like this:-
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework.authtoken',
'rest_framework',
'corsheaders',
'services',
'feeds',
'knox',
'users',
]
then I have also added same in MIDDLEWARE
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'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',
'django.middleware.common.CommonMiddleware',
]
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
ALLOWED_HOSTS = ['*']
and I'm passing CORS headers from my client-side React app like:-
const Axios = axios.create({
baseURL: `${BASE_URL}/api`,
timeout: 1000,
headers: {
'X-Custom-Header': 'foobar',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
})
Error on frontend:-
Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/register' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
Access-Control-Allow-Origin header is sent by server, not by frontend. Server also does not send this header always. Whenever client sends origin header, only then server sends Access-Control-Allow-Origin and when origin is not matched, CORS error in thrown. If you used create-react-app to bootstrap your react project, they have really nice documentation how to configure proxy, that way you dont have to configure CORS on backend. In django configuration try to remove ALLOWED_HOSTS = ['*'] line, CORS_ORIGIN_ALLOW_ALL = True should work for all.
there was a bug in my client-side headers'X-Custom-Header': 'foobar', after removing it started working fine

No 'Access-Control-Allow-Origin' header is present on the requested resource Django and ReactJS

Currently I have Django 1.98 as Backend and React as Front End.
I'm getting this error:
Access to XMLHttpRequest at
'https://mywebsite:8000/uploads/vtt/' from origin
'http://localhost:3000' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
I installed django-cors-headers==2.4.0 on my virtualenviroment
This is my settings.py file:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'uploads.core',
'corsheaders',
]
MIDDLEWARE_CLASSES = [
'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.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
CSRF_TRUSTED_ORIGINS = ['http://127.0.0.1:3000','http://localhost:3000','http://localhost:8000','https://mywebsite:8000','https://myapp.firebaseapp.com','https://mywebsite:8088']
CSRF_COOKIE_NAME = "csrftoken"
CSRF_HEADER_NAME = [
'HTTP_X_CSRFTOKEN'
]
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
CORS_ORIGIN_WHITELIST = ['http://localhost:3000','https://mywebsite:8088']
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
)
CORS_ALLOW_HEADERS = (
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
)
Any idea how to solve it?
Thanks.
django-cors-headers is reasonably fool-proof and your configuration seems correct to me.
There is however a gotcha I've had issues with too:
Your uploads directory is likely not served through Django, but by the server directly as a static file (best practice and nearly default behaviour in Django). Even the built-in development server will serve static files without invoking your Django app.
Since your app is not invoked, django-cors-headers cannot apply a CORS header to those responses.
Make sure https://mywebsite:8000/uploads/vtt/ is the correct URL.
In my case, I used the wrong port because my API used a different port.
I replaced 8000 with 52130.
Try adding:
CORS_ORIGIN_WHITELIST = (
'example.com',
'localhost:3000',
'127.0.0.1:3000',
'more.domain.or.subdomains'
)
Don't forget add the middleware too
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
I had the same issue, and I think is a problem with:
SECURE_SSL_REDIRECT = True
I don't know the impacts over disabling it, but setting it to:
SECURE_SSL_REDIRECT = False
This make the cors problem gone.

No 'Access-Control-Allow-Origin' header is present on the requested resource error in fetch API django

I'm trying to fetch some data from an API. It works and my data is sent to the server but I am getting the following error message that not allow me to continue:
Access to fetch at 'http://192.168.80.11:8000/upload/5bc4206e3ff2286d24c58899/' from origin 'http://localhost:8000' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I know that this is because I am trying to fetch that data from within my localhost and the solution should be using CORS.
But how can I set Access-Control-Allow-Origin in the response header?
I use Django.
And this is setting file on server:
INSTALLED_APPS = (
...
'corsheaders',
...
)
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGINE_ALLOW_ALL= True
CORS_ALLOW_CREDENTIALS = True
#CORS_ORIGINE_ALLOW_ALL= False
CORS_ORIGINE_WHITELIST=(
'http//:192.168.20.29:8000',
'http//:192.168.20.30:8000',
'http//:127.0.0.1:8000',
)
Did you add this to your installed apps?
INSTALLED_APPS = (
...
'corsheaders',
...
)
UPDATE
CORS_ORIGIN_ALLOW_ALL not CORS_ORIGINE_ALLOW_ALL
CORS_ORIGIN_WHITELIST not CORS_ORIGINE_WHITELIST