SAML-Toolkits / python3-saml

MIT License
699 stars 309 forks source link

Error while hitting process_response() #416

Closed MehtaKajol closed 3 months ago

MehtaKajol commented 3 months ago

I am trying to authenticate my SAML request from Okta. This is my code:

`import base64 import json import re from urllib.parse import unquote, urlparse from onelogin.saml2.auth import OneLogin_Saml2_Auth, OneLogin_Saml2_Settings from onelogin.saml2.utils import OneLogin_Saml2_Utils from flask import Flask, request, redirect, make_response, session import urllib3

app = Flask(name)

def init_saml_auth(req): with open("settings.json", "r") as f: saml_settings = json.load(f) saml_settings_obj = OneLogin_Saml2_Settings( settings=saml_settings, custom_base_path=None ) auth = OneLogin_Saml2_Auth(req, old_settings=saml_settings_obj) return auth

def prepare_flask_request(request): url_data = urlparse(request.url) body = request.data.decode("utf-8") is_base64_encoded = request.headers.get("Content-Transfer-Encoding") == "base64"

if is_base64_encoded:
    body = base64.b64decode(body).decode("utf-8")

# Extract SAMLResponse from the body
match = re.search(r"SAMLResponse=([^&]+)", body)
if not match:
    raise ValueError("SAMLResponse not found in the body")

saml_response_base64 = match.group(1)
decoded_url = unquote(saml_response_base64)

req_data = {
    "https": "on" if request.scheme == "https" else "off",
    "http_host": request.host,
    "server_port": url_data.port or ("443" if request.scheme == "https" else "80"),
    "script_name": request.path,
    "get_data": request.args.copy(),
    "post_data": {"SAMLResponse": decoded_url},
    "query_string": request.query_string.decode("utf-8"),
}
print(req_data)
return req_data

@app.route("/acs", methods=["POST"]) def acs(): req = prepare_flask_request(request) auth = init_saml_auth(req) auth.process_response() errors = auth.get_errors() print(errors) if len(errors) == 0: if auth.is_authenticated(): session["samlUserdata"] = auth.get_attributes() return redirect("/") else: return "Not authenticated" else: return "Error when processing SAML Response: " + ", ".join(errors)

if name == "main": app.run(debug=True) `

Error: ['invalid_response'] Please guide, I am not sure if I am following it correctly

pitbulk commented 3 months ago

@MehtaKajol have you reviewed the Flask example provided in the toolkit?

If you want to know the reason for the "invalid_response", use this method:

 auth.get_last_error_reason()