Django Microsoft AD Authentication - django

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

Related

How to solve facebook django url social-auth-app-django problem?

Im trying to have social-auth-app-django facebook on my website and im getting this error, on localhost everything works but now when i changed settings to my website it isn't work :(
My settings.py:
LOGIN_URL='Logowanie'
LOGIN_REDIRECT_URL = 'MeetMe!'
SOCIAL_AUTH_FACEBOOK_KEY = '***********' # App ID
SOCIAL_AUTH_FACEBOOK_SECRET = '***********' # App Secret
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/przekierowanie/'
SOCIAL_AUTH_FACEBOOK_SCOPE = [
'email',
]
SECURE_SSL_REDIRECT = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SOCIAL_AUTH_REDIRECT_IS_HTTPS = True
I solve it on my own !
What i did:
added to settings.py
SOCIAL_AUTH_FACEBOOK_API_VERSION = '2.11'
i followed this tutorial
no such table: social_auth_usersocialauth
1.pip install python-social-auth==0.2.21
2.pip install social-auth-app-django
3.Set Django's app list and the backend-related settings according to the settings paragraph of the migration page.
4.Apply migrations: python manage.py migrate
5.Uninstall the old package: pip uninstall python-social-auth
i set on developers facebook status to live
Domain:
domain.pl
Url:
https://domain.pl
Valid OAuth Redirect URIs:
https://domain.pl/oauth/complete/facebook/
First Go To Setting.py And Put This Code End Of All Codes:
AUTHENTICATION_BACKENDS = [
'social_core.backends.facebook.FacebookOAuth2',
]
Second Go To FaceBook Developer In This Address :
https://developers.facebook.com
And Make One Account There.
After go To My Apps And Then Click On Create App And Then Put Your Website Name ((Attention...If You Use Your Local Host You Need To Put One Domain Name For Your Local Ip)) And Your Email And Click On Create App ID And In Your Dashboard Looking For Facebook Login And Click On Set Up .
And Then In First Step In Web Window Put Your WebSite Name For Local Host For Example Put mysite.com:8000/ And Click On Save And Other Options Just Cross .
Now In Your Dashboard On The Left Side Click On Setting And Then Basic If You See Your APP ID And Your APP SECRET Put This Two In Your Settings.py After That Last Code .
SOCIAL_AUTH_FACEBOOK_KEY = 'Put Your App Id Code Here'
SOCIAL_AUTH_FACEBOOK_SECRET = 'Put Your App Secret Code Here'
If You Want To Take User's Email Also You Can You This As Well .
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
Now In You Dashboard Go To Settings And After Go To Basic An In Field App Domains Put Your Website Name Also Go To Settings After Advanced And Put Website Name In Domain Manager With CLick On Add a Domain .
Now Again In Dashboard Go In Products+ Part And Click On Facrbook Login After Settings And Check These Option Be Active(Yes) :
• Client OAuth Login
• Web OAuth Login
• Enforce HTTPS
• Embedded Browser OAuth Login
And IN This Form Your Are Now Also Go In This Field Valid OAuth Redirect URIs And Put This URL :
exapmle.com/social-auth/complete/facebook/
And Put Your Button In Your Website Page That Have This Login Auth :
<li>
Sign in with Facebook
</li>

Trouble getting Salesforce login working with dj-rest-auth + django-allauth

