def test_verify(self, srv): form = create_return_form_env("user", "hemligt", "query=foo") authn = UsernamePasswordMako(srv, "login.mako", tl, PASSWD, "authorization_endpoint") with LogCapture(level=logging.DEBUG) as logcap: response, success = authn.verify(compact(parse_qs(form))) assert query_string_compare( response.message.split("?")[1], "query=foo&upm_answer=true") headers = dict(response.headers) assert headers["Set-Cookie"].startswith('xyzxyz=') expected = { u'query': u'query=foo', u'login': u'user', u'password': '******' } # We have to use eval() here to avoid intermittent # failures from dict ordering assert eval(logcap.records[0].msg[7:-1]) == expected expected = { u'query': u'query=foo', u'login': u'user', u'password': '******' } assert eval(logcap.records[1].msg[5:]) == expected assert logcap.records[2].msg == 'Password verification succeeded.' expected = {u'query': [u'foo'], 'upm_answer': 'true'} assert eval(logcap.records[3].msg[8:]) == expected
def test_2(): authn = UsernamePasswordMako(None, "login.mako", tl, PASSWD, "authorization_endpoint") resp = authn(query="QUERY") print resp.message assert 'name="query" value="QUERY"' in resp.message assert 'name="login" value=""' in resp.message
def test_verify_unauthorized(self, srv): form = create_return_form_env("user", "secret", "QUERY") authn = UsernamePasswordMako(srv, "login.mako", tl, PASSWD, "authorization_endpoint") response, state = authn.verify(parse_qs(form)) assert isinstance(response, Unauthorized)
def test_authenticated_as(self, srv): form = create_return_form_env("user", "hemligt", "QUERY") authn = UsernamePasswordMako(srv, "login.mako", tl, PASSWD, "authorization_endpoint") response, success = authn.verify(parse_qs(form)) headers = dict(response.headers) user, timestamp = authn.authenticated_as(headers["Set-Cookie"]) assert user == {"uid": "user"}
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 test_verify(self, srv): form = create_return_form_env("user", "hemligt", "query=foo") authn = UsernamePasswordMako(srv, "login.mako", tl, PASSWD, "authorization_endpoint") response, success = authn.verify(parse_qs(form)) assert query_string_compare( response.message.split("?")[1], "query=foo&upm_answer=true") headers = dict(response.headers) assert headers["Set-Cookie"].startswith('xyzxyz=')
def test_6(): form = create_return_form_env("user", "secret", "QUERY") srv = SRV() srv.symkey = rndstr(16) srv.seed = rndstr() srv.iv = os.urandom(16) srv.cookie_name = "xyzxyz" authn = UsernamePasswordMako(srv, "login.mako", tl, PASSWD, "authorization_endpoint") response = authn.verify(parse_qs(form)) assert isinstance(response, Unauthorized)
def test_not_authenticated(self, srv): form = create_return_form_env("user", "hemligt", "QUERY") authn = UsernamePasswordMako(srv, "login.mako", tl, PASSWD, "authorization_endpoint") response, state = authn.verify(parse_qs(form)) headers = dict(response.headers) kaka = headers["Set-Cookie"] kaka = kaka.replace("1", "x") assert authn.authenticated_as(kaka) == (None, 0)
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 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 user_password(self, info): self.init_mako() self.username_password_authn = UsernamePasswordMako( None, "login.mako", self.lookup, self.config.PASSWD, "%sauthorization" % self.issuer, None, self.full_end_point_paths) PASSWORD_END_POINT_INDEX = 0 end_point = info["END_POINTS"][PASSWORD_END_POINT_INDEX] authn = AuthnIndexedEndpointWrapper(self.username_password_authn, PASSWORD_END_POINT_INDEX) self.urls.append((r'^' + end_point, make_auth_verify(authn.verify))) return authn
def test_3(): form = create_return_form_env("user", "hemligt", "query=foo") srv = SRV() srv.symkey = rndstr(16) srv.seed = rndstr() srv.iv = os.urandom(16) srv.cookie_name = "xyzxyz" authn = UsernamePasswordMako(srv, "login.mako", tl, PASSWD, "authorization_endpoint") response = authn.verify(parse_qs(form)) assert response.message == "authorization_endpoint?query=foo&upm_answer=true" print len(response.headers) == 2 flag = 0 for param, val in response.headers: if param == "Set-Cookie": assert val.startswith('xyzxyz=') flag = 1 assert flag == 1
def test_5(): form = create_return_form_env("user", "hemligt", "QUERY") srv = SRV() srv.symkey = rndstr(16) srv.seed = rndstr() srv.iv = os.urandom(16) srv.cookie_name = "xyzxyz" authn = UsernamePasswordMako(srv, "login.mako", tl, PASSWD, "authorization_endpoint") response = authn.verify(parse_qs(form)) kaka = "" for param, val in response.headers: if param == "Set-Cookie": kaka = val break kaka = kaka.replace("1", "x") try: _ = authn.authenticated_as(kaka) assert False except Exception: assert True
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, "1234567890123456", keyjar=None, configuration=as_conf, base_url=BASE, client_info_url="%s/" % BASE,
# 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( usernamePasswordAuthn, passwordEndPointIndex) authnBroker.add( config.AUTHENTICATION["UserPassword"]["ACR"], # (?!) authnIndexedEndPointWrapper, # (?!) method: an identifier of the authentication method. config.AUTHENTICATION["UserPassword"]["WEIGHT"], # security level "") # (?!) authentication authority
# 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, config.AUTHENTICATION[authkey]["WEIGHT"], config.AUTHENTICATION[authkey]["URL"]) # dealing with authorization authz = AuthzHandling() kwargs = {
def test_authenticated_as_no_cookie(self): authn = UsernamePasswordMako(None, "login.mako", tl, PASSWD, "authorization_endpoint") res = authn.authenticated_as() assert res == (None, 0)
} } URLMAP = {CLIENT_ID: ["https://example.com/authz"]} PASSWD = {"user": "******"} ROOT = '../oc3/' tl = TemplateLookup(directories=[ROOT + 'templates', ROOT + 'htdocs'], module_directory=ROOT + 'modules', input_encoding='utf-8', output_encoding='utf-8') AUTHN_BROKER = AuthnBroker() AUTHN_BROKER.add( "1", UsernamePasswordMako(None, "login.mako", tl, PASSWD, "authenticated")) # dealing with authorization AUTHZ = AuthzHandling() SYMKEY = "symmetric key used to encrypt cookie info" USERINFO = UserInfo(USERDB) provider_init = Provider("pyoicserv", SessionDB(SERVER_INFO["issuer"]), CDB, AUTHN_BROKER, USERINFO, AUTHZ, verify_client, SYMKEY, urlmap=URLMAP,
def userpwd_setup(item): from oic.utils.authn.user import UsernamePasswordMako _conf = item["config"] return UsernamePasswordMako(None, "login.mako", _conf["lookup"], _conf["passwd"], _conf["return_to"])
sys.path.insert(0, ".") config = importlib.import_module(args.config) if args.baseurl: config.baseurl = args.baseurl config.issuer = config.issuer.format(base=config.baseurl, port=args.port) config.SERVICE_URL = config.SERVICE_URL.format(issuer=config.issuer) ac = AuthnBroker() saml_authn = None end_points = config.AUTHENTICATION["UserPassword"]["END_POINTS"] full_end_point_paths = ["%s%s" % (config.issuer, ep) for ep in end_points] username_password_authn = UsernamePasswordMako( None, "login.mako", LOOKUP, PASSWD, "%sauthorization" % config.issuer, None, full_end_point_paths) for authkey, value in config.AUTHENTICATION.items(): authn = None if "UserPassword" == authkey: PASSWORD_END_POINT_INDEX = 0 end_point = config.AUTHENTICATION[authkey]["END_POINTS"][ PASSWORD_END_POINT_INDEX] authn = AuthnIndexedEndpointWrapper(username_password_authn, PASSWORD_END_POINT_INDEX) URLS.append((r'^' + end_point, make_auth_verify(authn.verify))) # Ensure javascript_login_authn to be defined try:
def test_1(): authn = UsernamePasswordMako(None, "login.mako", tl, PASSWD, "authorization_endpoint") assert authn.authenticated_as() is None