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 __init__(self, srv, ldapsrv, return_to, pattern, mako_template, template_lookup, ldap_user="", ldap_pwd="", verification_endpoints=["verify"]): """ :param srv: The server instance :param ldapsrv: Which LDAP server to us :param return_to: Where to send the user after authentication :param pattern: How to find the entry to log in to. Expected to be a dictionary where key is one of "dn" or "search". And the value a dictionary with values depends on the key: If "dn" only "pattern". If "search": "base", "filterstr", "scope" "base" and "filterstr" MUST be present :param ldap_user: If a search has to be done first which user to do that as. "" is a anonymous user :param ldap_pwd: The password for the ldap_user """ UsernamePasswordMako.__init__( self, srv, mako_template, template_lookup, None, return_to, verification_endpoints=verification_endpoints) self.ldap = ldap.initialize(ldapsrv) self.ldap.protocol_version = 3 self.ldap.set_option(ldap.OPT_REFERRALS, 0) self.pattern = pattern self.ldap_user = ldap_user self.ldap_pwd = ldap_pwd
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(compact(parse_qs(form))) headers = dict(response.headers) user, timestamp = authn.authenticated_as(headers["Set-Cookie"]) assert user == {"uid": "user"}
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_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(compact(parse_qs(form))) headers = dict(response.headers) kaka = headers["Set-Cookie"] kaka = kaka.replace("1", "x") assert authn.authenticated_as(kaka) == (None, 0)
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 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_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_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_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
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"])
config.issuer = config.issuer % args.port config.SERVICE_URL = config.SERVICE_URL % args.port ac = AuthnBroker() for authkey, value in config.AUTHORIZATION.items(): authn = None if "CAS" == authkey: from oic.utils.authn.user_cas import CasAuthnMethod from oic.utils.authn.ldap_member import UserLDAPMemberValidation config.LDAP_EXTRAVALIDATION.update(config.LDAP) authn = CasAuthnMethod(None, config.CAS_SERVER, config.SERVICE_URL,"%s/authorization" % config.issuer, UserLDAPMemberValidation(**config.LDAP_EXTRAVALIDATION)) if "UserPassword" == authkey: from oic.utils.authn.user import UsernamePasswordMako authn = UsernamePasswordMako(None, "login.mako", LOOKUP, PASSWD, "%s/authorization" % config.issuer) if authn is not None: ac.add(config.AUTHORIZATION[authkey]["ACR"], authn, config.AUTHORIZATION[authkey]["WEIGHT"], config.AUTHORIZATION[authkey]["URL"]) # dealing with authorization authz = AuthzHandling() # authz = UserInfoConsent() # User info database if args.insecure: kwargs = {"verify_ssl": False} else: kwargs = {"verify_ssl": True}
def test_authenticated_as_no_cookie(self): authn = UsernamePasswordMako(None, "login.mako", tl, PASSWD, "authorization_endpoint") res = authn.authenticated_as() assert res == (None, 0)
def test_call(self): authn = UsernamePasswordMako(None, "login.mako", tl, PASSWD, "authorization_endpoint") resp = authn(query="QUERY") assert 'name="query" value="QUERY"' in resp.message assert 'name="login" value=""' in resp.message
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,
def test_1(): authn = UsernamePasswordMako(None, "login.mako", tl, PASSWD, "authorization_endpoint") assert authn.authenticated_as() is None
# 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
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:
# 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, userinfo=config.USERINFO) 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 = { "template_lookup": LOOKUP,
def test_1(): authn = UsernamePasswordMako(None, "login.mako", tl, PASSWD, "authorization_endpoint") assert authn.authenticated_as()[0] is None