• Stars
    star
    102
  • Rank 335,584 (Top 7 %)
  • Language
    Python
  • License
    MIT License
  • Created about 9 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

OpenID Connect authentication for Django REST Framework

OpenID Connect authentication for Django Rest Framework

This package contains an authentication mechanism for authenticating users of a REST API using tokens obtained from OpenID Connect.

Currently, it only supports JWT and Bearer tokens. JWT tokens will be validated against the public keys of an OpenID connect authorization service. Bearer tokens are used to retrieve the OpenID UserInfo for a user to identify him.

Installation

Install using pip:

pip install drf-oidc-auth

Configure authentication for Django REST Framework in settings.py:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        # ...
        'oidc_auth.authentication.JSONWebTokenAuthentication',
        'oidc_auth.authentication.BearerTokenAuthentication',
    ),
}

And configure the module itself in settings.py:

OIDC_AUTH = {
    # Specify OpenID Connect endpoint. Configuration will be
    # automatically done based on the discovery document found
    # at <endpoint>/.well-known/openid-configuration
    'OIDC_ENDPOINT': 'https://accounts.google.com',

    # The Claims Options can now be defined by a static string.
    # ref: https://docs.authlib.org/en/latest/jose/jwt.html#jwt-payload-claims-validation
    # The old OIDC_AUDIENCES option is removed in favor of this new option.
    # `aud` is only required, when you set it as an essential claim.
    'OIDC_CLAIMS_OPTIONS': {
        'aud': {
            'values': ['myapp'],
            'essential': True,
        }
    },
    
    # (Optional) Function that resolves id_token into user.
    # This function receives a request and an id_token dict and expects to
    # return a User object. The default implementation tries to find the user
    # based on username (natural key) taken from the 'sub'-claim of the
    # id_token.
    'OIDC_RESOLVE_USER_FUNCTION': 'oidc_auth.authentication.get_user_by_id',
    
    # (Optional) Number of seconds in the past valid tokens can be 
    # issued (default 600)
    'OIDC_LEEWAY': 600,
    
    # (Optional) Time before signing keys will be refreshed (default 24 hrs)
    'OIDC_JWKS_EXPIRATION_TIME': 24*60*60,

    # (Optional) Time before bearer token validity is verified again (default 10 minutes)
    'OIDC_BEARER_TOKEN_EXPIRATION_TIME': 10*60,
    
    # (Optional) Token prefix in JWT authorization header (default 'JWT')
    'JWT_AUTH_HEADER_PREFIX': 'JWT',
    
    # (Optional) Token prefix in Bearer authorization header (default 'Bearer')
    'BEARER_AUTH_HEADER_PREFIX': 'Bearer',

    # (Optional) Which Django cache to use
    'OIDC_CACHE_NAME': 'default',

    # (Optional) A cache key prefix when storing and retrieving cached values
    'OIDC_CACHE_PREFIX': 'oidc_auth.',
}

Running tests

pip install tox
tox

Mocking authentication

There's a AuthenticationTestCaseMixin provided in the oidc_auth.test module, which you can use for testing authentication like so:

from oidc_auth.test import AuthenticationTestCaseMixin
from django.test import TestCase

class MyTestCase(AuthenticationTestCaseMixin, TestCase):
    def test_example_cache_of_valid_bearer_token(self):
        self.responder.set_response(
            'http://example.com/userinfo', {'sub': self.user.username})
        auth = 'Bearer egergerg'
        resp = self.client.get('/test/', HTTP_AUTHORIZATION=auth)
        self.assertEqual(resp.status_code, 200)

        # Token expires, but validity is cached
        self.responder.set_response('http://example.com/userinfo', "", 401)
        resp = self.client.get('/test/', HTTP_AUTHORIZATION=auth)
        self.assertEqual(resp.status_code, 200)

    def test_example_using_invalid_bearer_token(self):
        self.responder.set_response('http://example.com/userinfo', "", 401)
        auth = 'Bearer hjikasdf'
        resp = self.client.get('/test/', HTTP_AUTHORIZATION=auth)
        self.assertEqual(resp.status_code, 401)

References

More Repositories

1

hypernode-vagrant

[Deprecated, use hypernode-docker instead] Use Hypernode on your local machine!
Ruby
51
star
2

libapache-mod-fastcgi

libapache-mod-fastcgi
C
41
star
3

hypernode-docker

Fast and easy Docker for Magento development
HTML
31
star
4

pip-install-privates

Install pip packages from private GitHub repositories without an SSH agent
Python
26
star
5

hypernode-api-php

PHP Client for the Hypernode API
PHP
9
star
6

magento-continuous-integration-example

Example of automated testing and deploying Magento with Vagrant and Jenkins
Shell
8
star
7

php-hypernode

Hypernode extension for PHP
C
7
star
8

hypernode-deploy-configuration

Configuration objects for Hypernode Deploy
PHP
7
star
9

hypernode-docs-next

Hypernode Documentation
Python
5
star
10

fortunes-hypernode-hints

fortunes-hypernode-hints is a package that contains useful hints for users and developers. If you have encountered any good hints that can be useful to all of us, please add it here.
Shell
4
star
11

hypernode-deploy

Application deployment tool for the Hypernode platform
PHP
4
star
12

django-eventhandler

A Django plugin that fetches and dispatches events from RabbitMQ
Python
4
star
13

hypernode-performance-test

A sample JMeter performance test suite
3
star
14

wp-cluster-varnish

Wordpress Cluster Varnish plugin
PHP
3
star
15

rrpproxy

A python connector for RRP Proxy
Python
3
star
16

hypernode-api-python

Python Client for the Hypernode API
Python
2
star
17

amqpconsumer

RabbitMQ event listener
Python
2
star
18

elasticmetrics

ElasticSearch metrics collector
Python
2
star
19

pythonmeetup-bmazing

Are you able to escape out of the maze only using python? Let's find out!
Python
2
star
20

byte-cluster-varnish

Make Joomla/Wordpress/Drupal work nicely with Varnish. Send purge requests upon content change.
PHP
2
star
21

genbuf

Buffers almost anything to almost anything. Read from files and write to sockets, read from pipes and write to a remote UDP port.
C
2
star
22

searchguard-python

Python library for the Search Guard REST API
Python
2
star
23

MetaRobots

Magento extension MetaRobots. To set value of meta tag robots to noindex,follow on page 2 and further.
PHP
1
star
24

media

Logos and Artwork for Byte.nl
1
star
25

LessImages

This extension extends Mage_Catalog_Helper_Image to return the image url of the original when no resizing, rotation or watermark is applied.
PHP
1
star
26

community.hypernode.io

Hypernode community docs
Shell
1
star
27

htmltmpl-python

Source: http://htmltmpl.sourceforge.net/
Python
1
star
28

tornado-client-cache

Python
1
star
29

HypernodeShopware6Helpers

Shopware 6 helper plugins (for skipping the install wizard for example)
PHP
1
star
30

magento-installer

magento-installer
PHP
1
star
31

apache1.3

Shell
1
star
32

eventsender

Generic Python library to send events to AMQP
Python
1
star
33

django-oauth-provider

Django oauth provider as written by https://bitbucket.org/david/django-oauth-plus/wiki/Home. But in git format for easier access, and to be able to handle our own releases a bit quicker.
Python
1
star
34

lucene-solr

Backport of lucene-solr 3.6.2 to precise
Java
1
star