source: TI12-security/trunk/python/ndg.security.server/ndg/security/server/sso/sso/config/ssoServiceMiddleware.py @ 3918

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/ndg.security.server/ndg/security/server/sso/sso/config/ssoServiceMiddleware.py@3918
Revision 3918, 7.5 KB checked in by pjkersha, 12 years ago (diff)

Initial Integration of Single Sign On Service with OpenID and Pylons AuthKit?:

  • WAYF now contains an OpenID textbox for sign in
  • No role integration carried out yet - OpenID has no better privileges than an anonymous user(!)
  • Integrated into Authkit - requires lots of config settings in pylons ini file
  • HTTP 401 error get redirected automatically to WAYF
  • Need to create an AuthKit? egg from SVN 151 checkout - will put on NDG dist
Line 
1'''
2Security middleware - set-up configuration items
3
4P J Kershaw 18/03/08
5'''
6import authkit.authenticate
7from beaker.middleware import SessionMiddleware
8       
9from os.path import expandvars as xpdvars
10import logging
11log = logging.getLogger(__name__)
12
13class ndg:
14    '''Class structure to define a namespace for SSO Service config attached
15    Pylons global variable 'g'
16    '''
17    class security:
18        class server:
19            class sso:
20                cfg = None
21                class state:
22                    '''State information specific to server side'''
23                    trustedIdPs = {}
24               
25        class common:
26            '''Client class is also needed for BaseController handler to handle
27            responses from Single Sign On IdP'''
28            class sso:
29                class cfg:
30                    '''Placeholder for server and sslServer attributes'''
31                class state:
32                    '''State information - return to URL should be set each
33                    time a new page is loaded.  In ows_server this is handled
34                    by setting it in ndgPage.kid a template that is extended by
35                    all Browse pages.'''
36                    returnToURL = None
37                    b64encReturnToURL = None
38               
39class SSOMiddleware(object):
40           
41    def __init__(self, app, g, app_conf, **kw):
42        log.debug("SSOMiddleware.__init__ ...")
43        ndg.security.server.sso.cfg = SSOServiceConfig(app_conf['configfile'], **kw)
44       
45        # Copy into client for the benefit of
46        # ndg.security.client.ssoclient.ssoclient.lib.base.BaseController
47        # used to process responses back from SSO IdP
48        ndg.security.common.sso.cfg.server = ndg.security.server.sso.cfg.server
49        ndg.security.common.sso.cfg.sslServer = \
50                                        ndg.security.server.sso.cfg.sslServer
51           
52        g.ndg = ndg
53        self.globals = g
54   
55        # OpenID Middleware
56        app = authkit.authenticate.middleware(app, app_conf)
57        app = SessionMiddleware(app)
58
59        self.app = app
60               
61    def __call__(self, environ, start_response):
62        return self.app(environ, start_response)
63
64
65import sys
66from ConfigParser import SafeConfigParser as ConfigParser
67from ndg.security.common.wssecurity import WSSecurityConfig
68
69class SSOServiceConfigError(Exception):
70    """Handle errors from parsing security config items"""
71       
72class SSOServiceConfig(object):
73    """Get Security related parameters from the Pylons NDG config file"""
74
75    def __init__(self, cfg=None, **parseKw):
76        '''Get PKI settings for Attribute Authority and Session Manager from
77        the configuration file
78       
79        @type cfg: config file object or string
80        @param cfg: reference to NDG configuration file or config file object
81        '''
82       
83        self.wss = {}
84       
85        if isinstance(cfg, basestring):
86            # Assume file path to be read
87            self.read(cfg)
88        else:
89            # Assume existing config type object
90            self.cfg = cfg
91
92        if self.cfg:
93            self.parse(**parseKw)
94
95       
96    def read(self, cfgFilePath):
97        '''Read content of config file into object'''
98        self.cfg = ConfigParser()
99        self.cfg.read(cfgFilePath)
100 
101
102    def parse(self, 
103              defSection='DEFAULT', 
104              layoutSection='layout',
105              wssSection='WSSecurity'):
106        '''Extract content of config file object into self'''
107             
108        if self.cfg.has_option(defSection, 'tracefile'):       
109            self.tracefile = eval(self.cfg.get(defSection,'tracefile'))   
110        else:
111            self.tracefile = None
112           
113        self.smURI = self.cfg.get(defSection, 'sessionMgrURI')       
114        self.aaURI = self.cfg.get(defSection, 'attAuthorityURI')
115       
116        # ... for SSL connections to security web services
117        try:
118            self.sslCACertFilePathList = \
119            xpdvars(self.cfg.get(defSection, 'sslCACertFilePathList')).split()
120               
121        except AttributeError:
122            raise SSOServiceConfigError, \
123                        'No "sslCACertFilePathList" security setting'
124
125
126        # HTTP Proxy setting for web service connections...
127       
128        # Override an http_proxy env setting 
129        if self.cfg.has_option(defSection, 'httpProxyHost'):
130            self.httpProxyHost = self.cfg.get(defSection, 'httpProxyHost')
131        else:
132            self.httpProxyHost = None
133       
134        # Set this to True if the http_proxy environment variable should be
135        # ignored in this case
136        if self.cfg.has_option(defSection, 'ignoreHttpProxyEnv'):
137            self.ignoreHttpProxyEnv = self.cfg.getboolean(defSection, 
138                                                          'ignoreHttpProxyEnv')
139        else:
140            self.ignoreHttpProxyEnv = False
141           
142           
143        # If no separate WS-Security config file is set then read these params
144        # from the current config file
145        if self.cfg.has_option(defSection, 'wssCfgFilePath'):
146            path = self.cfg.get(defSection,'wssCfgFilePath', None) 
147            wssCfgFilePath = xpdvars(path)
148        else:
149            wssCfgFilePath = None
150           
151        wss = WSSecurityConfig(cfg=wssCfgFilePath or self.cfg)
152        wss.parse(section=wssSection)
153
154       
155        # Cast to standard dict because WSSecurityConfig object can't be
156        # passed via **kw and dict(wss) doesn't work
157        # TODO: check for cleaner solution - dict(wss)
158        self.wss = dict(wss.items())
159
160
161        # Hostname
162        self.server = self.cfg.get(defSection, 'server', '')
163
164        # For secure connections
165        self.sslServer = self.cfg.get(defSection, 'sslServer', '')
166       
167        # These URLs are referred from template files
168        self.getCredentials = '%s/getCredentials' % self.sslServer       
169        self.logoutURI = '%s/logout' % self.server
170                     
171        # Where Are You From URI         
172        self.wayfuri='%s/wayf' % self.server
173
174        # Flag to enable OpenID interface
175        if self.cfg.has_option(defSection, 'enableOpenID'):
176            self.enableOpenID = self.cfg.getboolean(defSection, 'enableOpenID')
177        else:
178            self.enableOpenID = False
179           
180        self.localLink=self.cfg.get(layoutSection, 'localLink', None)
181        self.localImage=self.cfg.get(layoutSection, 'localImage', None)
182        self.localAlt=self.cfg.get(layoutSection, 'localAlt', 
183                                   'Visit Local Site')
184        self.ndgLink=self.cfg.get(layoutSection, 'ndgLink', 
185                                  'http://ndg.nerc.ac.uk')
186        self.ndgImage=self.cfg.get(layoutSection, 'ndgImage', None)
187        self.ndgAlt=self.cfg.get(layoutSection, 'ndgAlt','Visit NDG')
188        self.stfcLink=self.cfg.get(layoutSection, 'stfcLink')
189        self.stfcImage=self.cfg.get(layoutSection, 'stfcImage')
190        self.helpIcon=self.cfg.get(layoutSection, 'helpIcon')
191        self.LeftAlt=self.cfg.get(layoutSection, 'HdrLeftAlt')
192        self.LeftLogo=self.cfg.get(layoutSection, 'HdrLeftLogo')
193        self.pageLogo="bodcHdr"
194        self.icons_xml=self.cfg.get(layoutSection,'Xicon')
195        self.icons_plot=self.cfg.get(layoutSection,'plot')
196        self.icons_prn=self.cfg.get(layoutSection, 'printer')
197       
198        self.disclaimer = self.cfg.get('DEFAULT', 'disclaimer')
199           
200           
201    def __repr__(self):
202        return '\n'.join(["%s=%s" % (k,v) for k,v in self.__dict__.items() \
203                if k[:2] != "__"])
204   
Note: See TracBrowser for help on using the repository browser.