Skip to content

Commit

Permalink
Merge pull request #21 from stdweird/vsc_details
Browse files Browse the repository at this point in the history
Add more configuration options for openid connect
  • Loading branch information
theferrit32 authored Oct 26, 2018
2 parents 75d1635 + 84fcce1 commit f3315a0
Show file tree
Hide file tree
Showing 19 changed files with 595 additions and 530 deletions.
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,28 @@ If a conflicting path is already in use on 443, the django app can be placed on
}
```

# Configuration

## config.json

### Providers

* `additional_params`: string (default empty) with (extra) parameters for the authorization url.
In case of OpenID Connect, most params (like `scope`, `response_type`, and `access_type`) are
already generated. For OAuth2, there are no default parameters.

* `additional_scopes`: list of additional scopes that will be requested via the authorization URL.

* `user_name_from_token`: list of token attributes to use as `user_name` (tried in order,
first existing attribute wins) (default to `preferred_username` and `email`)

* `name_from_token`: list of token attributes to use as `name` (tried in order,
first existing attribute wins) (default to `name`)

#### OpenID Connect

* prompt: boolean (default True): adds `prompt` parameter for `login` and `consent` to the authorization url

# Development

## Unittests
Expand Down
File renamed without changes.
8 changes: 8 additions & 0 deletions auth_microservice/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#!/usr/bin/env python3
import os
import sys
from django.core.management import execute_from_command_line

if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "auth_microservice.settings")
execute_from_command_line(sys.argv)
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
#
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

# Uncomment to debug sensitive data
# from token_service import config
# config.debug_sensitive = True

#
# Force enable logging, to be able to log during base_settings
LOGGING_CONFIG = None
Expand Down Expand Up @@ -79,6 +84,7 @@
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_extensions',
]

MIDDLEWARE = [
Expand All @@ -92,7 +98,7 @@
]
MIDDLEWARE_CLASSES = MIDDLEWARE # django < 20 compatibility

ROOT_URLCONF = 'microservice.urls'
ROOT_URLCONF = 'auth_microservice.urls'

TEMPLATES = [
{
Expand All @@ -110,7 +116,7 @@
},
]

WSGI_APPLICATION = 'microservice.wsgi.application'
WSGI_APPLICATION = 'auth_microservice.wsgi.application'



Expand Down
11 changes: 7 additions & 4 deletions example/microservice/urls.py → auth_microservice/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,14 @@
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
import token_service.urls
from django.contrib import admin
try:
from django.urls import url, include
except ImportError:
from django.conf.urls import url, include

urlpatterns = [
path('admin/', admin.site.urls),
path(r'', include(token_service.urls)),
url('^admin/?$', admin.site.urls),
url(r'', include(token_service.urls)),
]
2 changes: 1 addition & 1 deletion example/microservice/wsgi.py → auth_microservice/wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "microservice.settings")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "auth_microservice.settings")

application = get_wsgi_application()
15 changes: 0 additions & 15 deletions example/manage.py

This file was deleted.

1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ requires = python >= 2.7
django >= 1.8
django-extensions
python2-pycryptodomex
python2-jwt
pyjwkest
29 changes: 18 additions & 11 deletions token_service/base_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,36 +34,43 @@
TOKEN_SERVICE_DB_KEY = os.path.join(TOKEN_SERVICE_BASEDIR, 'db.key')
TOKEN_SERVICE_ADMIN_KEY = os.path.join(TOKEN_SERVICE_BASEDIR, 'admin.key')
TOKEN_SERVICE_CONFIG = os.path.join(TOKEN_SERVICE_BASEDIR, 'config.json')
TOKEN_SERVICE_DJANGO_KEY_ALT = os.path.join(TOKEN_SERVICE_BASEDIR, 'django.key')


def make_secret_key(keylen=SECRET_KEY_LEN):
if 'SECRET_KEY' in locals():
logging.info('django secret key present')
secret_key = locals()['SECRET_KEY']
else:
logging.info('loading django secret key from %s', TOKEN_SERVICE_DJANGO_KEY)
loaded_django_key = False
if os.path.isfile(TOKEN_SERVICE_DJANGO_KEY):
with open(TOKEN_SERVICE_DJANGO_KEY, 'r') as f:
secret_key = f.readline().strip()
if len(secret_key) == keylen:
loaded_django_key = True
else:
logging.warn('saved django key is incorrect size, generating new key')
for keyfn in [TOKEN_SERVICE_DJANGO_KEY, TOKEN_SERVICE_DJANGO_KEY_ALT]:
if os.path.isfile(keyfn):
logging.info('Trying to load django secret key from %s', keyfn)
with open(keyfn, 'r') as f:
secret_key = f.readline().strip()
if len(secret_key) == keylen:
loaded_django_key = True
break
else:
logging.warn('saved django key %s has incorrect size', keyfn)
else:
logging.info('No django secret key %s', keyfn)
if not loaded_django_key:
logging.info('No django secret key loaded, trying to create one at %s', TOKEN_SERVICE_DJANGO_KEY)
ascii_printable = [chr(c) for c in range(ord('!'), ord('~')+1)]
secret_key = ''.join([random.SystemRandom().choice(ascii_printable) for i in range(0, keylen)])
try:
with open(TOKEN_SERVICE_DJANGO_KEY, 'w') as f:
f.write(secret_key)
except OSError:
logging.error('Could not save django key. This will result in a different key being used each execution')
logging.error('Could not save django key %s. Will use a different key being for each execution',
TOKEN_SERVICE_DJANGO_KEY)
traceback.print_exc()
return secret_key


def make_database():
logging.info('creating database')
logging.info('generate django database configuration')
with open(TOKEN_SERVICE_DB_CFG, 'r') as f:
d = json.loads(f.read())
host = d['host']
Expand All @@ -85,7 +92,7 @@ def make_database():

def make_database_mem():
"""In memory sqlite config; do NOT use in production"""
logging.info('creating memory database')
logging.info('generate django memory database configuration')
return {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
Expand Down
4 changes: 4 additions & 0 deletions token_service/crypt.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ def decrypt(self, ciphertext):
logging_sensitive('crypt.decrypt de_encr: %s', de_encr)
# unpad
pad_n = de_encr[-1]
if not isinstance(pad_n, int):
# py3 returns bytes as decrypted value
# py2 original string; so it needs the inverse of the chr
pad_n = ord(pad_n)
de_encr = de_encr[:-pad_n]
de_encr = de_encr.decode('utf-8')
logging_sensitive('crypt.decrypt de_encr unpad: %s', de_encr)
Expand Down
4 changes: 3 additions & 1 deletion token_service/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ def __init__(self, *args, **kwargs):
super(EncryptedTextField, self).__init__(*args, **kwargs)

# invoked to convert db value to python value
def from_db_value(self, value, expression, connection):
# context: not used as from django 2.0
def from_db_value(self, value, expression, connection, context):
logging_sensitive('EncryptedTextField.from_db_value value: %s', value)
dec = self.crypt.decrypt(value)
logging_sensitive('EncryptedTextField.from_db_value(%s) -> %s', value, dec)
Expand All @@ -37,6 +38,7 @@ class User(models.Model):
class Meta:
unique_together = (('sub', 'provider'),)


class Token(models.Model):
'''
OpenID Connect/OAuth 2.0 token information
Expand Down
Loading

0 comments on commit f3315a0

Please sign in to comment.