0

Assign User to Application

by
Published 4 days ago

Assign a user to an application, with optional app-specific credentials and profile.

Script okta Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 5 days ago
1
//native
2

3
export type DynSelect_app_id = string
4

5
// Dropdown of the org's applications so users pick an app instead of typing its opaque ID.
6
export async function app_id(auth: RT.Okta) {
7
  const url = new URL(`${auth.org_url}/api/v1/apps`)
8
  url.searchParams.append("limit", "200")
9
  const response = await fetch(url, {
10
    headers: {
11
      Authorization: `SSWS ${auth.token}`,
12
      Accept: "application/json",
13
    },
14
  })
15
  if (!response.ok) {
16
    throw new Error(`${response.status} ${await response.text()}`)
17
  }
18
  const apps = (await response.json()) as {
19
    id: string
20
    label: string
21
    name: string
22
  }[]
23
  return apps.map((a) => ({
24
    value: a.id,
25
    label: a.label ? `${a.label} (${a.id})` : a.id,
26
  }))
27
}
28

29
/**
30
 * Assign User to Application
31
 * Assign a user to an application. Only `user_id` is required; optionally pass app-specific `credentials` (e.g. { userName }) and a `profile` of app-level attributes.
32
 */
33
export async function main(
34
  auth: RT.Okta,
35
  app_id: DynSelect_app_id,
36
  user_id: string,
37
  credentials: { [key: string]: any } | undefined,
38
  profile: { [key: string]: any } | undefined
39
) {
40
  const url = new URL(`${auth.org_url}/api/v1/apps/${app_id}/users`)
41

42
  const body: { [key: string]: any } = { id: user_id, scope: "USER" }
43
  if (credentials !== undefined) body.credentials = credentials
44
  if (profile !== undefined) body.profile = profile
45

46
  const response = await fetch(url, {
47
    method: "POST",
48
    headers: {
49
      Authorization: `SSWS ${auth.token}`,
50
      "Content-Type": "application/json",
51
      Accept: "application/json",
52
    },
53
    body: JSON.stringify(body),
54
  })
55

56
  if (!response.ok) {
57
    throw new Error(`${response.status} ${await response.text()}`)
58
  }
59

60
  return await response.json()
61
}
62