From b885a3286bea111dccaff6c0182bd80a6c347f92 Mon Sep 17 00:00:00 2001 From: Aurélien Bompard Date: Aug 09 2024 13:39:49 +0000 Subject: Support CORS pre-flight request in the OpenIDC endpoints Ref: https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request Signed-off-by: Aurélien Bompard --- diff --git a/ipsilon/providers/openidc/api.py b/ipsilon/providers/openidc/api.py index 0410027..44da553 100644 --- a/ipsilon/providers/openidc/api.py +++ b/ipsilon/providers/openidc/api.py @@ -92,6 +92,17 @@ class APIRequest(ProviderPageBase): if self.authenticate_token: self._authenticate_token(kwargs) + # Support pre-flight CORS requests: + # https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request + def OPTIONS(self, *args, **kwargs): + cherrypy.response.headers["Allow"] = "GET, POST" + cherrypy.response.headers["Access-Control-Allow-Methods"] = "GET, POST" + cherrypy.response.headers["Access-Control-Allow-Origin"] = "*" + if "Access-Control-Request-Headers" in cherrypy.serving.request.headers: + cherrypy.response.headers["Access-Control-Allow-Headers"] = "*" + cherrypy.response.status = 204 + return "" + def _respond(self, response): return json.dumps(response) diff --git a/tests/openidc.py b/tests/openidc.py index 24d4971..b508b1b 100755 --- a/tests/openidc.py +++ b/tests/openidc.py @@ -569,3 +569,33 @@ if __name__ == '__main__': raise Exception('Invalid token type returned') if 'access_token' not in anon_token: raise Exception('Did not get access token') + + with TC.case('Check CORS support'): + headers = { + "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "x-requested-with", + "Origin": "https://foobar.example.com", + } + r = requests.options('https://127.0.0.10:45080/idp1/openidc/Token', headers=headers) + if r.status_code != 204: + raise Exception('CORS OPTIONS request unsupported on Token') + assert "POST" in r.headers.get("Allow") + assert "POST" in r.headers.get("Access-Control-Allow-Methods") + assert r.headers.get("Access-Control-Allow-Origin") == "*" + assert r.headers.get("Access-Control-Allow-Headers") == "*" + + r = requests.options('https://127.0.0.10:45080/idp1/openidc/TokenInfo') + if r.status_code != 204: + raise Exception('CORS OPTIONS request unsupported on TokenInfo') + assert "POST" in r.headers.get("Allow") + assert "POST" in r.headers.get("Access-Control-Allow-Methods") + assert r.headers.get("Access-Control-Allow-Origin") == "*" + # This header is only present if "Access-Control-Request-Headers" was sent + assert "Access-Control-Allow-Headers" not in r.headers + + r = requests.options('https://127.0.0.10:45080/idp1/openidc/UserInfo') + if r.status_code != 204: + raise Exception('CORS OPTIONS request unsupported on UserInfo') + assert r.headers.get("Allow") == "GET, POST" + assert r.headers.get("Access-Control-Allow-Methods") == "GET, POST" + assert r.headers.get("Access-Control-Allow-Origin") == "*"