0

Assign Permissions to Role

by
Published 4 days ago

Add permissions to a role. Each permission needs a resource_server_identifier (API audience) and a permission_name.

Script auth0 Verified

The script

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

3
async function getManagementToken(auth: RT.Auth0): Promise<string> {
4
  const response = await fetch(`https://${auth.domain}/oauth/token`, {
5
    method: "POST",
6
    headers: { "Content-Type": "application/json" },
7
    body: JSON.stringify({
8
      grant_type: "client_credentials",
9
      client_id: auth.client_id,
10
      client_secret: auth.client_secret,
11
      audience: `https://${auth.domain}/api/v2/`,
12
    }),
13
  })
14
  if (!response.ok) {
15
    throw new Error(`${response.status} ${await response.text()}`)
16
  }
17
  const { access_token } = (await response.json()) as { access_token: string }
18
  return access_token
19
}
20
/**
21
 * Assign Permissions to Role
22
 * Add permissions to a role. Each permission needs a resource_server_identifier (API audience) and a permission_name.
23
 */
24
export async function main(
25
  auth: RT.Auth0,
26
  role_id: string,
27
  permissions: { resource_server_identifier: string; permission_name: string }[]
28
) {
29
  const token = await getManagementToken(auth)
30
  const url = new URL(
31
    `https://${auth.domain}/api/v2/roles/${role_id}/permissions`
32
  )
33

34
  const response = await fetch(url, {
35
    method: "POST",
36
    headers: {
37
      Authorization: `Bearer ${token}`,
38
      "Content-Type": "application/json",
39
      Accept: "application/json",
40
    },
41
    body: JSON.stringify({ permissions }),
42
  })
43

44
  if (!response.ok) {
45
    throw new Error(`${response.status} ${await response.text()}`)
46
  }
47

48
  if (response.status === 204) return { success: true }
49
  return await response.json()
50
}
51