Code Monkey home page Code Monkey logo

auth-backends's Introduction

auth-backends CI_ Codecov_

This package contains custom authentication backends, views, and pipeline steps used by edX services for single sign-on.

This package is compatible with Python 3.8, Django 2.2 and Django 3.0

We currently support OAuth 2.0 authentication. Support for OpenID Connect (OIDC) was removed as of version 3.0. Use version 2.x if you require OIDC and are not able to migrate to OAuth2.

Installation

The auth_backends package can be installed from PyPI using pip:

$ pip install edx-auth-backends

Update INSTALLED_APPS:

INSTALLED_APPS = (
    'social_django',
)

Configuration

Adding single sign-on/out support to a service requires a few changes:

  1. Define settings
  2. Add the authentication backend
  3. Add the login/logout redirects

OAuth 2.0 Settings

Setting Purpose
SOCIAL_AUTH_EDX_OAUTH2_KEY Client key
SOCIAL_AUTH_EDX_OAUTH2_SECRET Client secret
SOCIAL_AUTH_EDX_OAUTH2_URL_ROOT LMS root, reachable from the application server (e.g. https://courses.stage.edx.org or http://edx.devstack.lms:18000)
SOCIAL_AUTH_EDX_OAUTH2_PUBLIC_URL_ROOT LMS root, reachable from the end user's browser (e.g. https://courses.stage.edx.org or http://localhost:18000)
SOCIAL_AUTH_EDX_OAUTH2_JWS_HMAC_SIGNING_KEY (Optional) Shared secret for JWT signed with HS512 algorithm
SOCIAL_AUTH_EDX_OAUTH2_PROVIDER_CONFIGURATION_CACHE_TTL (Optional) Cache timeout for provider configuration. Defaults to 1 week.
SOCIAL_AUTH_EDX_OAUTH2_JWKS_CACHE_TTL (Optional) Cache timeout for provider's JWKS key data. Defaults to 1 day.

OAuth2 Applications require access to the user_id scope in order for the EdXOAuth2 backend to work. The backend will write the user_id into the social-auth extra_data, and can be accessed within the User model as follows:

self.social_auth.first().extra_data[u'user_id']  # pylint: disable=no-member

Strategy

We use a custom strategy that includes many of the default settings necessary to utilize single sign-on for edX services. This strategy should be used for all services to simplify configuration. If you need to override the defaults, you may still do so as you would with any social auth setting——prepend SOCIAL_AUTH_ to the setting name. Add the following to your Django settings to use the strategy:

SOCIAL_AUTH_STRATEGY = 'auth_backends.strategies.EdxDjangoStrategy'

Authentication Backend

Configuring the backend is simply a matter of updating the AUTHENTICATION_BACKENDS setting. The configuration below is sufficient for all edX services.

AUTHENTICATION_BACKENDS = (
    'auth_backends.backends.EdXOAuth2',
    'django.contrib.auth.backends.ModelBackend',
)

Authentication Views

In order to make use of the authentication backend, your service's login/logout views need to be updated. The login view should be updated to redirect to the authentication provider's login page. The logout view should be updated to redirect to the authentication provider's logout page.

This package includes views and urlpatterns configured for OAuth 2.0. To use them, simply append/prepend oauth2_urlpatterns to your service's urlpatterns in urls.py.

from auth_backends.urls import oauth2_urlpatterns

urlpatterns = oauth2_urlpatterns + [
    url(r'^admin/', include(admin.site.urls)),
    ...
]

It is recommended that you not modify the login view. If, however, you need to modify the logout view (to redirect to a different URL, for example), you can subclass EdxOAuth2LogoutView for the view and LogoutViewTestMixin for your tests.

Testing

Call make test.

Publishing a Release

After a PR merges, create a new tag from master branch with a new version of the package and create a Github release using the new tag that will automatically publish the package to PyPi when a release is created.

License

The code in this repository is licensed under the AGPL unless otherwise noted.

Please see LICENSE.txt for details.

How To Contribute

Contributions are very welcome!

Please read How To Contribute for details.

Reporting Security Issues

Please do not report security issues in public. Please email [email protected].

Mailing List and IRC Channel

You can discuss this code on the edx-code Google Group or in the #edx-code IRC channel on Freenode.

auth-backends's People

Contributors

aht007 avatar arbabkhalil avatar awais786 avatar awaisdar001 avatar bradenmacdonald avatar cgoldberg avatar christopappas avatar clintonb avatar cpennington avatar dependabot[bot] avatar dianakhuang avatar douglashall avatar dsjen avatar edx-requirements-bot avatar feanil avatar jawayria avatar mraarif avatar muhammad-ammar avatar mumarkhan999 avatar nedbat avatar pwnage101 avatar rgraber avatar robrap avatar sarina avatar timmc-edx avatar usamasadiq avatar waheedahmed avatar ziqixiao avatar zubairshakoorarbisoft avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

auth-backends's Issues

Config redirect to login in edx site?

Hi,
I'm trying to configure my Django app to authenticate the users with an Open Edx installation thought OAuth2, but I can't get the app to redirect to the OAuth login, it just show me this url: http://127.0.0.1:8000/login/edx-oidc/?next=/
screen shot 2018-07-10 at 9 26 55 pm

My settings:

INSTALLED_APPS = [
    'home', 
    'social_django',
]

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',

    'social_django.middleware.SocialAuthExceptionMiddleware',  # <--
]

