Django keeps logging me out from dev server when changing my codebase - django

In my Django app I have a lot of if request.user.is_authenticated logic and once I change some code other than in templates (like forms, models, views, etc.) I get logged out from the development server which makes it quite annoying to always have to re-login in the frontend to test my prior code changes again.
Is there any way to stay logged in (a superuser) when in Debug = True (or other) mode?
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.getenv("DEBUG", "False") == "True"
# Add s.th. here to keep me logged in?
# settings.py
SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key())
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",
]
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
...
]

The problem is:
SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key())
You are generating a new secret key every time the server is restarted. The authentication details are stored in django_sessions table, and the session details are hashed with the SECRET_KEY. So, every time the SECRET_KEY value is changed, the current session details are invalidated and you need to freshly login again.
For the solution:
Generate a random secret key manually once and store it as an environment variable in every environment (be it staging, production, or development).
Hope you find this useful.

Related

Django Microsoft AD Authentication

I noticed that this question was repeated few times, but still, from all the resources, I couldn't manage to make it work properly.
I'm simply trying to use Azure Active Directory authentication with my Django app.
I am using this module, and I configured everything as noted in the docs.
The thing is - I can't figure out where should user enter the credentials - since the module has only
one url ('auth-callback/'). I can't find out how to jump to Microsoft login html page. Should I use my login.html or?
Also, I guess that 'auth-callback/' url is obviously a callback URL, which comes after the login page.
I am using django auth.views LoginView for login, and custom login.html page.
In terms of Redirect URI's I configured redirect URI to match directly the 'http://localhost:8000/microsoft/auth-callback/' url, which is also how it needs to be I guess.
Main problem is - where can I enter the credentials for login? :)
Also, when I try this - I get invalid credentials error on my Admin login page :
Start site and go to /admin and logout if you are logged in.
Login as Microsoft/Office 365/Xbox Live user. It will fail. This will automatically create your new user.
Login as a Password user with access to change user accounts.
Quick Edit :
I noticed that when i go to django/admin page '..../admin/login' inside the console i have this error :
https://static/microsoft/css/login.css Failed to load resource (404)
https://static/microsoft/js/login.js Failed to load resource (404)
Where can i get those files?
Let's jump to my code :
settings.py
INSTALLED_APPS = [
...
'django.contrib.sites',
'microsoft_auth',
...
]
#Choped from templates
'context_processors': [
...
'microsoft_auth.context_processors.microsoft',
],
AUTHENTICATION_BACKENDS = [
'microsoft_auth.backends.MicrosoftAuthenticationBackend',
'django.contrib.auth.backends.ModelBackend',
]
SITE_ID = 1
LOGIN_REDIRECT_URL = 'main:index'
LOGOUT_REDIRECT_URL = 'main:index'
LOGIN_URL = '/'
LOGOUT_URL = '/'
# AZURE AUTH CONFIG
MICROSOFT_AUTH_CLIENT_ID = 'THIS IS MY CLIENT KEY'
MICROSOFT_AUTH_CLIENT_SECRET = 'THIS IS MY SECRET KEY'
MICROSOFT_AUTH_TENANT_ID = 'THIS IS MY TENANT KEY'
# include Microsoft Accounts, Office 365 Enterpirse and Azure AD accounts
MICROSOFT_AUTH_LOGIN_TYPE = 'ma'
And my urls.py
...
path('microsoft/', include('microsoft_auth.urls', namespace='microsoft')),
...
Thank you all in advance.
django-microsoft-auth uses the standard django login page and extends that. My guess is that your custom login page is interfering with that. You could try removing that view and test again to see if the login appears at /admin.
The files should be coming from the django-microsoft-auth package. You could try uninstalling and reinstalling it again with pip

Django accessible from the local pc where Django stored, but not accessible from another local device

I'm building an application using React TSX for the front-end side and Django for the back-end side. So the application is working properly and it is accessible from my local PC by localhost:5000 because the application is stored on that PC, the React TSX app and the Django backend files. But whenever I try to access the application from other local devices, my Mobile or Tablet, I keep getting Network Error from the catch of axios. I have tried a lot of ways but I'm still not able to grant access from Django or React TSX. So any help will be great guys. Thanks.
settings.py
..........
..........
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_METHODS = ["GET","POST"]
CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with" ]
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True
..........
..........

Django, mozilla-django-oidc and admin

