summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorBenjamin Dauvergne <bdauvergne@entrouvert.com>2014-03-27 09:01:08 (GMT)
committerBenjamin Dauvergne <bdauvergne@entrouvert.com>2014-03-27 09:22:14 (GMT)
commitafd3f287ec580f384c24e799acb41600b18e2791 (patch)
tree5089ff3bab4370b899e3acbc84f78329d50a4f9c
parent4d4b2f34493b5954ceada401d7db184c1e842bb2 (diff)
downloadauthentic2-idp-oauth2-afd3f287ec580f384c24e799acb41600b18e2791.zip
authentic2-idp-oauth2-afd3f287ec580f384c24e799acb41600b18e2791.tar.gz
authentic2-idp-oauth2-afd3f287ec580f384c24e799acb41600b18e2791.tar.bz2
add new web service proxy service using OAuth2 for authentication
You can translate user identifiers by referring to NameID in the output URL.
-rw-r--r--README.txt24
-rw-r--r--authentic2_idp_oauth2/admin.py5
-rw-r--r--authentic2_idp_oauth2/migrations/0002_auto__add_webservice.py100
-rw-r--r--authentic2_idp_oauth2/models.py48
-rw-r--r--authentic2_idp_oauth2/signature.py71
-rw-r--r--authentic2_idp_oauth2/urls.py4
-rw-r--r--authentic2_idp_oauth2/views.py32
7 files changed, 279 insertions, 5 deletions
diff --git a/README.txt b/README.txt
index 832025b..16e0a58 100644
--- a/README.txt
+++ b/README.txt
@@ -16,3 +16,27 @@ AUTOMATIC_GRANT:
A2_OAUTH2_AUTOMATIC_GRANT = (
('http://localhost:8000/', ('read',)),
)
+
+Web Service proxy
+=================
+
+You can configure simple REST web-service in
+/admin/authentic2_idp_oauth2/webservice/. URL field can contain template
+variable like that:
+
+ http://example.com/info/?user={{ user.username|urlencode }}
+
+or like:
+
+ http://example.com/categories/?format=json&NameID={{ federations.service_1.links.0|urlencode }}
+
+Supported authentication mechanisms on the target web-service are HMAC-SHA-256
+and HMAC-SHA-1 as specified on http://doc.entrouvert.org/portail-citoyen/dev/.
+
+You can access your newly proxy web-service through those URLs:
+
+ http://your-idp.com/idp/oauth2/ws-proxy/<web-service.id>/
+
+or:
+
+ http://your-idp.com/idp/oauth2/ws-proxy/<web-service.slug>/
diff --git a/authentic2_idp_oauth2/admin.py b/authentic2_idp_oauth2/admin.py
index 94afa64..bb924b2 100644
--- a/authentic2_idp_oauth2/admin.py
+++ b/authentic2_idp_oauth2/admin.py
@@ -5,3 +5,8 @@ from provider.oauth2.admin import ClientAdmin
from . import models
admin.site.register(models.A2Client, ClientAdmin)
+
+class WebServiceAdmin(admin.ModelAdmin):
+ prepopulated_fields = {'slug': ('name',)}
+
+admin.site.register(models.WebService, WebServiceAdmin)
diff --git a/authentic2_idp_oauth2/migrations/0002_auto__add_webservice.py b/authentic2_idp_oauth2/migrations/0002_auto__add_webservice.py
new file mode 100644
index 0000000..755d0b5
--- /dev/null
+++ b/authentic2_idp_oauth2/migrations/0002_auto__add_webservice.py
@@ -0,0 +1,100 @@
+# -*- coding: utf-8 -*-
+from south.utils import datetime_utils as datetime
+from south.db import db
+from south.v2 import SchemaMigration
+from django.db import models
+
+
+class Migration(SchemaMigration):
+
+ def forwards(self, orm):
+ # Adding model 'WebService'
+ db.create_table(u'authentic2_idp_oauth2_webservice', (
+ (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+ ('name', self.gf('django.db.models.fields.CharField')(max_length=32)),
+ ('slug', self.gf('django.db.models.fields.SlugField')(max_length=32)),
+ ('url', self.gf('django.db.models.fields.CharField')(max_length=1024)),
+ ('auth_mech', self.gf('django.db.models.fields.CharField')(default='', max_length=16, blank=True)),
+ ('signature_key', self.gf('django.db.models.fields.CharField')(default='', max_length=128, blank=True)),
+ ('verify_certificate', self.gf('django.db.models.fields.BooleanField')(default=True)),
+ ('allow_redirects', self.gf('django.db.models.fields.BooleanField')(default=True)),
+ ('timeout', self.gf('django.db.models.fields.IntegerField')(default=10)),
+ ))
+ db.send_create_signal(u'authentic2_idp_oauth2', ['WebService'])
+
+
+ def backwards(self, orm):
+ # Deleting model 'WebService'
+ db.delete_table(u'authentic2_idp_oauth2_webservice')
+
+
+ models = {
+ u'auth.group': {
+ 'Meta': {'object_name': 'Group'},
+ u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
+ 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
+ },
+ u'auth.permission': {
+ 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
+ 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+ 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
+ u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
+ },
+ u'auth.user': {
+ 'Meta': {'object_name': 'User'},
+ 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+ 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
+ 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+ 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
+ u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
+ 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+ 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+ 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
+ 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
+ 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
+ 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
+ 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
+ },
+ u'authentic2_idp_oauth2.a2client': {
+ 'Meta': {'object_name': 'A2Client', '_ormbases': [u'oauth2.Client']},
+ u'client_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['oauth2.Client']", 'unique': 'True', 'primary_key': 'True'}),
+ 'logout_url': ('django.db.models.fields.URLField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
+ 'logout_use_iframe': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
+ 'logout_use_iframe_timeout': ('django.db.models.fields.PositiveIntegerField', [], {'default': '300'})
+ },
+ u'authentic2_idp_oauth2.webservice': {
+ 'Meta': {'object_name': 'WebService'},
+ 'allow_redirects': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
+ 'auth_mech': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '16', 'blank': 'True'}),
+ u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
+ 'signature_key': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '128', 'blank': 'True'}),
+ 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '32'}),
+ 'timeout': ('django.db.models.fields.IntegerField', [], {'default': '10'}),
+ 'url': ('django.db.models.fields.CharField', [], {'max_length': '1024'}),
+ 'verify_certificate': ('django.db.models.fields.BooleanField', [], {'default': 'True'})
+ },
+ u'contenttypes.contenttype': {
+ 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
+ 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+ u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
+ },
+ u'oauth2.client': {
+ 'Meta': {'object_name': 'Client'},
+ 'client_id': ('django.db.models.fields.CharField', [], {'default': "'1035126d5fac86b5ca5c'", 'max_length': '255'}),
+ 'client_secret': ('django.db.models.fields.CharField', [], {'default': "'a1091f90af80d46507146ac3fa51e1dcb22ed35b'", 'max_length': '255'}),
+ 'client_type': ('django.db.models.fields.IntegerField', [], {}),
+ u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+ 'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
+ 'redirect_uri': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
+ 'url': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
+ 'user': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'oauth2_client'", 'null': 'True', 'to': u"orm['auth.User']"})
+ }
+ }
+
+ complete_apps = ['authentic2_idp_oauth2'] \ No newline at end of file
diff --git a/authentic2_idp_oauth2/models.py b/authentic2_idp_oauth2/models.py
index 5952955..ec28b62 100644
--- a/authentic2_idp_oauth2/models.py
+++ b/authentic2_idp_oauth2/models.py
@@ -1,10 +1,58 @@
+from django.core.exceptions import ValidationError
+from django.db import models
from django.utils.translation import ugettext_lazy as _
+from django.template import Template
from provider.oauth2.models import Client
from authentic2.models import LogoutUrlAbstract
+from authentic2.managers import GetBySlugManager
class A2Client(LogoutUrlAbstract, Client):
class Meta:
verbose_name = _('client')
verbose_name_plural = _('clients')
+
+class WebService(models.Model):
+ AUTH_MECH = (
+ ('', 'None'),
+ ('hmac-sha256', 'HMAC-SHA-256'),
+ ('hmac-sha1', 'HMAC-SHA-1'),
+ )
+
+ name = models.CharField(max_length=32)
+ slug = models.SlugField(max_length=32)
+
+ url = models.CharField(max_length=1024)
+
+ auth_mech = models.CharField(verbose_name=_('Authentication mechanism'),
+ max_length=16, choices=AUTH_MECH, default='', blank=True)
+ signature_key = models.CharField(verbose_name=_('Signature key'),
+ max_length=128, default='', blank=True)
+ verify_certificate = models.BooleanField(verbose_name=_('verify '
+ 'certificate'), default=True, blank=True)
+ allow_redirects = models.BooleanField(verbose_name=_('allows HTTP redirections'),
+ help_text=_('it can improve latencies to forbid redirection follow'),
+ default=True)
+ timeout = models.IntegerField(verbose_name=_('timeout'),
+ default=10,
+ help_text=_('time in second to wait before '
+ 'failing to download a datasource'))
+
+ objects = GetBySlugManager()
+
+ def clean(self):
+ if self.signature_key and (not self.auth_mech or not self.auth_mech.startswith('hmac-')):
+ raise ValidationError(_('You must choose a hashing algorithm if '
+ 'you set a signature key'))
+
+ def natural_key(self):
+ return (self.slug,)
+
+ def get_url(self, ctx=None):
+ if ctx is None:
+ ctx = {}
+ return Template(self.url).render(ctx)
+
+ def __unicode__(self):
+ return self.name
diff --git a/authentic2_idp_oauth2/signature.py b/authentic2_idp_oauth2/signature.py
new file mode 100644
index 0000000..67e798b
--- /dev/null
+++ b/authentic2_idp_oauth2/signature.py
@@ -0,0 +1,71 @@
+import datetime
+import base64
+import hmac
+import hashlib
+import urllib
+import random
+import urlparse
+
+'''Simple signature scheme for query strings'''
+
+def sign_url(url, key, algo='sha256', timestamp=None, nonce=None):
+ parsed = urlparse.urlparse(url)
+ new_query = sign_query(parsed.query, key, algo, timestamp, nonce)
+ return urlparse.urlunparse(parsed[:4] + (new_query,) + parsed[5:])
+
+def sign_query(query, key, algo='sha256', timestamp=None, nonce=None):
+ if timestamp is None:
+ timestamp = datetime.datetime.utcnow()
+ timestamp = timestamp.strftime('%Y-%m-%dT%H:%M:%SZ')
+ if nonce is None:
+ nonce = hex(random.getrandbits(128))[2:]
+ new_query = query
+ if new_query:
+ new_query += '&'
+ new_query += urllib.urlencode((
+ ('algo', algo),
+ ('timestamp', timestamp),
+ ('nonce', nonce)))
+ signature = base64.b64encode(sign_string(new_query, key, algo=algo))
+ new_query += '&signature=' + urllib.quote(signature)
+ return new_query
+
+def sign_string(s, key, algo='sha256', timedelta=30):
+ digestmod = getattr(hashlib, algo)
+ hash = hmac.HMAC(key, digestmod=digestmod, msg=s)
+ return hash.digest()
+
+def check_url(url, key, known_nonce=None, timedelta=30):
+ parsed = urlparse.urlparse(url, 'https')
+ return check_query(parsed.query, key)
+
+def check_query(query, key, known_nonce=None, timedelta=30):
+ parsed = urlparse.parse_qs(query)
+ signature = base64.b64decode(parsed['signature'][0])
+ algo = parsed['algo'][0]
+ timestamp = parsed['timestamp'][0]
+ timestamp = datetime.datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%SZ')
+ nonce = parsed['nonce']
+ unsigned_query = query.split('&signature=')[0]
+ if known_nonce is not None and known_nonce(nonce):
+ return False
+ print 'timedelta', datetime.datetime.utcnow() - timestamp
+ if abs(datetime.datetime.utcnow() - timestamp) > datetime.timedelta(seconds=timedelta):
+ return False
+ return check_string(unsigned_query, signature, key, algo=algo)
+
+def check_string(s, signature, key, algo='sha256'):
+ # constant time compare
+ signature2 = sign_string(s, key, algo=algo)
+ if len(signature2) != len(signature):
+ return False
+ res = 0
+ for a, b in zip(signature, signature2):
+ res |= ord(a) ^ ord(b)
+ return res == 0
+
+if __name__ == '__main__':
+ test_key = '12345'
+ signed_query = sign_query('NameId=_12345&orig=montpellier', test_key)
+ assert check_query(signed_query, test_key, timedelta=0) is False
+ assert check_query(signed_query, test_key) is True
diff --git a/authentic2_idp_oauth2/urls.py b/authentic2_idp_oauth2/urls.py
index c257d8e..7961f76 100644
--- a/authentic2_idp_oauth2/urls.py
+++ b/authentic2_idp_oauth2/urls.py
@@ -7,6 +7,6 @@ urlpatterns = patterns('authentic2_idp_oauth2.views',
url('^idp/oauth2/authorize/confirm/?$',
login_required(Authorize.as_view()), name='authorize'),
url('^idp/oauth2/', include('provider.oauth2.urls', namespace='oauth2')),
- url('^idp/oauth2/federation/$', 'user_info', name='user-info'),
- url('^idp/oauth2/user-info/$', 'user_info', name='user-info'),
+ url('^idp/oauth2/user-info/$', 'user_info', name='a2-idp-oauth2-user-info'),
+ url('^idp/oauth2/ws-proxy/(?P<ws_id>.*)/$', 'ws_proxy', name='a2-idp-oauth2-ws-proxy'),
)
diff --git a/authentic2_idp_oauth2/views.py b/authentic2_idp_oauth2/views.py
index b76de52..1e626a8 100644
--- a/authentic2_idp_oauth2/views.py
+++ b/authentic2_idp_oauth2/views.py
@@ -1,8 +1,10 @@
+import logging
import uuid
+import requests
+from django.template import RequestContext
-from rest_framework.decorators import (api_view, authentication_classes,
- permission_classes)
+from rest_framework.decorators import (api_view, authentication_classes)
from rest_framework.authentication import (OAuth2Authentication,
SessionAuthentication)
from rest_framework.response import Response
@@ -12,10 +14,12 @@ from provider import scope
from authentic2.models import FederatedId
-from . import forms, app_settings
+from . import forms, app_settings, models, signature
__ALL_ = [ 'user_info', 'Authorize' ]
+logger = logging.getLogger(__name__)
+
def add_targeted_id(request, data):
'''Retrieve a targeted id for the user and this client, if none exist
create one using a random UUID.
@@ -75,4 +79,26 @@ class Authorize(Authorize):
return super(Authorize, self).get_authorization_form(
request, client, data, client_data)
+@api_view(['GET', 'POST', 'PUT', 'DELETE'])
+@authentication_classes([OAuth2Authentication, SessionAuthentication])
+def ws_proxy(request, ws_id):
+ try:
+ ws = models.WebService.objects.get(id=ws_id)
+ except models.WebService.DoesNotExist:
+ ws = models.WebService.objects.get(slug=ws_id)
+ ctx = RequestContext(request)
+ url = ws.get_url(ctx)
+ logger.debug('proxy to URL %r', url)
+ method = request.method.lower()
+ if ws.signature_key and ws.auth_mech.startswith('hmac-'):
+ url = signature.sign_url(url, ws.signature_key,
+ algo=ws.auth_mech[5:])
+ response = getattr(requests, method)(url,
+ verify=ws.verify_certificate,
+ allow_redirects=ws.allow_redirects,
+ timeout=ws.timeout)
+ return Response(response.json())
+
+
+