Advantech

Roles & Activity API

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).

1. Authentication

Both APIs use credentials your service already has.

WayHeaderWhat it may do
The service's client ID / secretAuthorization: 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 tokenAuthorization: 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.

2. Roles

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.

  1. An SSO administrator or the service owner creates the first role in the console (service page, Roles), ticks "Can manage roles" and adds your administrators.
  2. From then on those people manage roles, permissions and members inside your own platform through the Roles API — no SSO administrator needed.
  3. At sign-in the user data you receive contains roles and permissions; decide what the user may do from them.

Using roles from the sign-in data

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.

Roles API

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 callWhat it does
GET /api/roles/meuser tokenThe signed-in user's roles, permissions and whether they can manage roles.
GET /api/rolesservice credentials or user tokenAll roles of this service (with member counts).
GET /api/roles/{key}service credentials or user tokenOne role.
GET /api/roles/{key}/membersservice credentials or user tokenA role's members (email, name, who added them, when).
GET /api/users/{email}/rolesservice credentials or user tokenSomeone's roles and permissions in this service (they need not have signed in).
POST /api/rolestoken of a user who can manage rolesCreate a role.
PUT /api/roles/{key}token of a user who can manage rolesChange a role (only the fields sent).
DELETE /api/roles/{key}token of a user who can manage rolesDelete a role and its members.
POST /api/roles/{key}/memberstoken of a user who can manage rolesAdd members (several at once, at most 500).
DELETE /api/roles/{key}/members/{email}token of a user who can manage rolesRemove a member.

Examples

# 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

Role object

FieldWhat it does
keyRole key: lower-case letters, digits, _ . - ; fixed once created; your code checks it.
name, descriptionDisplay name and description.
permissionsPermission strings; their meaning is up to your service (e.g. orders.read, reports:*).
manage_rolesWhen true, members may manage this service's roles and members through the Roles API.
member_count, created_at, updated_atMember count and creation / change time (unix seconds).

3. Activity log

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.

Event fields

FieldNeedWhat it does
userRequired*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.
typeRequiredEvent type, see the table below; your own types are fine too (lower-case letters, digits, _).
pathOptionalPage or API path, e.g. /aes, /api/v1/me/prefs/display.
actionOptionalShort description of what was done, e.g. the button label.
contentOptionalContent (up to 8000 characters), e.g. page title, query, exported file name.
method, statusOptionalHTTP method and status of an API call, e.g. PUT 200.
ai.question, ai.answer, ai.modelOptionalAI Q&A: the user's question (up to 16000 characters), the AI's answer (up to 60000), the model.
metaOptionalAny extra data (a JSON object, up to 16 KB), e.g. {"theme":"dark"}.
session_id, ip, user_agentOptionalSession id, the user's IP and browser (filled in by your server).
timeOptionalWhen: 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.

Event types

typeWhat 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).

Sending events

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/activity
import 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 resp
const 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" });

Logging AI questions and answers

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.

Automatic front-end tracking (page views, clicks)

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.

1. The web page

<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>

2. Your back end forwards

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 "", 204

Reading events back

GET /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
ParameterWhat it does
userone user (email)
typetype(s), comma-separated (ai,change)
qsearch in path, action, content and AI Q&A
from, todate range: YYYY-MM-DD (UTC, both days included) or RFC 3339
limit, cursor1–500 per page (default 100); cursor = the previous page's next

Statistics (for reports)

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 }, … ] }
ParameterWhat it does
group_byGroup by: day, hour (of the day, 0–23), type, user or path
from, to, type, user, qThe same filters as reading events
tzTime zone for day, hour and dates (IANA name, e.g. Asia/Taipei; default UTC)
limitAt 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.

4. Errors and limits

HTTP / errorMeaning
400 invalid_request / invalid_eventA bad field (the message names the event and field)
401 invalid_client / invalid_tokenWrong client ID / secret, or an invalid or expired access token
403 user_token_requiredChanging roles needs a user's access token; service credentials can only read
403 insufficient_roleThis user holds no role that can manage roles
404 not_foundNo such role or member
409 conflictThe role key already exists

Advantech Single Sign-On