Bug description
I got an error when i want to add roles and users programmatically using Superset API. Here is my code.
import requests
import json
import os
# --- Configuration ---
# For security, use environment variables in production environments.
SUPERSET_URL = "http://127.0.0.1:8088"
ADMIN_USER = os.getenv("SUPERSET_ADMIN_USER", "admin")
ADMIN_PASSWORD = os.getenv("SUPERSET_ADMIN_PASSWORD", "admin")
# --- New Role & User Details ---
NEW_ROLE_NAME = "Financial Analyst"
NEW_ROLE_PERMISSIONS = ["can read on Dashboard", "can read on Chart"]
NEW_USER_USERNAME = "dina.finance"
NEW_USER_FIRSTNAME = "Dina"
NEW_USER_LASTNAME = "Putri"
NEW_USER_EMAIL = "dina.finance@example.com"
NEW_USER_PASSWORD = "SecureStrongPassword456!"
# Error handler function
def handle_error(response):
"""Prints error message from API response and exits."""
try:
error_details = response.json()
print(f"❌ Failed: Status {response.status_code} - {error_details.get('message', response.text)}")
except json.JSONDecodeError:
print(f"❌ Failed: Status {response.status_code} - {response.text}")
exit()
def main():
"""Main function to execute the process."""
access_token = None
# Use a session object for efficient multiple requests
session = requests.Session()
# 1. Login and get access token
print(f"🔑 Attempting to log in as '{ADMIN_USER}'...")
try:
login_payload = {
"username": ADMIN_USER,
"password": ADMIN_PASSWORD,
"provider": "db"
}
response = session.post(f"{SUPERSET_URL}/api/v1/security/login", json=login_payload, timeout=10)
if response.status_code != 200:
handle_error(response)
access_token = response.json().get("access_token")
if not access_token:
print("❌ Access token not found in response.")
exit()
print("✅ Successfully retrieved token.")
# Set Authorization header for subsequent requests
session.headers.update({"Authorization": f"Bearer {access_token}"})
except requests.exceptions.RequestException as e:
print(f"❌ Connection error during login: {e}")
exit()
# 2. Create or get Role
print(f"🛠️ Checking for role '{NEW_ROLE_NAME}'...")
role_id = None
role_payload = {"name": NEW_ROLE_NAME, "permissions": NEW_ROLE_PERMISSIONS}
try:
response = session.post(f"{SUPERSET_URL}/api/v1/security/roles/", json=role_payload)
if response.status_code == 201:
role_id = response.json()["result"]["id"]
print(f"✅ Role '{NEW_ROLE_NAME}' successfully created with ID: {role_id}")
elif response.status_code == 409:
print(f"ℹ️ Role '{NEW_ROLE_NAME}' already exists. Searching for ID...")
params = {"q": json.dumps({"filters": [{"col": "name", "opr": "eq", "value": NEW_ROLE_NAME}]})}
response_get = session.get(f"{SUPERSET_URL}/api/v1/security/roles/", params=params)
if response_get.status_code == 200 and response_get.json()["count"] > 0:
role_id = response_get.json()["result"][0]["id"]
print(f"✅ Role found with ID: {role_id}")
else:
print("❌ Failed to find ID for existing role.")
exit()
else:
handle_error(response)
except requests.exceptions.RequestException as e:
print(f"❌ Connection error while creating role: {e}")
exit()
# 3. Create new user
if role_id:
print(f"👤 Creating user '{NEW_USER_USERNAME}'...")
user_payload = {
"first_name": NEW_USER_FIRSTNAME,
"last_name": NEW_USER_LASTNAME,
"username": NEW_USER_USERNAME,
"email": NEW_USER_EMAIL,
"password": NEW_USER_PASSWORD,
"active": True,
"roles": [role_id]
}
try:
response = session.post(f"{SUPERSET_URL}/api/v1/security/users/", json=user_payload)
if response.status_code != 201:
handle_error(response)
print(f"✅ User '{NEW_USER_USERNAME}' successfully created.")
except requests.exceptions.RequestException as e:
print(f"❌ Connection error while creating user: {e}")
exit()
else:
print("❌ Cannot proceed with user creation because role ID was not found.")
print("\n🎉 Process Completed!")
if __name__ == "__main__":
main()
When i run python setup_superset.py
, it gives this output.
🔑 Attempting to log in as 'admin'...
✅ Successfully retrieved token.
🛠️ Checking for role 'Financial Analyst'...
❌ Failed: Status 404 - {"errors": [{"message": "404 Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.", "error_type": "GENERIC_BACKEND_ERROR", "level": "error", "extra": {"issue_codes": [{"code": 1011, "message": "Issue 1011 - Superset encountered an unexpected error."}]}}]}
I succeeded to get access token, but failed when try to access /api/v1/security/roles/
and /api/v1/security/users/
. I also try another API but it gives a same error message.
I'm using Superset 4.1.3 and i don't change the code (just docker compose)
Any solution about that?
Screenshots/recordings
No response
Superset version
4.1.3
Python version
3.11
Node version
18 or greater
Browser
Chrome
Additional context
No response
Checklist
- [x] I have searched Superset docs and Slack and didn't find a solution to my problem.
- [x] I have searched the GitHub issue tracker and didn't find a similar bug report.
- [x] I have checked Superset's logs for errors and if I found a relevant Python stacktrace, I included it here as text in the "additional context" section.
Comment From: dosubot[bot]
The 404 errors happen because Superset 4.1.3 does not expose the /api/v1/security/roles/
or /api/v1/security/users/
endpoints—these APIs simply do not exist in this version, even if you try to enable them in superset_config.py
[discussion].
In Superset 4.1.3, user and role management is handled through the Superset UI or the CLI, not via REST API. For automation or scripting, you should use the CLI commands provided by Flask AppBuilder (FAB), which Superset uses under the hood. For example, you can create a user with:
superset fab create-user \
--username dina.finance \
--firstname Dina \
--lastname Putri \
--email dina.finance@example.com \
--password 'SecureStrongPassword456!' \
--role 'Financial Analyst'
You can also create roles and assign permissions using the FAB CLI, but fine-grained permission management still requires the UI or direct DB manipulation (which is not recommended or supported) [discussion].
If you need to manage users and roles via API, this is only supported in Superset 5.0.0+ with the FAB_ADD_SECURITY_API = True
setting [discussion]. Upgrading is the best path if API automation is a requirement.
To reply, just mention @dosu.
How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other
Comment From: msyavuz
Does this fix your issue @johannes-ws?
The 404 errors happen because Superset 4.1.3 does not expose the
/api/v1/security/roles/
or/api/v1/security/users/
endpoints—these APIs simply do not exist in this version, even if you try to enable them insuperset_config.py
[discussion].In Superset 4.1.3, user and role management is handled through the Superset UI or the CLI, not via REST API. For automation or scripting, you should use the CLI commands provided by Flask AppBuilder (FAB), which Superset uses under the hood. For example, you can create a user with:
superset fab create-user \ --username dina.finance \ --firstname Dina \ --lastname Putri \ --email dina.finance@example.com \ --password 'SecureStrongPassword456!' \ --role 'Financial Analyst'
You can also create roles and assign permissions using the FAB CLI, but fine-grained permission management still requires the UI or direct DB manipulation (which is not recommended or supported) [discussion].
If you need to manage users and roles via API, this is only supported in Superset 5.0.0+ with the
FAB_ADD_SECURITY_API = True
setting [discussion]. Upgrading is the best path if API automation is a requirement.
Comment From: johannes-ws
I got a new error. When i run docker compose for Superset 5.0.0, it gives an error message at address 127.0.0.1:8088.
{"errors": [{"message": "'NoneType' object has no attribute 'is_active'", "error_type": "GENERIC_BACKEND_ERROR", "level": "error", "extra": {"issue_codes": [{"code": 1011, "message": "Issue 1011 - Superset encountered an unexpected error."}]}}]}
What should i do?
Comment From: msyavuz
This looks like a session issue, either clearing the cache/cookies or restarting superset should fix it. Feel free to share backend logs if that doesn't help
Comment From: johannes-ws
superset_app | 2025-08-01 08:59:15,529:WARNING:superset.views.error_handling:Exception
superset_app | Traceback (most recent call last):
superset_app | File "/app/.venv/lib/python3.11/site-packages/flask/app.py", line 1484, in full_dispatch_request
superset_app | rv = self.dispatch_request()
superset_app | ^^^^^^^^^^^^^^^^^^^^^^^
superset_app | File "/app/.venv/lib/python3.11/site-packages/flask/app.py", line 1469, in dispatch_request
superset_app | return self.ensure_sync(self.view_functions[rule.endpoint])(view_args)
superset_app | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
superset_app | File "/app/superset/utils/log.py", line 304, in wrapper
superset_app | value = f(*args, kwargs)
superset_app | ^^^^^^^^^^^^^^^^^^
superset_app | File "/app/superset/views/core.py", line 897, in welcome
superset_app | if not g.user or not get_user_id():
superset_app | File "/app/.venv/lib/python3.11/site-packages/werkzeug/local.py", line 318, in get
superset_app | obj = instance._get_current_object()
superset_app | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
superset_app | File "/app/.venv/lib/python3.11/site-packages/werkzeug/local.py", line 526, in _get_current_object
superset_app | return get_name(local())
superset_app | ^^^^^^^
superset_app | File "/app/.venv/lib/python3.11/site-packages/flask_login/utils.py", line 25, in
I just add requirements-local.txt at ./docker/
which contains this code.
duckdb-engine==0.17.0
duckdb==1.3.2
flask_appbuilder==4.8.0
Then, i run docker compose. Any problem with my step?
Comment From: johannes-ws
After migration from Superset 4.1.3 to 5.0.0 and added FAB_ADD_SECURITY_API = True
to config.py
, i got a new error message.
🔑 Attempting to log in as 'admin'...
✅ Successfully retrieved token.
🛠️ Checking for role 'Financial Analyst'...
❌ Failed: Status 403 - Forbidden
Any solution about that? @dosu
Comment From: dosubot[bot]
The 403 Forbidden error means your admin user doesn't have the required permissions to access the roles API after migration. This is common after upgrading or enabling new APIs, because the permissions for the admin role may not be fully synced.
To fix this, run:
superset init
This will resync all roles and permissions, including the ones needed for the admin user to access the security APIs like /api/v1/security/roles/
reference. After running superset init
, restart your Superset server.
If you still get a 403, double-check that your admin user is assigned to the correct admin role (matching AUTH_ROLE_ADMIN
in your config), and that there are no custom security manager overrides or config differences affecting permissions reference.
This should resolve the permission issue and let you use the security API as intended.
To reply, just mention @dosu.
How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other