ROOT_URLCONF = 'login.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            # os.path.join(BASE_DIR,'home/templates')
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'social_django.context_processors.backends',
                'social_django.context_processors.login_redirect',
            ],
        },
    },
]

WSGI_APPLICATION = 'login.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/

STATIC_URL = '/static/'


#Some other dependencies 
AUTHENTICATION_BACKENDS = (
    'auth_backends.backends.EdXOAuth2', 
    # 'auth_backends.backends.EdXOpenIdConnect',
    'django.contrib.auth.backends.ModelBackend',
)


LOGIN_URL = '/login/'

# EDX OAuth2 config

SOCIAL_AUTH_EDX_OAUTH2_KEY = '<client_id>'
SOCIAL_AUTH_EDX_OAUTH2_SECRET = '<client_secret>'
SOCIAL_AUTH_EDX_OAUTH2_ENDPOINT = 'https://<openedxapp>/oauth2/access_token'

SOCIAL_AUTH_STRATEGY = 'auth_backends.strategies.EdxDjangoStrategy'

Add Support for True Multi-tenancy

We currently use the same OAuth credentials for all tenants on our IDAs. This works because the auth service (LMS) is not truly multi-tenant. Just because LMS is not truly multi-tenant doesn't mean our IDAs cannot be.

Most of the IDAs use the Django sites framework coupled with a custom model (e.g. SiteConfiguration). We should properly codify this implementation in https://github.com/edx/edx-django-extensions. Once that is done, we can create a new strategy that is multi-tenant-aware.

If we ever get to the point of separating users, we should explore a new storage backend as well as discussed in omab/python-social-auth#552.

Property name 'full_name' should be spelled 'fullname' without underscores

Hello,

I believe there is a spelling error at the file auth_backends/backends.py, line 12

I think it should be written 'fullname' without underscores, and not 'full_name'.

This is used for mapping the claims provided in the JWT returned by the OAuth authorization code grant flow, but the name 'full_name' is not recognized at the 'registration' part of the pipeline, which in turn leaves the corresponding registration field empty, making it impossible to proceed with a SSO without the user confirming the registration form (in the case it's the first time a user gets registered in by means of third party SSO).

Changing it into 'fullname' makes this work.

Tested using a production environment using the "auth_backends.backends.EdXOAuth2" backend used for SSO of LMS with a custom OAuth2 identity provider.

I don't know if it was the original purpose, but I found this implementation to be very useful to be used for SSO with a generic third party OAuth2 Identity Provider implemented in house (not one of those well known public providers already listed in python-social-auth).

Test auth-backends on Python 3.11

This repository is a depedency of edx-platform and needs to be upgraded to Python 3.11 before
the Readwood release is cut (mid-April).

  • Requirements are compiled with Python 3.8
  • Tests are run on Python 3.8 and 3.11
  • (Optional) Tests are also run with 3.12 and passing or 3.12 issues are ticketed.
  • Classifiers in setup.py setup.cfg or pyproject.toml indicate Python 3.11 support
  • A new version is release to PyPI
  • A PR is merged to edx-platform to use the new version

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.