Roles & Activity API
Two features every service can use: roles (each service's own roles and permissions, kept by the SSO and handed to you at sign-in) and the activity log (send what users do on your platform to the SSO to search, follow and analyse it in one place — including what they asked an AI and what it answered).
Both APIs use credentials your service already has.
| Way | Header | What it may do |
|---|---|---|
| The service's client ID / secret | Authorization: Basic base64(client_id:client_secret) | Called by your server. Read roles; send and read any user's activity. Cannot change roles. |
| A user's access token | Authorization: Bearer <access_token> | The one /token gave you (the signed-in user, valid 1 hour). Read their own roles; send and read their own activity; change roles if they hold a role that can manage roles. |
Either way, only your own service's roles and activity are reachable. Keep the client secret and access tokens on your server.
Roles belong to your service: you choose the keys, names and permission lists; the SSO stores them, keeps track of who holds which role and tells you at sign-in.
The user data from /token and /userinfo carries roles (role keys) and permissions (the sorted, de-duplicated union of their roles' permissions); empty arrays when they hold no role.
{
"sub": "8d6e2f1a-…", "email": "john.chen@advantech.com", "name": "John Chen",
"roles": ["editor", "viewer"],
"permissions": ["orders.read", "orders.write", "reports:*"],
…
}
def require_permission(perm):
def wrap(view):
@functools.wraps(view)
def inner(*a, **kw):
user = session.get("user") # saved at sign-in (/auth/callback)
if not user or perm not in user.get("permissions", []):
abort(403)
return view(*a, **kw)
return inner
return wrap
@app.post("/orders")
@require_permission("orders.write")
def create_order(): ...const can = (perm) => (req, res, next) =>
req.session.user?.permissions?.includes(perm) ? next() : res.status(403).send("Forbidden");
app.post("/orders", can("orders.write"), createOrder);
// roles: req.session.user.roles.includes("admin")// at sign-in: add each permission as a claim
foreach (var p in user.GetProperty("permissions").EnumerateArray())
claims.Add(new Claim("permission", p.GetString()!));
foreach (var r in user.GetProperty("roles").EnumerateArray())
claims.Add(new Claim(ClaimTypes.Role, r.GetString()!));
// then
app.MapPost("/orders", CreateOrder).RequireAuthorization(p => p.RequireClaim("permission", "orders.write"));
// or [Authorize(Roles = "admin")]@SuppressWarnings("unchecked")
static boolean can(HttpSession session, String perm) {
Map<String, Object> user = (Map<String, Object>) session.getAttribute("user");
return user != null && ((List<String>) user.getOrDefault("permissions", List.of())).contains(perm);
}
@PostMapping("/orders")
ResponseEntity<?> create(HttpSession session) {
if (!can(session, "orders.write")) return ResponseEntity.status(403).build();
...
}func can(u map[string]any, perm string) bool {
list, _ := u["permissions"].([]any)
for _, p := range list {
if p == perm {
return true
}
}
return false
}
// if u := currentUser(w, r); u == nil || !can(u, "orders.write") { http.Error(w, "Forbidden", 403); return }function sso_can(string $perm): bool {
$u = sso_user();
return $u && in_array($perm, $u['permissions'] ?? [], true);
}
if (!sso_can('orders.write')) { http_response_code(403); exit('Forbidden'); }Roles are read at sign-in. If they change afterwards, call /userinfo or /api/roles/me to refresh, or have the user sign in again.
Build your platform's own role management. Reading works with the service credentials; changes need the access token of a user who holds a role with "manage roles" — the SSO checks it.
| API (https://sso.advantech.world…) | Who may call | What it does |
|---|---|---|
| GET /api/roles/me | user token | The signed-in user's roles, permissions and whether they can manage roles. |
| GET /api/roles | service credentials or user token | All roles of this service (with member counts). |
| GET /api/roles/{key} | service credentials or user token | One role. |
| GET /api/roles/{key}/members | service credentials or user token | A role's members (email, name, who added them, when). |
| GET /api/users/{email}/roles | service credentials or user token | Someone's roles and permissions in this service (they need not have signed in). |
| POST /api/roles | token of a user who can manage roles | Create a role. |
| PUT /api/roles/{key} | token of a user who can manage roles | Change a role (only the fields sent). |
| DELETE /api/roles/{key} | token of a user who can manage roles | Delete a role and its members. |
| POST /api/roles/{key}/members | token of a user who can manage roles | Add members (several at once, at most 500). |
| DELETE /api/roles/{key}/members/{email} | token of a user who can manage roles | Remove a member. |
# the signed-in user's roles (their access token from /token)
curl -H "Authorization: Bearer $ACCESS_TOKEN" https://sso.advantech.world/api/roles/me
→ { "email": "john.chen@advantech.com", "roles": ["editor"], "permissions": ["orders.read", "orders.write"], "can_manage_roles": false }
# create a role (the caller must hold a role with manage_roles)
curl -X POST -H "Authorization: Bearer $ACCESS_TOKEN" -H "Content-Type: application/json" \
-d '{"key":"editor","name":"Editor","description":"Can edit orders","permissions":["orders.read","orders.write"],"manage_roles":false}' \
https://sso.advantech.world/api/roles
→ 201 { "key": "editor", "name": "Editor", "permissions": ["orders.read", "orders.write"], "manage_roles": false, "member_count": 0, … }
# change only what you send
curl -X PUT -H "Authorization: Bearer $ACCESS_TOKEN" -H "Content-Type: application/json" \
-d '{"permissions":["orders.read","orders.write","reports:*"]}' https://sso.advantech.world/api/roles/editor
# add members (people who never signed in can be added)
curl -X POST -H "Authorization: Bearer $ACCESS_TOKEN" -H "Content-Type: application/json" \
-d '{"emails":["amy.wu@advantech.com","ken.huang@advantech.com"]}' https://sso.advantech.world/api/roles/editor/members
# remove a member
curl -X DELETE -H "Authorization: Bearer $ACCESS_TOKEN" https://sso.advantech.world/api/roles/editor/members/ken.huang@advantech.com
# from your server, without a user: read only
curl -u "svc_xxxxxxxx:CLIENT_SECRET" https://sso.advantech.world/api/users/amy.wu@advantech.com/roles
| Field | What it does |
|---|---|
| key | Role key: lower-case letters, digits, _ . - ; fixed once created; your code checks it. |
| name, description | Display name and description. |
| permissions | Permission strings; their meaning is up to your service (e.g. orders.read, reports:*). |
| manage_roles | When true, members may manage this service's roles and members through the Roles API. |
| member_count, created_at, updated_at | Member count and creation / change time (unix seconds). |
Send what users do on your platform to the SSO: page views, clicks, changes, AI questions (with the answers), queries, exports… In the SSO console (Activity) you search by user, service, type, time and text, export to Excel, and click a person to see their activity on every platform.
| Field | Need | What it does |
|---|---|---|
| user | Required* | The user's email (or user_id = sub from the sign-in data). With a user token it is always that user and this field is ignored. |
| type | Required | Event type, see the table below; your own types are fine too (lower-case letters, digits, _). |
| path | Optional | Page or API path, e.g. /aes, /api/v1/me/prefs/display. |
| action | Optional | Short description of what was done, e.g. the button label. |
| content | Optional | Content (up to 8000 characters), e.g. page title, query, exported file name. |
| method, status | Optional | HTTP method and status of an API call, e.g. PUT 200. |
| ai.question, ai.answer, ai.model | Optional | AI Q&A: the user's question (up to 16000 characters), the AI's answer (up to 60000), the model. |
| meta | Optional | Any extra data (a JSON object, up to 16 KB), e.g. {"theme":"dark"}. |
| session_id, ip, user_agent | Optional | Session id, the user's IP and browser (filled in by your server). |
| time | Optional | When: RFC 3339 or unix seconds / milliseconds; omitted = now. At most a year ago, never in the future. |
* user or user_id. Emails that never signed in to the SSO are fine.
| type | What it does |
|---|---|
| page_view | ▤ Page view — the user opened a page |
| click | ◉ Click — clicked a button or link |
| change | ✎ Change — changed data or settings (usually POST / PUT / DELETE) |
| ai | ✦ Ask AI — asked an AI, with its answer |
| query | ⌕ Query — query, search |
| export | ⇩ Export — export, download |
| login | → Sign-in — signed in to your platform |
| logout | ← Sign-out — signed out |
| error | ⚠ Error — an error happened |
| (your own) | Any other type you need, e.g. approve, upload (lower-case letters, digits, _; role_change is reserved for the SSO). |
POST /api/activity with one event, or {"events": [...]} with up to 500. Send from your server (never give the client secret to the browser) and never let a failure affect the user.
# one event
curl -u "svc_xxxxxxxx:CLIENT_SECRET" -H "Content-Type: application/json" \
-d '{"user":"john.chen@advantech.com","type":"page_view","path":"/aes","content":"AE 名冊"}' \
https://sso.advantech.world/api/activity
→ 201 { "accepted": 1, "ids": ["5c1d…"] }
# a batch (up to 500)
curl -u "svc_xxxxxxxx:CLIENT_SECRET" -H "Content-Type: application/json" -d '{"events":[
{"user":"john.chen@advantech.com","type":"click","path":"/aes","action":"切換服務"},
{"user":"john.chen@advantech.com","type":"change","path":"/api/v1/me/prefs/display","method":"PUT","status":200,"meta":{"theme":"dark"}}
]}' https://sso.advantech.world/api/activityimport os, requests
SSO = "https://sso.advantech.world"
AUTH = (os.environ["SSO_CLIENT_ID"], os.environ["SSO_CLIENT_SECRET"])
def log_activity(user_email, type_, **fields):
"""fields: path, action, content, method, status, ai={...}, meta={...}, session_id, ip, user_agent"""
try:
requests.post(SSO + "/api/activity", auth=AUTH, timeout=5,
json={"user": user_email, "type": type_, **fields})
except requests.RequestException:
pass # never let logging break the page
# Flask: log every request of a signed-in user
@app.after_request
def after(resp):
u = session.get("user")
if u and request.method != "GET":
log_activity(u["email"], "change", path=request.path, method=request.method,
status=resp.status_code, ip=request.remote_addr)
return respconst SSO = "https://sso.advantech.world";
const AUTH = "Basic " + Buffer.from(`${process.env.SSO_CLIENT_ID}:${process.env.SSO_CLIENT_SECRET}`).toString("base64");
export async function logActivity(user, type, fields = {}) {
try {
await fetch(`${SSO}/api/activity`, {
method: "POST", headers: { Authorization: AUTH, "Content-Type": "application/json" },
body: JSON.stringify({ user, type, ...fields }), signal: AbortSignal.timeout(5000),
});
} catch { /* never let logging break the page */ }
}
// Express: log changes of signed-in users
app.use((req, res, next) => {
res.on("finish", () => {
if (req.session.user && req.method !== "GET")
logActivity(req.session.user.email, "change", { path: req.path, method: req.method, status: res.statusCode, ip: req.ip });
});
next();
});var sso = new HttpClient { BaseAddress = new Uri("https://sso.advantech.world/") };
sso.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}")));
async Task LogActivity(string user, string type, object? fields = null)
{
var ev = new Dictionary<string, object?> { ["user"] = user, ["type"] = type };
if (fields != null)
foreach (var p in fields.GetType().GetProperties()) ev[p.Name] = p.GetValue(fields);
try { await sso.PostAsJsonAsync("api/activity", ev); } catch { /* never break the page */ }
}
await LogActivity("john.chen@advantech.com", "export", new { path = "/reports", content = "Q3 sales.xlsx" });Use type ai and put the question and answer in the ai object. The console shows "Show the AI Q&A" with the full text, and its search covers questions and answers.
# after your AI answered (Python)
answer = ask_ai(question)
log_activity(user["email"], "ai", path="/s/aisa", content="AISA",
ai={"question": question, "answer": answer, "model": "claude-sonnet"},
meta={"conversation_id": conv_id, "tokens": usage.total_tokens})
AI answers can be long and sensitive: the SSO keeps the full text you send; only SSO administrators and the service's owner can see it. Do not send what must not be kept.
Rather not send each event by hand? Add this script: it records page views (including single-page-app navigation) and clicks on elements with data-track, and sends them to your own back end every few seconds.
<script src="https://sso.advantech.world/assets/js/advantech-activity.js" data-endpoint="/activity" defer></script>
<!-- clicks: add data-track (what was clicked) -->
<button data-track="切換服務">…</button>
<a href="/export" data-track="匯出 Excel" data-track-type="export">…</a>
<script>
// by hand
AdvActivity.track("change", { action: "主題", content: "深色", meta: { theme: "dark" } });
AdvActivity.ai(question, answer, "claude-sonnet");
</script>
The script only talks to your own site (data-endpoint). Your back end adds the user from its own session and forwards with the service credentials. Always take the user from your session, never from the browser.
app.post("/activity", express.json({ limit: "1mb" }), async (req, res) => {
const user = req.session.user;
if (!user) return res.status(204).end(); // not signed in: drop
const events = (req.body.events || []).slice(0, 500).map((e) => ({
...e, user: user.email, // the user comes from YOUR session, never the browser
ip: req.ip, user_agent: req.get("user-agent"),
}));
await fetch("https://sso.advantech.world/api/activity", {
method: "POST", headers: { Authorization: AUTH, "Content-Type": "application/json" },
body: JSON.stringify({ events }),
}).catch(() => {});
res.status(204).end();
});@app.post("/activity")
def activity():
user = session.get("user")
if not user:
return "", 204
events = (request.get_json(silent=True) or {}).get("events", [])[:500]
for e in events:
e.update(user=user["email"], ip=request.remote_addr, user_agent=request.headers.get("User-Agent"))
try:
requests.post(SSO + "/api/activity", auth=AUTH, json={"events": events}, timeout=5)
except requests.RequestException:
pass
return "", 204GET /api/activity returns your service's events (newest first) for your own reports and analysis. With a user token you only get that user's events.
curl -u "svc_xxxxxxxx:CLIENT_SECRET" "https://sso.advantech.world/api/activity?user=john.chen@advantech.com&type=ai,change&from=2026-11-01&to=2026-11-30&limit=100"
→ { "events": [
{ "id": "…", "user": "john.chen@advantech.com", "user_id": "8d6e…", "type": "ai", "path": "/s/aisa", "content": "AISA",
"ai": { "question": "…", "answer": "…", "model": "claude-sonnet" }, "time": 1764051600 }, …
],
"next": "1764051600.5c1d…" } ← pass it as cursor for the next page
| Parameter | What it does |
|---|---|
| user | one user (email) |
| type | type(s), comma-separated (ai,change) |
| q | search in path, action, content and AI Q&A |
| from, to | date range: YYYY-MM-DD (UTC, both days included) or RFC 3339 |
| limit, cursor | 1–500 per page (default 100); cursor = the previous page's next |
GET /api/activity/stats returns aggregated numbers for your own dashboards and reports (people per day, who asks the AI most, the most used pages…). The SSO console (Activity → Dashboard) also downloads an Excel report.
# events per day in Taiwan time, last month
curl -u "svc_xxxxxxxx:CLIENT_SECRET" "https://sso.advantech.world/api/activity/stats?group_by=day&from=2026-11-01&to=2026-11-30&tz=Asia/Taipei"
→ { "group_by": "day", "tz": "Asia/Taipei",
"total": { "events": 2129, "users": 37, "ai": 214 },
"rows": [ { "key": "2026-11-01", "events": 63, "users": 12, "ai": 5, "last": 1761998340 }, … ] }
# the 20 most active users, AI questions only
curl -u "svc_xxxxxxxx:CLIENT_SECRET" "https://sso.advantech.world/api/activity/stats?group_by=user&type=ai&limit=20"
→ { "rows": [ { "key": "john.chen@advantech.com", "label": "John Chen", "events": 41, "users": 1, "ai": 41, "last": 1764051600 }, … ] }
| Parameter | What it does |
|---|---|
| group_by | Group by: day, hour (of the day, 0–23), type, user or path |
| from, to, type, user, q | The same filters as reading events |
| tz | Time zone for day, hour and dates (IANA name, e.g. Asia/Taipei; default UTC) |
| limit | At most this many groups for user, path, type (1–1000, default 100, by event count) |
Each row: key (date, hour, type, email or path), events, users (distinct), ai (of which AI questions), last (unix seconds); user rows also carry label (the name). With a user token only that user's events are counted.
Do not log passwords, tokens or personal data you do not need. Events are kept; ask the SSO administrator to remove data.
| HTTP / error | Meaning |
|---|---|
| 400 invalid_request / invalid_event | A bad field (the message names the event and field) |
| 401 invalid_client / invalid_token | Wrong client ID / secret, or an invalid or expired access token |
| 403 user_token_required | Changing roles needs a user's access token; service credentials can only read |
| 403 insufficient_role | This user holds no role that can manage roles |
| 404 not_found | No such role or member |
| 409 conflict | The role key already exists |
Advantech Single Sign-On