def create_authn_request(self, session, acr_value=None): session["state"] = rndstr() session["nonce"] = rndstr() request_args = { "response_type": self.behaviour["response_type"], "scope": self.behaviour["scope"], "state": session["state"], "nonce": session["nonce"], "redirect_uri": self.registration_response["redirect_uris"][0] } if acr_value is not None: request_args["acr_values"] = acr_value cis = self.construct_AuthorizationRequest(request_args=request_args) logger.debug("request: %s" % cis) url, body, ht_args, cis = self.uri_and_body(AuthorizationRequest, cis, method="GET", request_args=request_args) logger.debug("body: %s" % body) logger.info("URL: %s" % url) logger.debug("ht_args: %s" % ht_args) resp = Redirect(str(url)) if ht_args: resp.headers.extend([(a, b) for a, b in ht_args.items()]) logger.debug("resp_headers: %s" % resp.headers) return resp
def create(self, redirect_uris=None, policy_uri="", logo_uri=""): if redirect_uris is None: print 'Enter redirect_uris one at the time, end with a blank line: ' redirect_uris = [] while True: redirect_uri = raw_input('?: ') if redirect_uri: redirect_uris.append(redirect_uri) else: break if not policy_uri: policy_uri = raw_input("Enter policy_uri or just return: ") if not logo_uri: logo_uri = raw_input("Enter logo_uri or just return: ") client_id = rndstr(12) while client_id in self.cdb: client_id = rndstr(12) client_secret = secret(self.seed, client_id) self.cdb[client_id] = { "client_secret": client_secret, "client_id": client_id, "redirect_uris": pack_redirect_uri(redirect_uris), "policy_uri": policy_uri, "logo_uri": logo_uri, } return self.cdb[client_id]
def create_new_client(self, request): """ :param request: The Client registration request :return: The client_id """ _cinfo = request.to_dict() # create new id and secret _id = rndstr(12) while _id in self.cdb: _id = rndstr(12) _cinfo["client_id"] = _id _cinfo["client_secret"] = secret(self.seed, _id) _cinfo["client_id_issued_at"] = utc_time_sans_frac() _cinfo["client_secret_expires_at"] = utc_time_sans_frac() + \ self.secret_lifetime # If I support client info endpoint if ClientInfoEndpoint in self.endp: _cinfo["registration_access_token"] = rndstr(32) _cinfo["registration_client_uri"] = "%s%s?client_id=%s" % ( self.client_info_url, ClientInfoEndpoint.etype, _id) if "redirect_uris" in request: _cinfo["redirect_uris"] = self._uris_to_tuples( request["redirect_uris"]) self.cdb[_id] = _cinfo return _id
def get_request_args(self, client, acr_value, session): """ :param client: Client instance :param acr_value: Authentication Context reference :param session: Session information :return: A set of Authorization request arguments """ request_args = { "response_type": self.flow_type, "scope": self.pool_config["scope"], "state": client.state, } if acr_value: request_args["acr_values"] = [acr_value] if self.flow_type == "token": request_args["nonce"] = rndstr(16) session["nonce"] = request_args["nonce"] else: use_nonce = getattr(self, "use_nonce", None) if use_nonce: request_args["nonce"] = rndstr(16) session["nonce"] = request_args["nonce"] logger.info("client args: %s" % list(client.__dict__.items()), ) logger.info("request_args: %s" % (request_args,)) return client, request_args
def create_authn_request(self, session, acr_value=None, **kwargs): session["state"] = rndstr() session["nonce"] = rndstr() request_args = { "response_type": self.behaviour["response_type"], "scope": self.behaviour["scope"], "state": session["state"], "nonce": session["nonce"], "redirect_uri": self.config.ME["redirect_uris"][0], } if self.config.DO_CLIENT_REGISTRATION: request_args["software_statement"] = self.software_statement if acr_value is not None: request_args["acr_values"] = acr_value request_args.update(kwargs) cis = self.construct_AuthorizationRequest(request_args=request_args) LOGGER.debug("request: %s", cis) url, body, ht_args, cis = self.uri_and_body(AuthorizationRequest, cis, method="GET", request_args=request_args) LOGGER.debug("body: %s", body) LOGGER.info("URL: %s", url) LOGGER.debug("ht_args: %s", ht_args) resp = Redirect(str(url)) if ht_args: resp.headers.extend([(a, b) for a, b in ht_args.items()]) LOGGER.debug("resp_headers: %s", resp.headers) return resp
def construct_AuthorizationRequest(self, request=AuthorizationRequest, request_args=None, extra_args=None, request_param=None, **kwargs): if request_args is not None: # if "claims" in request_args: # kwargs["claims"] = request_args["claims"] # del request_args["claims"] if "nonce" not in request_args: _rt = request_args["response_type"] if "token" in _rt or "id_token" in _rt: request_args["nonce"] = rndstr(12) elif "response_type" in kwargs: if "token" in kwargs["response_type"]: request_args = {"nonce": rndstr(12)} else: # Never wrong to specify a nonce request_args = {"nonce": rndstr(12)} if "request_method" in kwargs: if kwargs["request_method"] == "file": request_param = "request_uri" del kwargs["request_method"] areq = oauth2.Client.construct_AuthorizationRequest(self, request, request_args, extra_args, **kwargs) if request_param: alg = self.behaviour["request_object_signing_alg"] if "algorithm" not in kwargs: kwargs["algorithm"] = alg if "keys" not in kwargs and alg: _kty = alg2keytype(alg) try: kwargs["keys"] = self.keyjar.get_signing_key( _kty, kid=self.kid["sig"][_kty]) except KeyError: kwargs["keys"] = self.keyjar.get_signing_key(_kty) _req = make_openid_request(areq, **kwargs) if request_param == "request": areq["request"] = _req else: _filedir = kwargs["local_dir"] _webpath = kwargs["base_path"] _name = rndstr(10) filename = os.path.join(_filedir, _name) while os.path.exists(filename): _name = rndstr(10) filename = os.path.join(_filedir, _name) fid = open(filename, mode="w") fid.write(_req) fid.close() _webname = "%s%s" % (_webpath, _name) areq["request_uri"] = _webname return areq
def create_authn_request(self, session, acr_value=None, **kwargs): session["state"] = rndstr() session["nonce"] = rndstr() request_args = { "response_type": self.behaviour["response_type"], "scope": self.behaviour["scope"], "state": session["state"], "nonce": session["nonce"], "redirect_uri": self.registration_response["redirect_uris"][0] } if acr_value is not None: request_args["acr_values"] = acr_value request_args.update(kwargs) cis = self.construct_AuthorizationRequest(request_args=request_args) logger.debug("request: %s" % cis) url, body, ht_args, cis = self.uri_and_body(AuthorizationRequest, cis, method="GET", request_args=request_args) logger.debug("body: %s" % body) logger.info("URL: %s" % url) logger.debug("ht_args: %s" % ht_args) resp = HttpResponseRedirect(url) if ht_args: for key, value in ht_args.items(): resp[key] = value logger.debug("resp_headers: %s" % ht_args) return resp
def create_authnrequest(self, environ, server_env, start_response, session, acr_value): try: client = session.getClient() session.setAcrValue(client.authorization_endpoint, acr_value) request_args = { "response_type": self.flow_type, "scope": self.extra["scope"], "state": client.state, } if acr_value is not None: request_args["acr_values"] = acr_value if self.flow_type == "token": request_args["nonce"] = rndstr(16) session.setNonce(request_args["nonce"]) else: use_nonce = getattr(self, "use_nonce", None) if use_nonce: request_args["nonce"] = rndstr(16) session.setNonce(request_args["nonce"]) logger.info("client args: %s" % client.__dict__.items(),) logger.info("request_args: %s" % (request_args,)) # User info claims except Exception: message = traceback.format_exception(*sys.exc_info()) logger.error(message) return self.result(environ, start_response, server_env,(False, "Cannot find the OP! Please view your configuration of pyoidc RP.")) try: cis = client.construct_AuthorizationRequest( request_args=request_args) logger.debug("request: %s" % cis) url, body, ht_args, cis = client.uri_and_body( AuthorizationRequest, cis, method="GET", request_args=request_args) logger.debug("body: %s" % body) except Exception: message = traceback.format_exception(*sys.exc_info()) logger.error(message) return self.result(environ, start_response, server_env,(False, "Authorization request can not be performed!")) logger.info("URL: %s" % url) logger.debug("ht_args: %s" % ht_args) #session.setAuthn_auth(client.authorization_endpoint) #session.setAuthentication("VERIFY") #server_env["CACHE"][sid] = session session.setClient(client) resp_headers = [("Location", str(url))] if ht_args: resp_headers.extend([(a, b) for a, b in ht_args.items()]) logger.debug("resp_headers: %s" % resp_headers) start_response("302 Found", resp_headers) return []
def registration_endpoint(self, data): req = self.parse_registration_request(data) client_secret = rndstr() expires = utc_time_sans_frac() + self.registration_expires_in if req["type"] == "client_associate": client_id = rndstr(10) self.client[client_id] = { "client_secret": client_secret, "info": req.to_dict(), "expires": expires } else: client_id = req.client_id _cinfo = self.client[req.client_id] _cinfo["info"].update(req.to_dict()) _cinfo["client_secret"] = client_secret _cinfo["expires"] = expires resp = RegistrationResponseCARS(client_id=client_id, client_secret=client_secret, expires_at=expires) response = Response() response.headers = {"content-type":"application/json"} response.text = resp.to_json() return response
def get_request_args(self, acr_value, session): """ :param acr_value: Authentication Context reference :param session: Session information :return: A set of Authorization request arguments """ self.state = rndstr() request_args = { "response_type": self.flow_type, "scope": self.scope, "state": self.state, } if acr_value: request_args["acr_values"] = [acr_value] if self.flow_type == "token": request_args["nonce"] = rndstr(16) session["nonce"] = request_args["nonce"] else: use_nonce = getattr(self, "use_nonce", None) if use_nonce: request_args["nonce"] = rndstr(16) session["nonce"] = request_args["nonce"] logger.debug("request_args: %s" % (request_args,)) return request_args
def construct_OpenIDRequest(self, request=OpenIDRequest, request_args=None, extra_args=None, **kwargs): if request_args is not None: for arg in ["idtoken_claims", "userinfo_claims"]: if arg in request_args: kwargs[arg] = request_args[arg] del request_args[arg] if "nonce" not in request_args and "token" in \ request_args["response_type"]: request_args["nonce"] = rndstr(12) elif "response_type" in kwargs: if "token" in kwargs["response_type"]: request_args = {"nonce": rndstr(12)} else: # Never wrong to specify a nonce request_args = {"nonce": rndstr(12)} areq = oauth2.Client.construct_AuthorizationRequest(self, request, request_args, extra_args, **kwargs) if "key" not in kwargs: kwargs["keys"] = self.keystore.get_sign_key() if "userinfo_claims" in kwargs or "idtoken_claims" in kwargs: areq["request"] = make_openid_request(areq, **kwargs) return areq
def create(self, redirect_uris=None, policy_uri="", logo_uri=""): if redirect_uris is None: print 'Enter redirect_uris one at the time, end with a blank line: ' redirect_uris = [] while True: redirect_uri = raw_input('?: ') if redirect_uri: redirect_uris.append(redirect_uri) else: break if not policy_uri: policy_uri = raw_input("Enter policy_uri or just return: ") if not logo_uri: logo_uri = raw_input("Enter logo_uri or just return: ") client_id = rndstr(12) while client_id in self.cdb: client_id = rndstr(12) client_secret = secret(self.seed, client_id) info = { "client_secret": client_secret, "client_id": client_id, "redirect_uris": pack_redirect_uri(redirect_uris), } if policy_uri: info["policy_uri"] = policy_uri if logo_uri: info["logo_uri"] = logo_uri self.cdb[client_id] = info return self.cdb[client_id]
def get_request_args(self, client, acr_value, session): """ :param client: Client instance :param acr_value: Authentication Context reference :param session: Session information :return: A set of Authorization request arguments """ request_args = { "response_type": self.flow_type, "scope": self.pool_config["scope"], "state": client.state, } if acr_value: request_args["acr_values"] = [acr_value] if self.flow_type == "token": request_args["nonce"] = rndstr(16) session["nonce"] = request_args["nonce"] else: use_nonce = getattr(self, "use_nonce", None) if use_nonce: request_args["nonce"] = rndstr(16) session["nonce"] = request_args["nonce"] logger.info("client args: %s" % list(client.__dict__.items()), ) logger.info("request_args: %s" % (request_args, )) return client, request_args
def login(remote_user=None, **kwargs): oidc = auth.OIDC() flask.session['remote_user'] = None flask.session['state'] = rndstr() flask.session['nonce'] = rndstr() return flask.render_template('login.html', remote_user=remote_user, openid_url=oidc.get_login_uri(flask.session['state'], flask.session['nonce']))
def srv(): class Bunch(dict): def __init__(self, **kw): dict.__init__(self, kw) self.__dict__ = self return Bunch(symkey=rndstr(), seed=rndstr().encode("utf-8"), iv=os.urandom(16), cookie_name="xyzxyz")
def __init__(self, conv, io, sh, **kwargs): super(AsyncAuthn, self).__init__(conv, io, sh, **kwargs) self.op_args["endpoint"] = conv.entity.provider_info[ "authorization_endpoint"] conv.state = rndstr() self.req_args["state"] = conv.state conv.nonce = rndstr() self.req_args["nonce"] = conv.nonce
def construct_AuthorizationRequest(self, request=AuthorizationRequest, request_args=None, extra_args=None, request_param=None, **kwargs): if request_args is not None: # if "claims" in request_args: # kwargs["claims"] = request_args["claims"] # del request_args["claims"] if "nonce" not in request_args: _rt = request_args["response_type"] if "token" in _rt or "id_token" in _rt: request_args["nonce"] = rndstr(12) elif "response_type" in kwargs: if "token" in kwargs["response_type"]: request_args = {"nonce": rndstr(12)} else: # Never wrong to specify a nonce request_args = {"nonce": rndstr(12)} if "request_method" in kwargs: if kwargs["request_method"] == "file": request_param = "request_uri" del kwargs["request_method"] areq = oauth2.Client.construct_AuthorizationRequest( self, request, request_args, extra_args, **kwargs) if request_param: alg = self.behaviour["require_signed_request_object"] if "algorithm" not in kwargs: kwargs["algorithm"] = alg if "keys" not in kwargs and alg: atype = alg2keytype(alg) kwargs["keys"] = self.keyjar.get_signing_key(atype) _req = make_openid_request(areq, **kwargs) if request_param == "request": areq["request"] = _req else: _filedir = kwargs["local_dir"] _webpath = kwargs["base_path"] _name = rndstr(10) filename = os.path.join(_filedir, _name) while os.path.exists(filename): _name = rndstr(10) filename = os.path.join(_filedir, _name) fid = open(filename, mode="w") fid.write(_req) fid.close() _webname = "%s%s" % (_webpath, _name) areq["request_uri"] = _webname return areq
def __init__(self, conv, session, test_id, conf, funcs): Request.__init__(self, conv, session, test_id, conf, funcs) self.op_args["endpoint"] = conv.client.provider_info[ "authorization_endpoint"] conv.state = rndstr() self.req_args["state"] = conv.state conv.nonce = rndstr() self.req_args["nonce"] = conv.nonce
def __init__(self, conv, io, sh, **kwargs): super(SyncAuthn, self).__init__(conv, io, sh, **kwargs) self.op_args["endpoint"] = conv.entity.provider_info[ "authorization_endpoint"] conv.state = rndstr() self.req_args["state"] = conv.state conv.nonce = rndstr() self.req_args["nonce"] = conv.nonce # verify that I've got a valid access code self.tests["post"].append("valid_code")
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 registration_endpoint(self, environ, start_response, **kwargs): logger.debug("@registration_endpoint") try: query = kwargs["query"] except KeyError: try: query = get_or_post(environ) except UnsupportedMethod: resp = BadRequest("Unsupported method") return resp(environ, start_response) request = RegistrationRequest().deserialize(query, "urlencoded") logger.info("registration_request:%s" % request.to_dict()) _keystore = self.server.keystore if request["type"] == "client_associate": # create new id och secret client_id = rndstr(12) while client_id in self.cdb: client_id = rndstr(12) client_secret = secret(self.seed, client_id) self.cdb[client_id] = { "client_secret":client_secret } _cinfo = self.cdb[client_id] if "redirect_uris" in request: for uri in request["redirect_uris"]: if urlparse.urlparse(uri).fragment: err = ClientRegistrationErrorResponse( error="invalid_configuration_parameter", error_description="redirect_uri contains fragment") resp = Response(err.to_json(), content="application/json", status="400 Bad Request") return resp(environ, start_response) for key,val in request.items(): _cinfo[key] = val try: self.keystore.load_keys(request, client_id) except Exception, err: logger.error("Failed to load client keys: %s" % request.to_dict()) err = ClientRegistrationErrorResponse( error="invalid_configuration_parameter", error_description="%s" % err) resp = Response(err.to_json(), content="application/json", status="400 Bad Request") return resp(environ, start_response) response = RegistrationResponseCARS(client_id=client_id)
def authenticate(self, session): request_args = IMPLICIT_FLOW session["state"] = rndstr() session["nonce"] = rndstr() request_args["state"] = session["state"] request_args["nonce"] = session["nonce"] auth_req = self.client.construct_AuthorizationRequest(request_args=request_args) login_url = auth_req.request(self.client.authorization_endpoint) return login_url
def construct_AuthorizationRequest(self, request=AuthorizationRequest, request_args=None, extra_args=None, **kwargs): if request_args is not None: if "nonce" not in request_args: request_args["nonce"] = rndstr(12) else: request_args = {"nonce": rndstr(12)} return oauth2.Client.construct_AuthorizationRequest(self, request, request_args, extra_args, **kwargs)
def authenticate(self, session): request_args = IMPLICIT_FLOW session["state"] = rndstr() session["nonce"] = rndstr() request_args["state"] = session["state"] request_args["nonce"] = session["nonce"] auth_req = self.client.construct_AuthorizationRequest( request_args=request_args) login_url = auth_req.request(self.client.authorization_endpoint) return login_url
def get(self): provider_url = self.authenticator.oidc_provider_url redirect_uri = self.authenticator.oidc_callback_url self.log.info('oidc redirect: %r', redirect_uri) response_type = ['code'] oclient = self.authenticator.oclient issuer_url = oclient.wf.discovery_query(provider_url) #issuer_url = provider_url self.log.info('issuer_url: %r', issuer_url) provider_info = oclient.provider_config(issuer_url) response_types = ["code", "id_token", "token"] response_types = ["code"] behaviour = { "scope": ["openid", "profile"], "acr_values": ["password"] } args = { "redirect_uris": [redirect_uri], "response_types": response_types } registration_endpoint = provider_info.to_dict().get("registration_endpoint", None) if registration_endpoint is not None: registration_response = oclient.register(provider_info["registration_endpoint"], **args) print("registration_response: %s" % registration_response) else: oclient.client_id = self.authenticator.client_id oclient.client_secret = self.authenticator.client_secret state = rndstr() nonce = rndstr() self.set_cookie("oidc_state", state) self.set_cookie("oidc_nonce", nonce) request_args = { "response_type": "code", "state": state, "nonce": nonce, "redirect_uri": redirect_uri, "client_id": oclient.client_id } request_args.update(behaviour) auth_req = oclient.construct_AuthorizationRequest(request_args=request_args) login_url = auth_req.request(oclient.authorization_endpoint) print("login_url:{}".format(login_url)) self.redirect(login_url)
def __call__(self, conv, **kwargs): _id = rndstr(16) try: conv.cache[_id] = conv except KeyError: conv.cache = {_id: conv} return _id
def test_complete_secret_auth(): consumer = Consumer(SessionDB(), CONFIG, CLIENT_CONFIG, SERVER_INFO) mfos = MyFakeOICServer("http://localhost:8088") mfos.keyjar = SRVKEYS consumer.http_request = mfos.http_request consumer.redirect_uris = ["http://example.com/authz"] consumer.state = "state0" consumer.nonce = rndstr() consumer.client_secret = "hemlig" consumer.secret_type = "basic" del consumer.config["password"] args = { "client_id": consumer.client_id, "response_type": "code", "scope": ["openid"], } result = consumer.do_authorization_request(state=consumer.state, request_args=args) assert result.status_code == 302 assert result.headers["location"].startswith(consumer.redirect_uris[0]) _, query = result.headers["location"].split("?") consumer.parse_response(AuthorizationResponse, info=query, sformat="urlencoded") resp = consumer.complete() print resp assert resp.type() == "AccessTokenResponse" print resp.keys() assert _eq(resp.keys(), ['token_type', 'state', 'access_token', 'scope', 'expires_in', 'refresh_token']) assert resp["state"] == consumer.state
def init_client(self, session, key): """ Instantiate a client to talk to the AS :param session: :param key: :return: client instance """ logger.debug("FLOW type: %s" % self.flow_type) if self.baseurl.endswith("/"): callback = self.baseurl + key else: callback = "%s/%s" % (self.baseurl, key) try: _ = self.pool_config["client"][key]["client_id"] client = self.static(callback, key) except KeyError: client = self.dynamic(callback, session, key) try: client.state = session["state"] except KeyError: client.state = session["state"] = rndstr() return client
def init_srv(self, srv): if srv: self.srv = srv for param in ["seed", "iv"]: if not getattr(srv, param, None): setattr(srv, param, rndstr().encode("utf-8"))
def _distributed(self, info): # store the user info so it can be accessed later access_token = rndstr() self.info_store[access_token] = info return UserClaimsResponse(endpoint=self.claims_userinfo_endpoint, access_token=access_token, claims_names=info.keys())
def assertion_jwt(cli, keys, audience, algorithm): _now = time.time() at = AuthnToken(iss=cli.client_id, sub=cli.client_id, aud=audience, jti=rndstr(8), exp=_now + 600, iat=_now) return at.to_jwt(key=keys, algorithm=algorithm)
def _distributed(self, info): # store the user info so it can be accessed later access_token = rndstr() self.info_store[access_token] = info return UserClaimsResponse( endpoint=self.claims_userinfo_endpoint, access_token=access_token, claims_names=info.keys() )
def __init__(self, name, sdb, cdb, authn, authz, client_authn, symkey="", urlmap=None, iv=0, default_scope=""): self.name = name self.sdb = sdb self.cdb = cdb self.srvmethod = SrvMethod() self.authn = authn if authn: self.authn.srv = self self.authz = authz self.client_authn = client_authn self.symkey = symkey self.seed = rndstr() self.iv = iv or os.urandom(16) self.cookie_name = "pyoidc" self.default_scope = default_scope if urlmap is None: self.urlmap = {} else: self.urlmap = urlmap self.response_type_map = { "code": code_response, "token": token_response, "none": none_response, }
def authorization_request(request): client = Client() hapax = rndstr() state = rndstr() params = { "authorization_endpoint": WSO2IS__AUTHORIZATIONENDPOINT, "client_id": CLIENT__OAUTH2KEY, "response_type": "code", "scope": ["openid"], "nonce": hapax, "redirect_uri": CLIENT__REDIRECTURL, } result = client.do_authorization_request(state=state, request_args=params) logger.debug(" auth (1) %s" % (state)) request.session["state"] = state return HttpResponseRedirect(result.headers["location"])
def test_stateID(): seed = rndstr() sid0 = stateID("http://example.com/home", seed) sid1 = stateID("http://example.com/home", seed) assert sid0 assert sid1 assert sid0 != sid1
def assertion_jwt(cli, keys, audience, algorithm, lifetime=600): _now = utc_time_sans_frac() at = AuthnToken(iss=cli.client_id, sub=cli.client_id, aud=audience, jti=rndstr(16), exp=_now + lifetime, iat=_now) return at.to_jwt(key=keys, algorithm=algorithm)
def pedir_autorizacion(request): cliente = Client() hapax = rndstr() estado = rndstr() parametros = { "authorization_endpoint": endpoint_autorizacion, "client_id": llave, "response_type": "code", "scope": ["openid"], "nonce": hapax, "redirect_uri": callback } resultado = cliente.do_authorization_request(state=estado, request_args=parametros) request.session['estado'] = estado return HttpResponseRedirect(resultado.headers['location'])
def test_provider_authenticated_token(): provider = Provider("pyoicserv", sdb.SessionDB(), CDB, AUTHN_BROKER, AUTHZ, verify_client, symkey=rndstr(16)) _session_db = {} cons = Consumer(_session_db, client_config=CLIENT_CONFIG, server_info=SERVER_INFO, **CONSUMER_CONFIG) cons.debug = True location = cons.begin("http://localhost:8087", "http://localhost:8088/authorization", "token") QUERY_STRING = location.split("?")[1] resp = provider.authorization_endpoint(QUERY_STRING) print resp.headers print resp.message txt = resp.message assert "access_token=" in txt assert "token_type=Bearer" in txt
def assertion_jwt(cli, keys, audience, algorithm): _now = utc_now() at = AuthnToken(iss = cli.client_id, sub = cli.client_id, aud = audience, jti = rndstr(8), exp = _now+600, iat = _now) return at.to_jwt(key=keys, algorithm=algorithm)
def test_provider_authenticated(): provider = Provider("pyoicserv", sdb.SessionDB(), CDB, AUTHN_BROKER, AUTHZ, verify_client, symkey=rndstr(16)) _session_db = {} cons = Consumer(_session_db, client_config=CLIENT_CONFIG, server_info=SERVER_INFO, **CONSUMER_CONFIG) cons.debug = True location = cons.begin("http://localhost:8087", "http://localhost:8088/authorization") query_string = location.split("?")[1] resp = provider.authorization_endpoint(query_string) assert resp.status == "302 Found" print resp.headers print resp.message if content_type(resp.headers) == "json": resp = resp.message else: resp = resp.message.split("?")[1] aresp = cons.handle_authorization_response(query=resp) print aresp.keys() assert aresp.type() == "AuthorizationResponse" assert _eq(aresp.keys(), ['state', 'code']) print cons.grant[cons.state].keys() assert _eq(cons.grant[cons.state].keys(), ['tokens', 'code', 'exp_in', 'seed', 'id_token', 'grant_expiration_time'])
def test_token_endpoint_unauth(): provider = Provider("pyoicserv", sdb.SessionDB(), CDB, AUTHN_BROKER, AUTHZ, verify_client, symkey=rndstr(16)) authreq = AuthorizationRequest(state="state", redirect_uri="http://example.com/authz", client_id="client1") _sdb = provider.sdb sid = _sdb.token.key(user="******", areq=authreq) access_grant = _sdb.token(sid=sid) _sdb[sid] = { "oauth_state": "authz", "user_id": "user_id", "authzreq": "", "client_id": "client1", "code": access_grant, "code_used": False, "redirect_uri": "http://example.com/authz" } # Construct Access token request areq = AccessTokenRequest(code=access_grant, redirect_uri="http://example.com/authz", client_id="client2", client_secret="hemlighet",) print areq.to_dict() resp = provider.token_endpoint(request=areq.to_urlencoded()) print resp.message atr = TokenErrorResponse().deserialize(resp.message, "json") print atr.keys() assert _eq(atr.keys(), ['error_description', 'error'])
def test_faulty_idtoken_from_accesstoken_endpoint(): consumer = Consumer(SessionDB(SERVER_INFO["issuer"]), CONFIG, CLIENT_CONFIG, SERVER_INFO) consumer.keyjar = CLIKEYS mfos = MITMServer("http://localhost:8088") mfos.keyjar = SRVKEYS consumer.http_request = mfos.http_request consumer.redirect_uris = ["http://example.com/authz"] _state = "state0" consumer.nonce = rndstr() consumer.client_secret = "hemlig" consumer.secret_type = "basic" consumer.config["response_type"] = ["id_token"] args = { "client_id": consumer.client_id, "response_type": consumer.config["response_type"], "scope": ["openid"], } result = consumer.do_authorization_request(state=_state, request_args=args) consumer._backup("state0") assert result.status_code == 302 # assert result.location.startswith(consumer.redirect_uri[0]) _, query = result.headers["location"].split("?") print query try: consumer.parse_authz(query=query) except BadSignature: pass else: assert False
def __init__(self, client, config, trace, interaction, check_factory=None, msg_factory=None, features=None, verbose=False, expect_exception=None, **extra_args): self.entity = client self.entity_config = config self.trace = trace self.features = features self.verbose = verbose self.check_factory = check_factory self.msg_factory = msg_factory self.expect_exception = expect_exception self.extra_args = extra_args self.cjar = {"browser": http.cookiejar.MozillaCookieJar(), "rp": http.cookiejar.MozillaCookieJar(), "service": http.cookiejar.MozillaCookieJar()} self.events = Events() self.interaction = Interaction(self.entity, interaction) self.exception = None self.provider_info = self.entity.provider_info or {} self.interact_done = [] self.ignore_check = [] self.login_page = "" self.sequence = {} self.flow_index = 0 self.request_args = {} self.args = {} self.creq = None self.cresp = None self.req = None self.request_spec = None self.last_url = "" self.state = rndstr()
def test_userinfo(): consumer = Consumer(SessionDB(SERVER_INFO["issuer"]), CONFIG, CLIENT_CONFIG, SERVER_INFO) consumer.keyjar = CLIKEYS mfos = MyFakeOICServer("http://localhost:8088") mfos.keyjar = SRVKEYS consumer.http_request = mfos.http_request consumer.redirect_uris = ["http://example.com/authz"] _state = "state0" consumer.nonce = rndstr() consumer.secret_type = "basic" consumer.set_client_secret("hemligt") consumer.keyjar = CLIKEYS args = { "client_id": consumer.client_id, "response_type": "code", "scope": ["openid"], } result = consumer.do_authorization_request(state=_state, request_args=args) assert result.status_code == 302 assert result.headers["location"].startswith(consumer.redirect_uris[0]) _, query = result.headers["location"].split("?") consumer.parse_response(AuthorizationResponse, info=query, sformat="urlencoded") consumer.complete(_state) result = consumer.get_user_info(_state) print result assert result.type() == "OpenIDSchema" assert _eq(result.keys(), ['name', 'email', 'verified', 'nickname', 'sub'])
def test_parse_authz(self): mfos = MyFakeOICServer("http://localhost:8088") mfos.keyjar = SRVKEYS self.consumer.http_request = mfos.http_request _state = "state0" self.consumer.nonce = rndstr() args = { "client_id": self.consumer.client_id, "response_type": "code", "scope": ["openid"], } result = self.consumer.do_authorization_request(state=_state, request_args=args) print self.consumer.sdb["state0"].keys() part = self.consumer.parse_authz(query=result.headers["location"]) print part atr = part[0] assert part[1] is None assert part[2] is None assert atr.type() == "AuthorizationResponse" assert atr["state"] == _state assert "code" in atr
def make_authentication_request(self, session): session["state"] = rndstr() session["nonce"] = rndstr() request_args = { "response_type": self.response_type, "state": session["state"], "nonce": session["nonce"], "redirect_uri": self.redirect_uri } request_args.update(self.behaviour) auth_req = session["client"].construct_AuthorizationRequest( request_args=request_args) login_url = auth_req.request(session["client"].authorization_endpoint) raise cherrypy.HTTPRedirect(login_url, 303)
def registration_endpoint(self, data): try: req = self.parse_registration_request(data, "json") except ValueError: req = self.parse_registration_request(data) client_secret = rndstr() expires = utc_time_sans_frac() + self.registration_expires_in kwargs = {} if "client_id" not in req: client_id = rndstr(10) registration_access_token = rndstr(20) _client_info = req.to_dict() kwargs.update(_client_info) _client_info.update({ "client_secret": client_secret, "info": req.to_dict(), "expires": expires, "registration_access_token": registration_access_token, "registration_client_uri": "register_endpoint" }) self.client[client_id] = _client_info kwargs["registration_access_token"] = registration_access_token kwargs["registration_client_uri"] = "register_endpoint" try: del kwargs["operation"] except KeyError: pass else: client_id = req.client_id _cinfo = self.client[req.client_id] _cinfo["info"].update(req.to_dict()) _cinfo["client_secret"] = client_secret _cinfo["expires"] = expires resp = RegistrationResponse(client_id=client_id, client_secret=client_secret, client_secret_expires_at=expires, **kwargs) response = Response() response.headers = {"content-type": "application/json"} response.text = resp.to_json() return response
def create(self, redirect_uris=None, policy_uri="", logo_uri="", jwks_uri=""): if redirect_uris is None: print( 'Enter redirect_uris one at the time, end with a blank line: ') redirect_uris = [] while True: redirect_uri = input('?: ') if redirect_uri: redirect_uris.append(redirect_uri) else: break if not policy_uri: policy_uri = input("Enter policy_uri or just return: ") if not logo_uri: logo_uri = input("Enter logo_uri or just return: ") client_id = rndstr(12) while client_id in self.cdb.keys(): client_id = rndstr(12) client_secret = secret(self.seed, client_id) info = { "client_secret": client_secret, "client_id": client_id, "client_salt": rndstr(8), "redirect_uris": pack_redirect_uri(redirect_uris), } if policy_uri: info["policy_uri"] = policy_uri if logo_uri: info["logo_uri"] = logo_uri if jwks_uri: info['jwks_uri'] = jwks_uri self.cdb[client_id] = info return self.cdb[client_id]
def handle(self): provider = select_provider(self.client.form) client = self.init_oic(provider) redirect_uri = self.redirect_uri(provider) client.redirect_uris = [redirect_uri] client.state = rndstr() _nonce = rndstr() args = { #"client_id": client.client_id, "response_type": "code", "scope": self.scopes, "openid.realm": self.base + "?@action=openid_return", #"nonce": hmac.new(_nonce, digestmod=hashlib.sha224), "redirect_uri": client.redirect_uris[0] } auth_req = client.construct_AuthorizationRequest(request_args=args) login_url = auth_req.request(client.authorization_endpoint) raise Redirect, login_url
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 oidc_op_redirect(): if 'op' in request.args and request.args['op'] in __OP: client = __OP[request.args['op']]['client'] session['op'] = request.args['op'] session['state'] = rndstr() session['nonce'] = rndstr() args = { "client_id": client.client_id, "response_type": "code", "scope": ["openid", "email"], "nonce": session["nonce"], "redirect_uri": client.redirect_uris[0], "state": session["state"] } auth_req = client.construct_AuthorizationRequest(request_args=args) login_url = client.authorization_endpoint + "?" + auth_req.to_urlencoded( ) return redirect(login_url) return redirect(url_for('login'))