My app has a Django 3.1 backend with django-allauth and dj-rest-auth (actively supported fork of django-rest-auth).
My mobile and web frontends can already sign in using Facebook and Google via REST. I'm now trying to add Salesforce as a 3rd REST social login method, but am running into issues.
I've followed the django-allauth instructions for Salesforce:
Created a Salesforce Connected App with id and openid scopes (along with some others), and set the callback URL to https://www.mywebdomain.com/accounts/salesforce/login/callback/
Created a SocialApplication in Django with client ID, secret, and login URL in the "Key" field (https://login.salesforce.com/)
Included allauth.socialaccount.providers.salesforce in INSTALLED_APPS
I've been using client-side JSforce to kick off the Salesforce auth request in the frontend, but I'm open to other methods if they are simpler/better/etc.
Running jsforce.browser.login() in my clients' JS code opens a Salesforce login popup. After entering Salesforce login credentials, the Salesforce system redirected to my defined callback URL, resulting in a page that shows the following text:
Social Network Login Failure
An error occurred while attempting to login via your social network account.
The URL in the address bar on that page looks something like this:
https://www.mywebdomain.com/accounts/salesforce/login/callback/#access_token=00D3t000004QWRm%21ARwAQPfHWiM6jdB43dlyW6qjEw._34mjzGi_Jv6YCXp0QssT.9F9lCge5_YaH8gqTy3Od6SywCs8X9zOGv145SyviBVeGdn0&instance_url=https%3A%2F%2Fna123.salesforce.com&id=https%3A%2F%2Flogin.salesforce.com%2Fid%2F00D3t000004QWRmEAO%2F0053t000008QBetAAG&issued_at=1606802917608&signature=KvxAX0WBCFQYY%2BO25id9%2FXxpbh2q2d2vWdQ%2FFV5FCBw%3D&state=jsforce0.popup.c0ockgct29g&scope=id+api+web+refresh_token+openid&token_type=Bearer
I tried to debug and print the error in my backend, but both auth_error.code and auth_error.exception were blank/empty.
I also tried sending the access_token from that URL's hash to my Salesforce API endpoint (see below), but that resulted in a 400 error ("Incorrect value").
Here is how I've defined my SocialLoginViews in my views.py, based on dj-rest-auth's social auth documentation:
from dj_rest_auth.registration.views import SocialLoginView
from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.salesforce.views import SalesforceOAuth2Adapter
class FacebookLogin(SocialLoginView):
adapter_class = FacebookOAuth2Adapter
class GoogleLogin(SocialLoginView):
adapter_class = GoogleOAuth2Adapter
class SalesforceLogin(SocialLoginView):
adapter_class = SalesforceOAuth2Adapter
My urls.py:
from .views import FacebookLogin, GoogleLogin, SalesforceLogin
urlpatterns = [
...
# Sending access_token to the Facebook and Google REST endpoints works,
# but doing the same for the Salesforce REST endpoint does not (400 error: "Incorrect value")
url(r'^api/rest-auth/facebook/$', FacebookLogin.as_view(), name='fb_login'),
url(r'^api/rest-auth/google/$', GoogleLogin.as_view(), name='google_login'),
url(r'^api/rest-auth/salesforce/$', SalesforceLogin.as_view(), name='salesforce_login'),
...
]
How can Salesforce social auth be made to work in this app?
I figured it out and got it working: when posting to my dj-rest-auth Salesforce API endpoint, I was only including access_token in my POST body. I actually need both access_token and key, where key is the Salesforce login URL ("https://login.salesforce.com").
It was indeed in the django-allauth instructions for Salesforce, but I misinterpreted the wording. I now know that it says to require both access_token and key in the POST body.

Django Management command for Activating/Deactivating admin site

I would like to know if it's possible to 'Activate' and 'Deactivate' the admin site using a custom management command and what i mean by deactivating is commenting the line containing the path of admin.site.urls in the main urls.py file.
Or if there is a better way to do this.
I think the best way to do it - write custom middleware.
You can detect if current request is request to admin site (for example request.path.startswith('/admin')) and return 404 error if you disable you admin page.
When do you want to deactivate the admin urls? For example if you want to deactivate admin site urls for production, you can add a control to urls.py checkin if settings.DEBUG is False.
urlpatterns = [
...
]
if not settings.DEBUG:
urlpatterns += [
path('basic-admin/', basic_site.urls)
]

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.

Django + socialauth: login with openid or admin

i'm trying to implement the socialauth module to my django project, but i get a bit confused on its relation toward the admin site.
My problem: the #login_required decorator redirects me to the admin login page instead of the accounts/login/ page to log in via openid.
how do i offer the possibility to the user to log in via admin or openid?
thanks
the solution:
in settings.py, change LOGIN_URL = 'admin' to LOGIN_URL = '/accounts/login/'
in urls.py add (r'^accounts/', include('socialauth.urls')),