+def saml2_register_sp(url, user, password, sp_name, sp_metadata):
+ s = requests.Session()
+
+ # Authenticate to the IdP
+ form_auth_url = '%s/login/form' % url.rstrip('/')
+ test_auth_url = '%s/login/testauth' % url.rstrip('/')
+ auth_data = {'login_name': user,
+ 'login_password': password}
+
+ r = s.post(form_auth_url, data=auth_data)
+ if r.status_code == 404:
+ r = s.post(test_auth_url, data=auth_data)
+
+ if r.status_code != 200:
+ raise Exception('Unable to authenticate to IdP (%d)' % r.status_code)
+
+ # Add the SP
+ sp_url = '%s/rest/providers/saml2/SPS/%s' % (url.rstrip('/'), sp_name)
+ sp_headers = {'Content-type': 'application/x-www-form-urlencoded',
+ 'Referer': sp_url}
+ sp_data = urlencode({'metadata': sp_metadata})
+
+ r = s.post(sp_url, headers=sp_headers, data=sp_data)
+ if r.status_code != 201:
+ message = json.loads(r.text)['message']
+ raise Exception('%s' % message)
+
+