Django: How to use a custom social-auth backend? - django

I have overridden the GoogleOAuth2 class in django social-auth.
Currently the new class is in views.py.
But I cannot find how to add it to AUTHENTICATION_BACKENDS in settings.py
I have tried like this:
AUTHENTICATION_BACKENDS = (
'_auth.backends.YouTubeOAuth2', <---------- new backend
'social_core.backends.google.GoogleOAuth2',
'social_core.backends.twitter.TwitterOAuth',
'social_core.backends.facebook.FacebookOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
And adjusted the template:
window.open('{% url 'social:begin' 'youtube' %}', '_blank', 'location=yes,height=570,width=520,scrollbars=yes,status=yes');
In the end of the Google auth process comes an error:
ModuleNotFoundError at /api/oauth/complete/google-oauth2/
No module named '_auth'

Related

KeyCloack integration wirh DRF (Django Rest Framework)

I am a beginner level DRF developer. I am trying to integrate Keycloak with Django Rest Framework. Unfortunately, I was unable to find any type of help/blog/tutorial online.
You can use KeyCloack's Oauth2 API to authenticate and authorize your djagno users. Is is the same as implementing Sign-in with Google or any other provider.
My favorite package to implement social auth is python-social-auth, and it even has an existing backend for KeyCloack.
Here is how a configuration for Oauth2 against KeyCloack should look like:
First, setup social auth in your project like so
$ pip install social-auth-app-django
In your settings.py
INSTALLED_APPS = (
# ...
'social_django',
# ...
)
AUTHENTICATION_BACKENDS = (
'social_core.backends.keycloak.KeycloakOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
# Add you connection settings here
SOCIAL_AUTH_KEYCLOAK_KEY = 'test-django-oidc'
SOCIAL_AUTH_KEYCLOAK_SECRET = 'a7a41-245e-...'
SOCIAL_AUTH_KEYCLOAK_PUBLIC_KEY = \
'MIIBIjANBxxxdSD'
SOCIAL_AUTH_KEYCLOAK_AUTHORIZATION_URL = \
'https://iam.example.com/auth/realms/voxcloud-staff/protocol/openid-connect/auth'
SOCIAL_AUTH_KEYCLOAK_ACCESS_TOKEN_URL = \
'https://iam.example.com/auth/realms/voxcloud-staff/protocol/openid-connect/token'
In your urls.py
urlpatterns = [
...
path('auth/', include('social_django.urls', namespace='social'))
...
]
Then add this to your login page template:
Login with KeyCloack

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-rest-framework-social-oauth2 error with google

I am using Django 1.11 with Django Rest Framework 3.6. I am trying to schedule a social network login from an Android application with the django-rest-framework-social-oauth2 plugin but I am having an error that is not solved.
Configuration setting.py
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'social_core.backends.open_id.OpenIdAuth',
'social_core.backends.google.GoogleOAuth2',
'social_core.backends.google.GoogleOAuth',
'social_core.backends.facebook.FacebookOAuth2',
'social_core.backends.facebook.FacebookAppOAuth2',
# 'social_core.backends.instagram.InstagramOAuth2',
'rest_framework_social_oauth2.backends.DjangoOAuth2',
'frontend.login.EmailOrUsernameModelBackend',
)
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = ****
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = ***
REST_FRAMEWORK = {
...
'DEFAULT_AUTHENTICATION_CLASSES': (
...
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
'rest_framework_social_oauth2.authentication.SocialAuthentication',
)
}
The data configuration according to the documents.
Then from Postman I make the next call and it returns an error 400.
enter the description of the image here
The fact is that it returns the error:
The backend responded with HTTP403: the daily limit for
unauthenticated use was exceeded. Continuous use requires
registration.

Cannot pass APP ID while using Django Social Auth

I am trying to enable logging in via facebook,twitter and Google Open Auth 2. I am using the main documentation https://django-social-auth.readthedocs.org/en/latest/index.html. I have also used http://c2journal.com/2013/01/24/social-logins-with-django/
I have put all the necessary configurations in place. Here is my settings.py
....
AUTHENTICATION_BACKENDS = (
'social_auth.backends.twitter.TwitterBackend',
'social_auth.backends.facebook.FacebookBackend',
'social_auth.backends.google.GoogleOAuthBackend',
'social_auth.backends.google.GoogleOAuth2Backend',
'social_auth.backends.google.GoogleBackend',
'django.contrib.auth.backends.ModelBackend',
)
.....
TEMPLATE_CONTEXT_PROCESSORS = (
"social_auth.context_processors.social_auth_by_type_backends",
"django.contrib.auth.context_processors.auth",
)
......
SOCIAL_AUTH_ENABLED_BACKENDS = ('google','facebook','twitter')
.....
FACEBOOK_APP_ID='**********'
FACEBOOK_API_SECRET='**********************'
FACEBOOK_APP_NAMESPACE = '********_app'
FACEBOOK_EXTENDED_PERMISSIONS = ['email']
GOOGLE_OAUTH2_CLIENT_ID = '***************'
GOOGLE_OAUTH2_CLIENT_SECRET = '**************************'
TWITTER_CONSUMER_KEY = '***************'
TWITTER_CONSUMER_SECRET = '**********************'
........
INSTALLED_APPS = (
............
'social_auth',
)
I have added social-auth to my urls.py too
(r'^accounts/login/$', 'django.contrib.auth.views.login',
{'template_name': 'login.html'}),
(r'^accounts/logout/$', 'django.contrib.auth.views.logout_then_login'),
.....
urlpatterns = patterns('',
...
url(r'', include('social_auth.urls')),
...
)
On my login.html page, here is how I have called the links
<div>Login with Facebook</div>
</div>Login with Twitter</div>
</div>Login with Google</div>
The problem however, everytime I try logging in via any of these services, It seems the APP Id is missing.
I get this error on Facebook Invalid App ID: None and this one on twitter Only unicode objects are escapable. Got None of type .. Google doesn't work too but It tells me I cannot use raw IP addresses. I am using the server IP address. Please help.
I figured out what was the problem. I had installed python social auth then installed django-social auth. My application was still using the python-social-auth package.
Using the python-social-Auth syntax of naming configuration variables, I added the prefix
SOCIAL_AUTH_
to my config variables so that they now looked like this
SOCIAL_AUTH_FACEBOOK_SECRET='*******************'
SOCIAL_AUTH_FACEBOOK_APP_NAMESPACE = '*******'
SOCIAL_AUTH_FACEBOOK_EXTENDED_PERMISSIONS = ['email']
SOCIAL_AUTH_TWITTER_KEY = '********'
SOCIAL_AUTH_TWITTER_SECRET = '************'
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '*************************************'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '****************'
I can now log in. Thanks

Django: django-facebook redirects to /facebook/connect/

I read all the documentation about django-facebook, and I'm still not understanding why after setup the settings.py, the registration redirects to a template on django-facebook.
settings.py
FACEBOOK_LOGIN_DEFAULT_REDIRECT = '/profile/'
FACEBOOK_REGISTRATION_BACKEND = 'django_facebook.registration_backends.UserenaBackend'
LOGIN_REDIRECT_URL = '/profile/'
AUTHENTICATION_BACKENDS = (
'userena.backends.UserenaAuthenticationBackend',
'django_facebook.auth_backends.FacebookBackend',
'django.contrib.auth.backends.ModelBackend',
'guardian.backends.ObjectPermissionBackend',
)
The template shouldn't be editable on templates folder at my app?
There is something I'm missing?
Thanks!
It's all about the template loader priority, I think. Try to list your custom app before the django-facebook in your settings INSTALLED_APPS and you should get the right template.