i am trying to connect Okta with a custom Django (v.3.0.2) app i am coding, using the mozilla-django-oidc library. So far the initial user authentication and account creation (using Django's user model) works, but i don't understand what i need to do to have the Django AdminSite work.
The Adminsite, before introducing mozilla-django-oidc worked as expected. I created an admin user, named "admin" and the user was able to login.
To integrate the mozilla-django-oidc library i followed the instructions here: https://mozilla-django-oidc.readthedocs.io/en/stable/installation.html. The instructions do not have any specific mention of the AdminSite.
When i access the AdminSite after the library integration, i have the following:
The AdminSite uses the default template - my assumption was that it
would also use Okta to authenticate.
The admin account "admin" that used to be able to login into the AdminSite does not work anymore
My goal is to be able to access the AdminSite. I don't mind if it will be over Okta or over the vanilla interface as long as i can access it.
Below are the relevant segments from the files (in order to integrate):
urls.py
urlpatterns = [
path('', static_site.site_index, name='site_index'),
path('admin/', admin.site.urls),
path('review/', include('review.urls')),
path('oidc/', include('mozilla_django_oidc.urls')),
]
settings.py
# OICD
AUTHENTICATION_BACKENDS = (
'mozilla_django_oidc.auth.OIDCAuthenticationBackend',
)
OIDC_RP_CLIENT_ID = 'xxxxx'
OIDC_RP_CLIENT_SECRET = 'xxxx'
OIDC_RP_SIGN_ALGO = 'RS256'
OIDC_OP_JWKS_ENDPOINT = 'https://dev-xxx.okta.com/oauth2/default/v1/keys'
OIDC_RP_SCOPES = 'openid email profile'
OIDC_OP_AUTHORIZATION_ENDPOINT = 'https://dev-xxx.okta.com/oauth2/default/v1/authorize'
OIDC_OP_TOKEN_ENDPOINT = 'https://dev-xxx.okta.com/oauth2/default/v1/token'
OIDC_OP_USER_ENDPOINT = 'https://dev-xxx.okta.com/oauth2/default/v1/userinfo'
# Provided by mozilla-django-oidc
LOGIN_URL = reverse_lazy('oidc_authentication_callback')
# App urls
LOGIN_REDIRECT_URL = reverse_lazy('review:dashboard')
LOGOUT_REDIRECT_URL = reverse_lazy('site_index')
Any ideas or pointers welcomed!
The goal was achieved by adding the default auth backend to the settings:
settings.py
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
'mozilla_django_oidc.auth.OIDCAuthenticationBackend',
]
I don't get Okta auth for the admin, but since i am happy just to have the admin running, i will stop here.
I've come up with a solution for using the mozilla-django-oidc login with the django admin. It's a little hacky but it's a lot less intimidating to redirect the admin login page than to override AdminSite.
In my top-level urls.py I have
class CustomLogin(View):
def get(self, request, **kwargs):
return HttpResponseRedirect(
reverse('oidc_authentication_init') + (
'?next={}'.format(request.GET['next']) if 'next' in request.GET else ''
)
)
urlpatterns = [
path('oidc/', include("mozilla_django_oidc.urls")),
path('admin/login/', CustomLogin.as_view()),
path('admin/', admin.site.urls),
# the rest of my urls...
]
If you don't care about passing the ?next= value correctly you can skip the CustomLogin class and do the following instead
urlpatterns = [
path('oidc/', include("mozilla_django_oidc.urls")),
]
# This only works if you break up urlpatterns so the reverse below can find what it needs
urlpatterns += [
path('admin/login/', RedirectView.as_view(
url=reverse('oidc_authentication_init') + ?next=/admin/,
permanent=False
)),
path('admin/', admin.site.urls),
# the rest of my urls...
]
I added ?next=/admin/ because by default once you log in you will be redirected to settings.LOGIN_REDIRECT_URL which I'm already using for something else
If you're using the default primary identifier, "email", you can create a superuser with that same email which will give SU privileges to that SSO user. So for example, if you have an SSOuser with email testuser#example.com, you can then run python manage.py createsuperuser and when prompted, set the email to testuser#example.com; the username and password don't matter since you're not actually using them for authentication (if you remove 'django.contrib.auth.backends.ModelBackend' from AUTHENTICATION_BACKENDS). I currently have this working, although I am extending the mozilla backend with the steps recommended in https://mozilla-django-oidc.readthedocs.io/en/stable/installation.html#connecting-oidc-user-identities-to-django-users to prevent users from being created on the fly.

Error: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty

I am currently attempting to update django from 1.4 to 2.0 after many syntax corrections I have run into this error when trying to run the server. I am updating django by having installed the latest version on my previous directory.
From everything that ive read online, the SECRET_KEY should be set in the settings.py which it is in my case.
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
Here is a snippet of where I am defining the SECRET_KEY variable as well as commented out attempts of what I have tried in my settings.py:
# Examples: "http://foo.com/media/", "/media/".
if versionNumber >= 1.3 and revisionNumber >= 3.1:
STATIC_URL = '/media/'
else:
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
#print ('before the SECRET KEY is defined')
#SECRET_KEY=os.environ.get("SECRET_KEY", 'tk1#!52kv9m(1hf5*t$q6e0am&1yon*-hlet0a+m975zg9a0)c')
SECRET_KEY='tk1#!52kv9m(1hf5*t$q6e0am&1yon*-hlet0a+m975zg9a0)c'
#print ('after the secret key is defined ',SECRET_KEY)
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
(
'django.template.loaders.cached.Loader',
If anyone has any resolutions please let me know as I have been struggling with this error for a couple of days now. I understand this may be an issue in the way I am updating so if anyone has more in depth information on updating django that would be very helpful as well.

LDAP authentication in Django

I'm very new to Django and LDAP ... any help is is appreciated.
So i'm trying to setup and ldaps in Django. I'm trying to follow this (http://packages.python.org/django-auth-ldap/) instruction, but i have few questions ...
Where is AUTHENTICATION_BACKENDS located? So that i can add django_auth_ldap.backend.LDAPBackend
Where is AUTH_LDAP_SERVER_URI?
If i get the solutions to these i maybe able to figure out the rest ...
Thanks a lot for looking into this.
AUTHENTICATION_BACKENDS should be located in your settings.py. This is where almost all configuration is done.
For AUTH_LDAP_SERVER_URI, I think you need to add this as a global variable to your settings.py.
You may also take a quick look at the example configuration on the page you referred to.
EDIT
You are right, those variables are not present in the initial settings.py. You need to add the following to your settings.py:
# Keep ModelBackend around for per-user permissions and maybe a local
# superuser.
AUTHENTICATION_BACKENDS = (
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
)
AUTH_LDAP_SERVER_URI = "ldap://ldap.example.com" # replace by the real URI