def permission_registration_endpoint_(self, entity, **kwargs): """ The endpoint URI at which the resource server registers a client-requested permission with the authorization server. This is a proposed permission waiting for the user to accept it. """ request = kwargs["request"] _ticket = rndstr(24) logging.debug("Registering permission request: %s" % request) resp = PermissionRegistrationResponse(ticket=_ticket) self.permission_requests.add_request(_ticket, request) return Created(resp.to_json(), content="application/json")
def permission_registration_endpoint_(self, request="", requestor="", client_id="", **kwargs): """ The endpoint URI at which the resource server registers a client-requested permission with the authorization server. This is a proposed permission waiting for the user to accept it. """ _ticket = rndstr(24) logging.debug("Registering permission request: %s" % request) resp = PermissionRegistrationResponse(ticket=_ticket) self.permit.add_request(requestor, _ticket, request) return Created(resp.to_json(), content="application/json")
def get_info(self, requester, path, state=""): """ :param requester: requester """ resp = self.rs_query(requester, path) self.trace.append(trace("rs_query", "C<--RS", response=resp)) if resp.status_code == 200: return Response(resp.text) if resp.status_code == 401: # No RPT as_uri = resp.headers["as_uri"] if as_uri == self.baseurl: # It's me as it should be, means get a RPT from myself self.get_aat(requester) self.get_rpt(requester) return self.get_info(requester, path, state) else: return R2C[500]("Wrong AS") if resp.status_code == 403: # Permission registered, got ticket prr = PermissionRegistrationResponse().from_json(resp.text) kwargs = self.client.create_authorization_data_request( requester, prr["ticket"]) resp = self.authorization_request_endpoint( kwargs["data"], kwargs["headers"]["Authorization"]) self.trace.append( trace("*authorization_request", "C<--AS", response=resp)) if resp.status == "200 OK": return self.get_info(requester, path) raise UMAError()
def register_permission(self, resp, requester): prr = PermissionRegistrationResponse().from_json(resp.text) kwargs = self.client.create_authorization_data_request( requester, prr["ticket"]) pre_trace("C-->AS", "authorization_request", **kwargs) resp = self.srv.authorization_request_endpoint( kwargs["data"], authn=kwargs["headers"]["Authorization"]) post_trace("C<--AS", **repack_response(resp)) return resp
def permission_registration_endpoint_(self, request, **kwargs): """ The endpoint URI at which the resource server registers a client-requested permission with the authorization server. This is a proposed permission waiting for the user to accept it. :param request: The permission registration request :return: HTTP Response """ adb = self.get_adb(kwargs['client_id']) prr = self.to_prr(request, kwargs['client_id']) if prr: _ticket = adb.ticket_factory.pack(aud=[kwargs['client_id']], type='ticket') logging.debug("Registering permission request: %s" % request) adb.permission_requests[_ticket] = prr resp = PermissionRegistrationResponse(ticket=_ticket) return Created(resp.to_json(), content="application/json") else: return BadRequest("Can't register permission for unknown resource")
def do_permission_request(self, prrs): pat = self.rs_handler.token['PAT'] kwargs = { "headers": {"Authorization": "Bearer %s" % pat}, "body": prrs} url = self.client.provider_info["rpt_endpoint"] resp = self.client.send(url, "POST", **kwargs) assert resp.status == "201 Created" return PermissionRegistrationResponse().from_json(resp.message)[ "ticket"]
def operation(self, resource, requestor, oper="GET", **kwargs): """ :param owner: user identifier :param requestor: The entity_id of the SP that requests the information :param attrs: which attributes to return param kwargs: extra keyword arguments """ try: state = kwargs["state"] except KeyError: state = rndstr() self.client.state[requestor] = state try: authn_method = kwargs["authn_method"] except: authn_method = "" resp = self.rs_query(resource, requestor, oper, **kwargs) if resp.status_code == 200: return Response(resp.text) if resp.status_code == 401: # No RPT as_uri = resp.headers["as_uri"] resp = self.client.acquire_grant(as_uri, "RPT", requestor, state, self.acr, authn_method) return resp # elif resp.status_code == 302: # which it should be # # redirect that are part of the grant code flow # headers = [(a, b) for a, b in resp.headers.items() # if a != "location"] # return Redirect(resp.headers["location"], headers=headers) # elif resp.status_code == 200: # ??? # return Response(resp.text) # else: # return R2C[resp.status_code](resp.text) if resp.status_code == 403: # Permission registered, got ticket if state == "403": # loop ? return {} prr = PermissionRegistrationResponse().from_json(resp.text) resp = self.client.authorization_data_request(requestor, prr["ticket"]) if resp.status_code in (200, 201): return self.operation(resource, requestor, oper, **kwargs) raise UMAError()
def get_info(self, user, requestor, attrs=None, state="", **kwargs): """ :param user: user identifier :param requestor: The entity_id of the SP that requests the information :param attrs: which attributes to return :param state: Where in the process am I """ # The real requestor is <user>@<sp_entity_id> user_and_sp = "%s@%s" % (user, requestor) resp = self.rs_query(user_and_sp, user, attrs) args = {} for attr in ["authn_method", "password"]: try: args[attr] = kwargs[attr] except KeyError: args[attr] = "" if resp.status_code == 200: return Response(resp.text) if resp.status_code == 401: # No RPT as_uri = resp.headers["as_uri"] return self.client.acquire_grant(as_uri, "RPT", user_and_sp, state, self.acr, **args) #if isinstance(resp, Redirect): # which it should be # redirect that are part of the grant code flow # return resp # elif resp.status_code == 200: # ??? # return Response(resp.text) # else: # return R2C[resp.status_code](resp.text) if resp.status_code == 403: # Permission registered, got ticket if state == "403": # loop ? return {} prr = PermissionRegistrationResponse().from_json(resp.text) resp = self.client.authorization_data_request( user_and_sp, prr["ticket"]) if resp.status_code in (200, 201): return self.get_info(user, requestor, attrs, "403") raise UMAError()
# The RS on the other hand registers the necessary permission at the AS prrs = [] for rsid, scopes in pre_rpp: prrs.append( PermissionRegistrationRequest(resource_set_id=rsid, scopes=scopes).to_dict()) pat = ressrv.rs_handler.token['PAT'] resp = authzsrv.permission_registration_endpoint(json.dumps(prrs), 'Bearer {}'.format(pat)) assert resp.status == "201 Created" ticket = PermissionRegistrationResponse().from_json(resp.message)["ticket"] # ============================== 4 =========================================== # Crank up the client such that the relationship with the AS can be # settled. CLI_PORT = 8090 CLI_BASE = "https://localhost:%s" % CLI_PORT UMA_CLIENT = UMAUserInfo(CLI_BASE, ["%s/authz_cb" % CLI_BASE], "https://localhost:8089", acr="BasicAuthn") _uma_client = UMA_CLIENT.client # uma_pcr same as in (1) _uma_client.handle_provider_config(uma_pcr, authzsrv.baseurl, False, True)
ir = IntrospectionResponse().from_json(resp.message) assert ir["active"] is True assert "permissions" not in ir # The RS registers an Authorization request REQ_SCOPES = ["http://its.umu.se/uma/attr/displayName"] prr = PermissionRegistrationRequest(resource_set_id=_rsid, scopes=REQ_SCOPES) client, url, ht_args = ressrv.register_init( RESOURCE_OWNER, "permission_registration_endpoint", prr, _rsid) authninfo = ht_args["headers"]["Authorization"] permresp = authzsrv.permission_registration_endpoint(prr.to_json(), authninfo) created = PermissionRegistrationResponse().from_json(permresp.message) _, kwargs = _uma_client.create_authorization_data_request( USER, created["ticket"]) request = kwargs["data"] authn_info = kwargs["headers"]["Authorization"] res = authzsrv.authorization_request_endpoint(request, authn_info) assert res.status == "200 OK" # Now everything should be ready for accessing the resource # The resource server will do an introspection of the RPT _rpt = _uma_client.token[USER]["RPT"] pat = ressrv.permreg.get(RESOURCE_OWNER, "pat")["access_token"]
def application(environ, start_response): session = {} try: cookie = environ["HTTP_COOKIE"] try: _tmp = CookieHandler.get_cookie_value(cookie, COOKIE_NAME) except InvalidCookieSign: pass else: if _tmp: session = json.loads(_tmp[0]) except KeyError: pass path = environ.get('PATH_INFO', '').lstrip('/') logger.info("PATH: %s" % path) if session: logger.info("Session: %s" % (session,)) if path == "robots.txt": return static(environ, session, "static/robots.txt") elif path.startswith("static/"): return static(environ, session, path) try: query = parse_qs(environ["QUERY_STRING"]) except KeyError: query = None if query: logger.info("Query: %s" % (query,)) resp = None if path == "": #?user=<rs_uid> resp = opbyuid(environ, start_response) _val = {"uid": query["user"][0]} resp.headers.append(CookieHandler.create_cookie( json.dumps(_val), "uma_rs", cookie_name=COOKIE_NAME)) return resp(environ, start_response) elif path == "rp": # Authenticating the user and binding the RS to the AS link = acr = "" if "uid" in query: try: link = RES_SRV.find_srv_discovery_url( resource=query["uid"][0]) except requests.ConnectionError: resp = ServiceError("Webfinger lookup failed, connection error") return resp(environ, start_response) elif "url" in query: link = query["url"][0] if "acr_values" in query: acr = query["acr_values"][0] else: acr = query["uid"][0].split("@")[0] # The userid if link: RES_SRV.srv_discovery_url = link md5 = hashlib.md5() md5.update(link) opkey = base64.b16encode(md5.digest()) session["callback"] = True func = getattr(RES_SRV, "begin") return func(environ, start_response, session, opkey, acr_value=acr) else: resp = BadRequest() return resp(environ, start_response) elif path.startswith("info"): # Assume query of the form # info/<uid>/<bundle>[?attr=<attribute>[&attr=<attribute>]] or # info/<uid>[?attr=<attribute>[&attr=<attribute>]] owner = path[5:] try: res = RES_SRV.dataset_endpoint(path, owner, environ) except Unknown: resp = BadRequest("Unknown user: %s" % owner) return resp(environ, start_response) except UnknownAuthzSrv: resp = BadRequest("User have not registered an authz server") return resp(environ, start_response) except KeyError, err: resp = BadRequest("Missing info: %s" % err) return resp(environ, start_response) # either a ErrorResponse or a ResourceResponse er = ErrorResponse().from_json(res) try: er.verify() headers = [] for var in ["as_uri", "host_id", "error"]: try: headers.append((var, str(er[var]))) except KeyError: pass if "ticket" in er: prr = PermissionRegistrationResponse(ticket=er["ticket"]) resp = Forbidden(prr.to_json(), headers=headers, content="application/json") else: resp = Unauthorized(headers=headers) except MissingRequiredAttribute: rr = ResourceResponse().from_json(res) resp = Response(rr.to_json()) return resp(environ, start_response)