def as_setup(jconf): _module = importlib.import_module('oic.utils.authn.user') ab = AuthnBroker() for _id, authn in jconf["authn"].items(): cls = getattr(_module, authn["class"]) if "template_lookup" in authn["kwargs"]: authn["kwargs"]["template_lookup"] = lookup(jconf["template_root"]) ci = cls(None, **authn["kwargs"]) ab.add(_id, ci, authn["level"], authn["authn_authority"]) _base = jconf["configuration"]["issuer"] cauth = dict([(x, CLIENT_AUTHN_METHOD[x]) for x in jconf["client_auth_methods"]]) return { "name": _base, "sdb": {}, "cdb": {}, "authn_broker": ab, "authz": Implicit("PERMISSION"), "client_authn": verify_client, "symkey": "1234567890123456", "client_authn_methods": cauth, "client_info_url": jconf["client_info_url"], "default_acr": jconf["default_acr"], "keyjar": None }
def test_pkce_verify_256(self, session_db_factory): _cli = Client( config={"code_challenge": { "method": "S256", "length": 64 }}) args, cv = _cli.add_code_challenge() authn_broker = AuthnBroker() authn_broker.add("UNDEFINED", DummyAuthn(None, "username")) _prov = Provider( "as", session_db_factory("https://connect-op.heroku.com"), {}, authn_broker, Implicit(), verify_client, ) assert _prov.verify_code_challenge(cv, args["code_challenge"]) is True assert _prov.verify_code_challenge(cv, args["code_challenge"], "S256") is True resp = _prov.verify_code_challenge("XXX", args["code_challenge"]) assert isinstance(resp, Response) assert resp.info()["status_code"] == 401
def test_password_grant_type_no_authn(self): # Set a blank AuthnBroker self.provider.authn_broker = AuthnBroker() self.provider.set_token_policy('client1', {'grant_type': ['password']}) areq = ROPCAccessTokenRequest(grant_type='password', username='******', password='******') areq['client_id'] = 'client1' # Token endpoint would fill that in based on client_authn resp = self.provider.password_grant_type(areq) atr = TokenErrorResponse().deserialize(resp.message, "json") assert atr['error'] == 'invalid_grant'
def test_pkce_verify_512(): _cli = Client(config={'code_challenge': {'method': 'S512', 'length': 96}}) args, cv = _cli.add_code_challenge() authn_broker = AuthnBroker() authn_broker.add("UNDEFINED", DummyAuthn(None, "username")) _prov = Provider("as", sdb.SessionDB(SERVER_INFO["issuer"]), CDB, authn_broker, Implicit(), verify_client) assert _prov.verify_code_challenge(cv, args['code_challenge'], 'S512') is True
def test(self): ac = AuthnBroker() issuer = "https://example.com/op" CAS_SERVER = "" SERVICE_URL = "" LDAP = { "uri": "ldaps://ldap.umu.se", "base": "dc=umu, dc=se", "filter_pattern": "(uid=%s)", "user": "", "passwd": "", "attr": ["eduPersonScopedAffiliation", "eduPersonAffiliation"], } LDAP_EXTRAVALIDATION = { "verify_attr": "eduPersonAffiliation", "verify_attr_valid": ["employee", "staff", "student"], } LDAP_EXTRAVALIDATION.update(LDAP) ac.add( PASSWORD, UsernamePasswordMako(None, "login.mako", LOOKUP, PASSWD, "%s/authorization" % issuer), 10, "http://%s" % socket.gethostname(), ) try: ac.add( PASSWORD, CasAuthnMethod( None, CAS_SERVER, SERVICE_URL, "%s/authorization" % issuer, UserLDAPMemberValidation(**LDAP_EXTRAVALIDATION), ), 20, "http://%s" % socket.gethostname(), ) except Exception: assert len(ac) == 1 else: assert len(ac) == 2 res = ac.pick(PASSWORD) assert res # list of two 2-tuples assert len(res) == 2 assert res[0][0].__class__.__name__ == "CasAuthnMethod" assert res[1][0].__class__.__name__ == "UsernamePasswordMako"
def setup_authentication_methods(authn_config, template_env): """Add all authentication methods specified in the configuration.""" routing = {} ac = AuthnBroker() for authn_method in authn_config: cls = make_cls_from_name(authn_method["class"]) instance = cls(template_env=template_env, **authn_method["kwargs"]) ac.add(authn_method["acr"], instance) routing[instance.url_endpoint] = VerifierMiddleware(instance) return ac, routing
def main(base, cookie_handler): as_conf = { "version": "1.0", "issuer": base, "pat_profiles_supported": ["bearer"], "aat_profiles_supported": ["bearer"], "rpt_profiles_supported": ["bearer"], "pat_grant_types_supported": ["authorization_code"], "aat_grant_types_supported": ["authorization_code"], "claim_profiles_supported": ["openid"], #"dynamic_client_endpoint": "%s/dynamic_client_endpoint" % BASE, #"token_endpoint": "%s/token_endpoint" % BASE, #"user_endpoint": "%s/user_endpoint" % BASE, #"resource_set_registration_endpoint": "%s/rsr_endpoint" % BASE, #"introspection_endpoint": "%s/introspection_endpoint" % BASE, #"permission_registration_endpoint": "%s/pr_endpoint" % BASE, #"rpt_endpoint": "%s/rpt_endpoint" % BASE, #"authorization_request_endpoint": "%s/ar_endpoint" % BASE, #"userinfo_endpoint": "%s/user_info_endpoint" % BASE # ------------ The OIDC provider config ----------------------- } base_url = "http://%s" % socket.gethostname() ab = AuthnBroker() ab.add("linda", DummyAuthn(None, "linda")) #AB.add("hans", DummyAuthn(None, "*****@*****.**")) ab.add( "UserPwd", UsernamePasswordMako(None, "login2.mako", LOOKUP, PASSWD, "%s/authorization" % base), 10, base_url) ab.add("BasicAuthn", BasicAuthnExtra(None, PASSWD), 10, base_url) AUTHZSRV = authzsrv.OidcDynRegUmaAS(base, SessionDB(base_url), CDB, ab, USERINFO, AUTHZ, verify_client, "1234567890", keyjar=None, configuration=as_conf, base_url=base) cookie_handler.init_srv(AUTHZSRV) jwks = keyjar_init(AUTHZSRV, KEYS, "a%d") fp = open("static/jwk_as.json", "w") fp.write(json.dumps(jwks)) fp.close() return AUTHZSRV
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 test_password_grant_type_no_authn(self): # Set a blank AuthnBroker self.provider.authn_broker = AuthnBroker() self.provider.set_token_policy("client1", {"grant_type": ["password"]}) areq = ROPCAccessTokenRequest(grant_type="password", username="******", password="******") areq[ "client_id"] = "client1" # Token endpoint would fill that in based on client_authn resp = self.provider.password_grant_type(areq) atr = TokenErrorResponse().deserialize(resp.message, "json") assert atr["error"] == "invalid_grant"
def authn_setup(config): broker = AuthnBroker() # Which methods to use is defined in the configuration file for authkey, method_conf in config.AUTHN_METHOD.items(): try: func = AUTH_METHOD[authkey] except KeyError: pass else: broker.add(method_conf["ACR"], func(method_conf), method_conf["WEIGHT"], method_conf["URL"]) return broker
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 test_pkce_verify_512(self, session_db_factory): _cli = Client(config={'code_challenge': {'method': 'S512', 'length': 96}}) args, cv = _cli.add_code_challenge() authn_broker = AuthnBroker() authn_broker.add("UNDEFINED", DummyAuthn(None, "username")) _prov = Provider("as", session_db_factory('https://connect-op.heroku.com'), {}, authn_broker, Implicit(), verify_client) assert _prov.verify_code_challenge(cv, args['code_challenge'], 'S512') is True resp = _prov.verify_code_challenge('XXX', args['code_challenge']) assert isinstance(resp, Response) assert resp.info()['status_code'] == 401
def create_provider(self): authn_broker = AuthnBroker() authn_broker.add("UNDEFINED", DummyAuthn(None, "username")) self.provider = Provider("pyoicserv", sdb.SessionDB( TestProvider.SERVER_INFO["issuer"]), TestProvider.CDB, authn_broker, Implicit(), verify_client, client_info_url="https://example.com/as", client_authn_methods={ "client_secret_post": ClientSecretPost, "client_secret_basic": ClientSecretBasic, "bearer_header": BearerHeader})
def test_pkce_verify_256(session_db_factory): _cli = Client(config={'code_challenge': {'method': 'S256', 'length': 64}}) args, cv = _cli.add_code_challenge() authn_broker = AuthnBroker() authn_broker.add("UNDEFINED", DummyAuthn(None, "username")) _prov = Provider("as", session_db_factory(SERVER_INFO["issuer"]), CDB, authn_broker, Implicit(), verify_client) assert _prov.verify_code_challenge(cv, args['code_challenge']) is True assert _prov.verify_code_challenge(cv, args['code_challenge'], 'S256') is True resp = _prov.verify_code_challenge('XXX', args['code_challenge']) assert isinstance(resp, Response) assert resp.info()['status_code'] == 401
def main(base, cookie_handler): as_conf = { "version": "1.0", "issuer": base, "pat_profiles_supported": ["bearer"], "aat_profiles_supported": ["bearer"], "rpt_profiles_supported": ["bearer"], "pat_grant_types_supported": ["authorization_code"], "aat_grant_types_supported": ["authorization_code"], "claim_profiles_supported": ["openid"], #"dynamic_client_endpoint": "%s/dynamic_client_endpoint" % BASE, #"token_endpoint": "%s/token_endpoint" % BASE, #"user_endpoint": "%s/user_endpoint" % BASE, #"resource_set_registration_endpoint": "%s/rsr_endpoint" % BASE, #"introspection_endpoint": "%s/introspection_endpoint" % BASE, #"permission_registration_endpoint": "%s/pr_endpoint" % BASE, #"rpt_endpoint": "%s/rpt_endpoint" % BASE, #"authorization_request_endpoint": "%s/ar_endpoint" % BASE, #"userinfo_endpoint": "%s/user_info_endpoint" % BASE # ------------ The OIDC provider config ----------------------- } base_url = "http://%s" % socket.gethostname() ab = AuthnBroker() ab.add("linda", DummyAuthn(None, "linda")) ab.add("hans", DummyAuthn(None, "hans")) AUTHZSRV = FakeUmaAs(base, SessionDB(base_url), CDB, ab, USERINFO, AUTHZ, verify_client, "1234567890", keyjar=None, configuration=as_conf, base_url=base) cookie_handler.init_srv(AUTHZSRV) jwks = keyjar_init(AUTHZSRV, KEYS, "a%d") fp = open("static/jwk_as.json", "w") fp.write(json.dumps(jwks)) fp.close() return AUTHZSRV
def test_pkce_verify_512(session_db_factory): _cli = Client(config={"code_challenge": {"method": "S512", "length": 96}}) args, cv = _cli.add_code_challenge() authn_broker = AuthnBroker() authn_broker.add("UNDEFINED", DummyAuthn(None, "username")) _prov = Provider( "as", session_db_factory(SERVER_INFO["issuer"]), CDB, authn_broker, Implicit(), verify_client, ) assert _prov.verify_code_challenge(cv, args["code_challenge"], "S512") is True resp = _prov.verify_code_challenge("XXX", args["code_challenge"]) assert isinstance(resp, Response) assert resp.info()["status_code"] == 401
def __init__(self, config, issuer): self.config = config self.issuer = issuer self.root = None self.lookup = None self.username_password_authn = None self.saml_authn = None self.javascript_login_authn = None self.urls = [] self.ac = AuthnBroker() self.authn = False end_points = config.AUTHENTICATION["UserPassword"]["END_POINTS"] self.full_end_point_paths = [ "{}{}".format(self.issuer, ep) for ep in end_points] self.auth_methods = { "UserPassword": self.user_password, # "JavascriptLogin": self.javascript_login, # "SAML": self.saml_login, # "SamlPass": self.saml_pass_login, # "JavascriptPass": self.javascript_passw_login }
class DummyAuthn(UserAuthnMethod): def __init__(self, srv, user): UserAuthnMethod.__init__(self, srv) self.user = user 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
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=80, type=int) parser.add_argument('-k', dest='insecure', action='store_true') parser.add_argument(dest="config") args = parser.parse_args() # Client data base cdb = shelve.open("client_db", writeback=True) sys.path.insert(0, ".") config = importlib.import_module(args.config) config.issuer = config.issuer % args.port config.SERVICE_URL = config.SERVICE_URL % args.port ac = AuthnBroker() for authkey, value in config.AUTHENTICATION.items(): authn = None if "UserPassword" == authkey: from oic.utils.authn.user import UsernamePasswordMako authn = UsernamePasswordMako(None, "login.mako", LOOKUP, PASSWD, "%s/authorization" % config.issuer) if "SAML" == authkey: from oic.utils.authn.saml import SAMLAuthnMethod authn = SAMLAuthnMethod(None, LOOKUP, config.SAML, config.SP_CONFIG, config.issuer, "%s/authorization" % config.issuer, config.SERVICE_URL) if authn is not None: ac.add(config.AUTHENTICATION[authkey]["ACR"], authn,
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
config = importlib.import_module(args.config) config.ISSUER = config.ISSUER + ':{}/'.format(config.PORT) config.SERVICEURL = config.SERVICEURL.format(issuer=config.ISSUER) endPoints = config.AUTHENTICATION["UserPassword"]["EndPoints"] fullEndPointsPath = ["%s%s" % (config.ISSUER, ep) for ep in endPoints] # TODO: why this instantiation happens so early? can I move it later? # An OIDC Authorization/Authentication server is designed to # allow more than one authentication method to be used by the server. # And that is what the AuthBroker is for. # Given information about the authorisation request, the AuthBroker # chooses which method(s) to be used for authenticating the person/entity. # According to the OIDC standard a Relaying Party can say # 'I want this type of authentication', and the AuthnBroker tries to pick # methods from the set it has been supplied, to map that request. authnBroker = AuthnBroker() # UsernamePasswordMako: authenticas a user using the username/password form in a # WSGI environment using Mako as template system usernamePasswordAuthn = UsernamePasswordMako( None, # server instance "login.mako", # a mako template lookup, # lookup template usernamePasswords, # username/password dictionary-like database "%sauthorization" % config.ISSUER, # where to send the user after authentication None, # templ_arg_func ??!! fullEndPointsPath) # verification endpoints # AuthnIndexedEndpointWrapper is a wrapper class for using an authentication module with multiple endpoints. authnIndexedEndPointWrapper = AuthnIndexedEndpointWrapper(
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
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
BASE = "http://localhost:%s/" % PORT RESOURCE_SERVER = "https://localhost:8089" # The UMA AS=C combo as_conf = { "version": "1.0", "issuer": BASE, "pat_profiles_supported": ["bearer"], "aat_profiles_supported": ["bearer"], "rpt_profiles_supported": ["bearer"], "pat_grant_types_supported": ["authorization_code"], "aat_grant_types_supported": ["authorization_code"], "claim_profiles_supported": ["openid"], } ab = AuthnBroker() ab.add("alice", DummyAuthn(None, "alice")) ab.add( "UserPwd", UsernamePasswordMako(None, "login2.mako", LOOKUP, PASSWD, "%s/authorization" % BASE), 10, "http://%s" % socket.gethostname()) ab.add("BasicAuthn", BasicAuthnExtra(None, PASSWD), 10, "http://%s" % socket.gethostname()) AUTHZSRV = AuthorizationServer(BASE, SessionDB(), CDB, ab, AUTHZ, verify_client,