def __init__(self, db, oidcsrv, client_info=None): UserInfo.__init__(self, db) self.oidcsrv = oidcsrv self.claims_clients = self.init_claims_clients(client_info) for key, cc in self.claims_clients.items(): oidcsrv.keyjar.update(cc.keyjar)
def __init__(self, spconf, url, db=None): UserInfo.__init__(self, db) # Configurations for the SP handler. (pyOpSamlProxy.client.sp.conf) self.sp_conf = importlib.import_module(spconf) ntf = NamedTemporaryFile(suffix="pyoidc.py", delete=True) ntf.write("CONFIG = " + str(self.sp_conf.CONFIG).replace("%s", url)) ntf.seek(0) self.sp = Saml2Client(config_file="%s" % ntf.name) self.samlcache = self.sp_conf.SAML_CACHE
def __init__(self, uri, base, filter_pattern, scope=SCOPE_SUBTREE, tls=False, user="", passwd="", attr=None, attrsonly=False): UserInfo.__init__(self, None) self.ldapuri = uri self.base = base self.filter_pattern = filter_pattern self.scope = scope self.tls = tls self.attr = attr self.attrsonly = attrsonly self.ldapuser = user self.ldappasswd = passwd self.bind()
def create_claims_server(self, keyjar): self.srv = ClaimsServer("pyoicserv", SessionDB("https://example.com"), TestClaimsServer.CDB, UserInfo(USERDB), verify_client, keyjar=keyjar, dist_claims_mode=ClaimsMode( TestClaimsServer.USER2MODE))
def create_claims_server(self, keyjar, session_db): self.srv = ClaimsServer("pyoicserv", session_db, TestClaimsServer.CDB, UserInfo(USERDB), verify_client, keyjar=keyjar, dist_claims_mode=ClaimsMode( TestClaimsServer.USER2MODE))
def provider(tmpdir): client_db_path = os.path.join(tmpdir.strpath, "client_db") cdb = shelve_wrapper.open(client_db_path) ab = AuthnBroker() ab.add("dummy", DummyAuthn()) sdb = SessionDB("https://testprovider.com") provider = CourseProvider("https://testprovider.com", sdb, cdb, ab, UserInfo({"user": {}}), AuthzHandling(), None, None) return provider
def __init__(self, uri, base, filter_pattern, scope=SCOPE_SUBTREE, tls=False, user="", passwd="", attr=None, attrsonly=False): UserInfo.__init__(self, None) self.ldapuri = uri self.base = base self.filter_pattern = filter_pattern self.scope = scope self.tls = tls self.attr = attr self.attrsonly = attrsonly self.ldapuser = user self.ldappasswd = passwd self.bind() self.ld = None
def setup(): with open("config.yaml", 'r') as f: config = yaml.load(f) issuer = config["baseurl"] ac = AuthnBroker() authn = UsernamePasswordMako(None, "login.mako", LOOKUP, PASSWD, "{}/authorization".format(issuer)) ac.add("password", authn) URLS.append((r'^verify', make_auth_verify(authn.verify))) authz = AuthzHandling() client_db_path = os.environ.get("OIDC_CLIENT_DB", "client_db") LOGGER.info("Using db: {}".format(client_db_path)) cdb = shelve_wrapper.open(client_db_path) global OAS OAS = CourseProvider(issuer, SessionDB(issuer), cdb, ac, None, authz, verify_client, rndstr(16)) OAS.baseurl = issuer OAS.userinfo = UserInfo(config["userdb"]) # Additional endpoints the OpenID Connect Provider should answer on add_endpoints(ENDPOINTS, ENDPOINT_FUNCS) OAS.endpoints = ENDPOINTS authn.srv = OAS try: OAS.cookie_ttl = config["cookie_ttl"] except KeyError: pass try: OAS.cookie_name = config["cookie_name"] except KeyError: pass keyjar_init(OAS, config["keys"]) public_keys = [] for keybundle in OAS.keyjar[""]: for key in keybundle.keys(): public_keys.append(key.serialize()) public_jwks = {"keys": public_keys} filename = "static/jwks.json" with open(filename, "w") as f: f.write(json.dumps(public_jwks)) OAS.jwks_uri = "{}/{}".format(OAS.baseurl, filename) return config
def main(): parser = argparse.ArgumentParser(description='Example OIDC Provider.') parser.add_argument("-p", "--port", default=80, type=int) parser.add_argument("-b", "--base", default="https://localhost", type=str) parser.add_argument("-d", "--debug", action="store_true") parser.add_argument("settings") args = parser.parse_args() # Load configuration with open(args.settings, "r") as f: settings = yaml.load(f) issuer = args.base.rstrip("/") template_dirs = settings["server"].get("template_dirs", "templates") jinja_env = Environment(loader=FileSystemLoader(template_dirs)) authn_broker, auth_routing = setup_authentication_methods( settings["authn"], jinja_env) # Setup userinfo userinfo_conf = settings["userinfo"] cls = make_cls_from_name(userinfo_conf["class"]) i = cls(**userinfo_conf["kwargs"]) userinfo = UserInfo(i) client_db = {} provider = Provider(issuer, SessionDB(issuer), client_db, authn_broker, userinfo, AuthzHandling(), verify_client, None) provider.baseurl = issuer provider.symkey = rndstr(16) # Setup keys path = os.path.join(os.path.dirname(__file__), "static") try: os.makedirs(path) except OSError, e: if e.errno != errno.EEXIST: raise e pass
def _get_user_info(self, user_attributes, requested_claims=None, scopes=None): """ Filter user attributes to return to the client (as claims in the ID Token) based on what was requested in request 'claims' parameter and in the 'scope'. :type user_attributes: dict[str, str] :type requested_claims: dict[str, Optional[dict]] :type scopes: list[str] :rtype: dict[str, str] :param user_attributes: attributes provided by the backend :param requested_claims: claims requested by the client through the 'claims' request param :param scopes: the scopes requested by the client :return: all attributes/claims to return to the client """ requested_claims = requested_claims or {} scopes = scopes or [] claims_requested_by_scope = Provider._scope2claims(scopes) claims_requested_by_scope.update( requested_claims) # let explicit claims request override scope return UserInfo().filter(user_attributes, claims_requested_by_scope)
def main_setup(args, lookup): sys.path.insert(0, ".") config = importlib.import_module(args.config) config.issuer = config.issuer % args.port config.SERVICE_URL = config.SERVICE_URL % args.port # Client data base # cdb = shelve.open(config.CLIENT_DB, writeback=True) cdb = {} ac = AuthnBroker() for authkey, value in list(config.AUTHENTICATION.items()): authn = None # if "UserPassword" == authkey: # from oic.utils.authn.user import UsernamePasswordMako # authn = UsernamePasswordMako(None, "login.mako", LOOKUP, PASSWD, # "authorization") if "NoAuthn" == authkey: from oic.utils.authn.user import NoAuthn authn = NoAuthn(None, user=config.AUTHENTICATION[authkey]["user"]) if authn is not None: ac.add(config.AUTHENTICATION[authkey]["ACR"], authn, config.AUTHENTICATION[authkey]["WEIGHT"]) # dealing with authorization authz = AuthzHandling() kwargs = { "template_lookup": lookup, "template": { "form_post": "form_response.mako" }, } if config.USERINFO == "SIMPLE": # User info is a simple dictionary in this case statically defined in # the configuration file userinfo = UserInfo(config.USERDB) else: userinfo = None # Should I care about verifying the certificates used by other entities if args.insecure: kwargs["verify_ssl"] = False else: kwargs["verify_ssl"] = True uri_schemes = read_uri_schemes('uri-schemes-1.csv') as_args = { "name": config.issuer, "cdb": cdb, "authn_broker": ac, "userinfo": userinfo, "authz": authz, "client_authn": verify_client, "symkey": config.SYM_KEY, "template_lookup": lookup, "template": { "form_post": "form_response.mako" }, "jwks_name": "./static/jwks_{}.json", 'event_db': Events(), } com_args = { "name": config.issuer, # "sdb": SessionDB(config.baseurl), "baseurl": config.baseurl, "cdb": cdb, "authn_broker": ac, "userinfo": userinfo, "authz": authz, "client_authn": verify_client, "symkey": config.SYM_KEY, "template_lookup": lookup, "template": { "form_post": "form_response.mako" }, "jwks_name": "./static/jwks_{}.json", 'uri_schemes': uri_schemes } op_arg = {} try: op_arg["cookie_ttl"] = config.COOKIETTL except AttributeError: pass try: op_arg["cookie_name"] = config.COOKIENAME except AttributeError: pass try: as_args['behavior'] = config.BEHAVIOR except AttributeError: pass # print URLS if args.debug: op_arg["debug"] = True if args.port == 80: _baseurl = config.baseurl else: if config.baseurl.endswith("/"): config.baseurl = config.baseurl[:-1] _baseurl = "%s:%d" % (config.baseurl, args.port) if not _baseurl.endswith("/"): _baseurl += "/" op_arg["baseurl"] = _baseurl # Add own keys for signing/encrypting JWTs try: # a throw-away OP used to do the initial key setup _op = Provider(sdb=SessionDB(com_args["baseurl"]), **com_args) jwks = keyjar_init(_op, config.keys) except KeyError: pass else: op_arg["jwks"] = jwks op_arg["keys"] = config.keys as_args['jwks_uri'] = '{}{}/jwks.json'.format(_baseurl, 'static') as_args['jwks_name'] = 'static/jwks.json' f = open('static/jwks.json', 'w') f.write(json.dumps(jwks)) f.close() as_args['keyjar'] = _op.keyjar as_args['sdb'] = SessionDB(com_args["baseurl"], token_factory=JWTToken('T', keyjar=_op.keyjar, lt_pattern={ 'code': 3600, 'token': 900 }, iss=_baseurl, sign_alg='RS256'), refresh_token_factory=JWTToken( 'R', keyjar=_op.keyjar, lt_pattern={'': 24 * 3600}, iss=_baseurl)) try: op_arg["marg"] = multi_keys(as_args, config.multi_keys) except AttributeError as err: pass return as_args, op_arg, config
def authenticated_as(self, cookie=None, **kwargs): if cookie == "FAIL": return None, 0 else: return {"uid": self.user}, time() # AUTHN = UsernamePasswordMako(None, "login.mako", tl, PASSWD, "authenticated") AUTHN_BROKER = AuthnBroker() AUTHN_BROKER.add("UNDEFINED", DummyAuthn(None, "username")) # dealing with authorization AUTHZ = AuthzHandling() SYMKEY = rndstr(16) # symmetric key used to encrypt cookie info USERINFO = UserInfo(USERDB) KEYS = {} ISSUER = {} OPERATOR = {} for entity in ['fo', 'fo1', 'org', 'inter', 'admin', 'ligo', 'op']: fname = os.path.join(BASE_PATH, "{}.key".format(entity)) _keydef = KEYDEFS[:] _keydef[0]['key'] = fname _jwks, _keyjar, _kidd = build_keyjar(_keydef) KEYS[entity] = {'jwks': _jwks, 'keyjar': _keyjar, 'kidd': _kidd} ISSUER[entity] = 'https://{}.example.org'.format(entity) OPERATOR[entity] = Operator(keyjar=_keyjar, iss=ISSUER[entity])
# Should I care about verifying the certificates used other entities if args.insecure: kwargs["verify_ssl"] = False else: kwargs["verify_ssl"] = True OAS = Provider(config.issuer, SessionDB(), cdb, ac, None, authz, verify_client, config.SYM_KEY, **kwargs) for authn in ac: authn.srv = OAS if config.USERINFO == "SIMPLE": # User info is a simple dictionary in this case statically defined in # the configuration file OAS.userinfo = UserInfo(config.USERDB) elif config.USERINFO == "SAML": OAS.userinfo = UserInfo(config.SAML) else: raise Exception("Unsupported userinfo source") try: OAS.cookie_ttl = config.COOKIETTL except AttributeError: pass try: OAS.cookie_name = config.COOKIENAME except AttributeError: pass
def __init__(self, db, instance=None): UserInfo.__init__(self) SSIXADBBase.__init__(self, db) self.instance = instance
def main_setup(args, lookup=None): sys.path.insert(0, ".") config = importlib.import_module(args.config) config.issuer = config.issuer % args.port config.SERVICE_URL = config.SERVICE_URL % args.port # Client data base cdb = shelve.open(config.CLIENT_DB, writeback=True) ac = AuthnBroker() for authkey, value in list(config.AUTHENTICATION.items()): authn = None # if "UserPassword" == authkey: # from oic.utils.authn.user import UsernamePasswordMako # authn = UsernamePasswordMako(None, "login.mako", LOOKUP, PASSWD, # "authorization") if "NoAuthn" == authkey: from oic.utils.authn.user import NoAuthn authn = NoAuthn(None, user=config.AUTHENTICATION[authkey]["user"]) if authn is not None: ac.add(config.AUTHENTICATION[authkey]["ACR"], authn, config.AUTHENTICATION[authkey]["WEIGHT"]) # dealing with authorization authz = AuthzHandling() if config.USERINFO == "SIMPLE": # User info is a simple dictionary in this case statically defined in # the configuration file userinfo = UserInfo(config.USERDB) else: userinfo = None com_args = { "name": config.issuer, "baseurl": config.baseurl, "cdb": cdb, "authn_broker": ac, "userinfo": userinfo, "authz": authz, "client_authn": verify_client, "symkey": config.SYM_KEY, "template_lookup": lookup, "template": { "form_post": "form_response.mako" }, "jwks_name": "./static/jwks_{}.json" } # Should I care about verifying the certificates used by other entities if args.insecure: com_args["verify_ssl"] = False else: com_args["verify_ssl"] = True try: assert os.path.isfile(config.SERVER_CERT) assert os.path.isfile(config.SERVER_KEY) com_args['client_cert'] = (config.SERVER_CERT, config.SERVER_KEY) except AttributeError: pass except AssertionError: print("Can't access client certificate and/or client secret") exit(-1) op_arg = {} try: op_arg["cookie_ttl"] = config.COOKIETTL except AttributeError: pass try: op_arg["cookie_name"] = config.COOKIENAME except AttributeError: pass # print URLS if args.debug: op_arg["debug"] = True # All endpoints the OpenID Connect Provider should answer on add_endpoints(ENDPOINTS) op_arg["endpoints"] = ENDPOINTS if args.port == 80: _baseurl = config.baseurl else: if config.baseurl.endswith("/"): config.baseurl = config.baseurl[:-1] _baseurl = "%s:%d" % (config.baseurl, args.port) if not _baseurl.endswith("/"): _baseurl += "/" op_arg["baseurl"] = _baseurl # Add own keys for signing/encrypting JWTs try: # a throw-away OP used to do the initial key setup _op = Provider(sdb=SessionDB(com_args["baseurl"]), **com_args) jwks = keyjar_init(_op, config.keys) except KeyError: pass else: op_arg["jwks"] = jwks op_arg['keyjar'] = _op.keyjar #op_arg["keys"] = config.keys try: op_arg["marg"] = multi_keys(com_args, config.multi_keys) except AttributeError as err: pass return com_args, op_arg, config
def as_arg_setup(args, lookup, config): if args.port: _port = args.port else: if args.tls: _port = 443 else: _port = 80 if args.path2port: # means there is a reverse proxy in front translating # path -> port p2p_map = read_path2port_map(args.path2port) _path = p2p_map[_port] if args.xport: _issuer = "{base}:{port}/{path}".format(base=config.baseurl, port=args.xport, path=_path) _port = args.xport else: _issuer = "{base}/{path}".format(base=config.baseurl, path=_path) else: # the old port based _path = '' _issuer = "{base}:{port}".format(base=config.baseurl, port=_port) if args.tls and _issuer.startswith('http://'): _issuer = _issuer.replace('http://', 'https://') cdb = {} ac = AuthnBroker() for authkey, value in list(config.AUTHENTICATION.items()): authn = None # if "UserPassword" == authkey: # from oic.utils.authn.user import UsernamePasswordMako # authn = UsernamePasswordMako(None, "login.mako", LOOKUP, PASSWD, # "authorization") if "NoAuthn" == authkey: from oic.utils.authn.user import NoAuthn authn = NoAuthn(None, user=config.AUTHENTICATION[authkey]["user"]) if authn is not None: ac.add(config.AUTHENTICATION[authkey]["ACR"], authn, config.AUTHENTICATION[authkey]["WEIGHT"]) # dealing with authorization authz = AuthzHandling() if config.USERINFO == "SIMPLE": # User info is a simple dictionary in this case statically defined in # the configuration file userinfo = UserInfo(config.USERDB) else: userinfo = None as_args = { "name": _issuer, 'instance_path': _path, 'instance_port': _port, "cdb": cdb, "authn_broker": ac, "userinfo": userinfo, "authz": authz, "client_authn": verify_client, "symkey": config.SYM_KEY, "template_lookup": lookup, "template": { "form_post": "form_response.mako" }, "jwks_name": "./static/jwks_{}.json", 'event_db': Events(), } try: as_args['behavior'] = config.BEHAVIOR except AttributeError: pass com_args = { "baseurl": config.baseurl, } for arg in [ 'name', 'cdb', 'authn_broker', 'userinfo', 'authz', 'template', 'jwks_name', 'client_authn', 'symkey', 'template_lookup' ]: com_args[arg] = as_args[arg] # Add own keys for signing/encrypting JWTs try: # a throw-away OP used to do the initial key setup _op = Provider(sdb=SessionDB(com_args["baseurl"]), **com_args) jwks = keyjar_init(_op, config.keys) except KeyError: key_arg = {} else: key_arg = {"jwks": jwks, "keys": config.keys} as_args['jwks_name'] = 'static/jwks.json' f = open('static/jwks.json', 'w') f.write(json.dumps(jwks)) f.close() if args.insecure: _op.keyjar.verify_ssl = False else: _op.keyjar.verify_ssl = True as_args['keyjar'] = _op.keyjar as_args['sdb'] = SessionDB( com_args["baseurl"], token_factory=JWTToken('T', keyjar=_op.keyjar, lt_pattern={ 'code': 3600, 'token': 900 }, iss=com_args['baseurl'], sign_alg='RS256'), refresh_token_factory=JWTToken('R', keyjar=_op.keyjar, lt_pattern={'': 24 * 3600}, iss=com_args['baseurl'])) return as_args, key_arg
from cherrypy import wsgiserver from cherrypy.wsgiserver import ssl_builtin from oic.oic.claims_provider import ClaimsServer from oic.utils.sdb import create_session_db parser = argparse.ArgumentParser() parser.add_argument('-v', dest='verbose', action='store_true') parser.add_argument('-d', dest='debug', action='store_true') parser.add_argument('-p', dest='port', default=8093, type=int) parser.add_argument(dest="config") args = parser.parse_args() cdb = json.loads(open("claims_client.json").read()) userinfo = UserInfo(USERDB) # in memory session storage config = json.loads(open(args.config).read()) sdb = create_session_db(config["issuer"], config["SESSION_KEY"], password="******") OAS = ClaimsServer(config["issuer"], sdb, cdb, userinfo, verify_client) if "keys" in config: for typ, info in config["keys"].items(): OAS.keyjar.add_kb("", keybundle_from_local_file(info["key"], "rsa", ["ver", "sig"])) try:
def main_setup(args, lookup=None): sys.path.insert(0, ".") config = importlib.import_module(args.config) if args.path: if config.baseurl.endswith('/'): config.issuer = '{}{}/'.format(config.baseurl, args.path) else: config.issuer = '{}/{}/'.format(config.baseurl, args.path) elif args.port and args.port not in [80, 443]: if config.baseurl.endswith('/'): config.issuer = '{}:{}/'.format(config.baseurl[:-1], args.port) else: config.issuer = '{}:{}/'.format(config.baseurl, args.port) _baseurl = config.issuer if not _baseurl.endswith("/"): _baseurl += "/" com_args = { "name": config.issuer, "baseurl": _baseurl, "client_authn": verify_client, "symkey": config.SYM_KEY, "template_lookup": lookup, "template": { "form_post": "form_response.mako" }, "jwks_name": "./static/jwks_{}.json" } # Client data base try: com_args['cdb'] = shelve.open(config.CLIENT_DB, writeback=True) except AttributeError: pass try: _auth = config.AUTHENTICATION except AttributeError: pass else: ab = AuthnBroker() for authkey, value in list(_auth.items()): authn = None if "NoAuthn" == authkey: from oic.utils.authn.user import NoAuthn authn = NoAuthn(None, user=_auth[authkey]["user"]) if authn is not None: ab.add(_auth[authkey]["ACR"], authn, _auth[authkey]["WEIGHT"]) com_args['authn_broker'] = ab # dealing with authorization com_args['authz'] = AuthzHandling() try: if config.USERINFO == "SIMPLE": # User info is a simple dictionary in this case statically defined in # the configuration file com_args['userinfo'] = UserInfo(config.USERDB) else: com_args['userinfo'] = None except AttributeError: pass # Should I care about verifying the certificates used by other entities if args.insecure: com_args["verify_ssl"] = False else: com_args["verify_ssl"] = True try: assert os.path.isfile(config.SERVER_CERT) assert os.path.isfile(config.SERVER_KEY) com_args['client_cert'] = (config.SERVER_CERT, config.SERVER_KEY) except AttributeError: pass except AssertionError: print("Can't access client certificate and/or client secret") exit(-1) op_arg = {} try: op_arg["cookie_ttl"] = config.COOKIETTL except AttributeError: pass try: op_arg["cookie_name"] = config.COOKIENAME except AttributeError: pass # print URLS if args.debug: op_arg["debug"] = True # All endpoints the OpenID Connect Provider should answer on add_endpoints(ENDPOINTS) op_arg["endpoints"] = ENDPOINTS op_arg["baseurl"] = _baseurl # Add own keys for signing/encrypting JWTs try: # a throw-away OP used to do the initial key setup _sdb = create_session_db(com_args["baseurl"], 'automover', '430X', {}) _op = Provider(sdb=_sdb, **com_args) jwks = keyjar_init(_op, config.keys) except KeyError: pass else: op_arg["jwks"] = jwks op_arg['keyjar'] = _op.keyjar #op_arg["keys"] = config.keys try: op_arg["marg"] = multi_keys(com_args, config.multi_keys) except AttributeError as err: pass return com_args, op_arg, config
# the authenticated/authorised users. It includes information # such as "what has been asked for (claims, scopes, and etc. )" # and "the state of the session". There is one entry in the # database per person # # __________ Note __________ # provider.keyjar is an interesting parameter, # currently it uses default values, but # if you have time, it worth investigating. for authnIndexedEndPointWrapper in authnBroker: authnIndexedEndPointWrapper.srv = provider # TODO: this is a point to consider: what if user data in a database? if config.USERINFO == "SIMPLE": provider.userinfo = UserInfo(config.USERDB) provider.cookie_ttl = config.COOKIETTL provider.cookie_name = config.COOKIENAME if args.debug: provider.debug = True try: # JWK: JSON Web Key # JWKS: is a dictionary of JWK # __________ NOTE __________ # JWKS contains private key information. # # keyjar_init configures cryptographic key # based on the provided configuration "keys".
def op_setup(args, config, provider_cls): # Client data base cdb = shelve_wrapper.open("client_db") if args.issuer: _issuer = args.issuer[0] else: if args.port not in [80, 443]: _issuer = config.ISSUER + ':{}'.format(args.port) else: _issuer = config.ISSUER if _issuer[-1] != '/': _issuer += '/' config.SERVICE_URL = config.SERVICE_URL.format(issuer=_issuer) auth_setup = AuthSetup(config, _issuer) auth_setup() # dealing with authorization authz = AuthzHandling() auth_setup.init_mako() kwargs = { "template_lookup": auth_setup.lookup, "template": {"form_post": "form_response.mako"}, # "template_args": {"form_post": {"action": "form_post"}} } # Should I care about verifying the certificates used by other entities if args.insecure: kwargs["verify_ssl"] = False else: kwargs["verify_ssl"] = True if args.capabilities: kwargs["capabilities"] = json.loads(open(args.capabilities).read()) else: pass _sdb = create_session_db(_issuer, 'automover', '430X', {}) _op = provider_cls(_issuer, _sdb, cdb, auth_setup.ac, None, authz, verify_client, config.SYM_KEY, **kwargs) _op.baseurl = _issuer for authn in auth_setup.ac: authn.srv = _op if config.USERINFO == "SIMPLE": # User info is a simple dictionary in this case statically defined in # the configuration file _op.userinfo = UserInfo(config.USERDB) elif config.USERINFO == "SAML": _op.userinfo = UserInfo(config.SAML) elif config.USERINFO == "AA": _op.userinfo = AaUserInfo(config.SP_CONFIG, _issuer, config.SAML) else: raise Exception("Unsupported userinfo source") try: _op.cookie_ttl = config.COOKIETTL except AttributeError: pass try: _op.cookie_name = config.COOKIENAME except AttributeError: pass # print URLS if args.debug: _op.debug = True try: jwks = keyjar_init(_op, config.keys, kid_template="op%d") except Exception as err: logger.error("Key setup failed: %s" % err) _op.key_setup("static", sig={"format": "jwk", "alg": "rsa"}) else: f = open(config.JWKS_FILE_NAME, "w") f.write(json.dumps(jwks)) f.close() _op.jwks_uri = "%s%s" % (_op.baseurl, config.JWKS_FILE_NAME) try: _op.signed_jwks_uri = "%s%s" % (_op.baseurl, config.SIGNED_JWKS_PATH) except AttributeError: pass _op.keyjar.verify_ssl = kwargs["verify_ssl"] for b in _op.keyjar[""]: logger.info("OC3 server keys: %s" % b) return _op
def main(): parser = argparse.ArgumentParser(description='Example OIDC Provider.') parser.add_argument("-p", "--port", default=80, type=int) parser.add_argument("-b", "--base", default="https://localhost", type=str) parser.add_argument("-d", "--debug", action="store_true") parser.add_argument("settings") args = parser.parse_args() # Load configuration with open(args.settings, "r") as f: settings = yaml.load(f) issuer = args.base.rstrip("/") template_dirs = settings["server"].get("template_dirs", "templates") jinja_env = Environment(loader=FileSystemLoader(template_dirs)) authn_broker, auth_routing = setup_authentication_methods( settings["authn"], jinja_env) # Setup userinfo userinfo_conf = settings["userinfo"] cls = make_cls_from_name(userinfo_conf["class"]) i = cls(**userinfo_conf["kwargs"]) userinfo = UserInfo(i) client_db = {} provider = Provider(issuer, SessionDB(issuer), client_db, authn_broker, userinfo, AuthzHandling(), verify_client, None) provider.baseurl = issuer provider.symkey = rndstr(16) # Setup keys path = os.path.join(os.path.dirname(__file__), "static") try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: raise e pass jwks = keyjar_init(provider, settings["provider"]["keys"]) name = "jwks.json" with open(os.path.join(path, name), "w") as f: f.write(json.dumps(jwks)) provider.jwks_uri.append("{}/static/{}".format(provider.baseurl, name)) # Mount the WSGI callable object (app) on the root directory app_routing = setup_endpoints(provider) app_routing["/.well-known/openid-configuration"] = pyoidcMiddleware( provider.providerinfo_endpoint) app_routing["/.well-known/webfinger"] = pyoidcMiddleware( partial(_webfinger, provider)) routing = dict(list(auth_routing.items()) + list(app_routing.items())) routing["/static"] = make_static_handler(path) dispatcher = WSGIPathInfoDispatcher(routing) server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', args.port), dispatcher) # Setup SSL if provider.baseurl.startswith("https://"): server.ssl_adapter = BuiltinSSLAdapter( settings["server"]["cert"], settings["server"]["key"], settings["server"]["cert_chain"]) # Start the CherryPy WSGI web server try: print("Server started: {}".format(issuer)) server.start() except KeyboardInterrupt: server.stop()
"linda": "krall", "hans": "thetake", } USER_DB = { "hans": { "name": "Hans Granberg", "sub": "*****@*****.**" }, "linda": { "name": "Linda Lindgren", "sub": "*****@*****.**" } } USERINFO = UserInfo(USER_DB) KEYS = [ { "type": "RSA", "key": "as.key", "use": ["enc", "sig"] }, ] class DummyAuthn(UserAuthnMethod): def __init__(self, srv, uid="Linda"): UserAuthnMethod.__init__(self, srv) self.user = uid
ac.add(config.AUTHENTICATION[authkey]["ACR"], authn, config.AUTHENTICATION[authkey]["WEIGHT"]) # dealing with authorization authz = AuthzHandling() kwargs = { "template_lookup": LOOKUP, "template": {"form_post": "form_response.mako"}, #"template_args": {"form_post": {"action": "form_post"}} } if config.USERINFO == "SIMPLE": # User info is a simple dictionary in this case statically defined in # the configuration file userinfo = UserInfo(config.USERDB) else: userinfo = None # Should I care about verifying the certificates used by other entities if args.insecure: kwargs["verify_ssl"] = False else: kwargs["verify_ssl"] = True COM_ARGS = { "name": config.issuer, "sdb": SessionDB(config.baseurl), "cdb": cdb, "authn_broker": ac, "userinfo": userinfo,