All pages
Powered by GitBook
1 of 11

Admin API

The Admin API allows your server to manage users via a GraphQL endpoint.

The Admin API allows your server to manage users via a GraphQL endpoint. You can list users, search users, view user details, and many more. In fact, the user management part of the portal is built with the Admin API.

The Admin API GraphQL endpoint

The Admin API GraphQL endpoint is at /_api/admin/graphql. For example, if your app is myapp , then the endpoint is https://myapp.authgear.cloud/_api/admin/graphql .

Authentication of the API endpoint

Accessing the Admin API GraphQL endpoint requires your server to generate a valid JWT and include it as Authorization HTTP header.

See Authentication and Security to learn how to access the Admin API securely.

API Explorer

If you want to explore what the Admin API can do, you can visit the GraphiQL tool. The GraphQL schema can also be found there.

  • Go to Advanced -> Admin API

  • Click on the GraphiQL tool link

  • Toggle the schema documentation by pressing the Docs button in the top left corner.

Explor the Admin API with GraphiQL tool from the Admin Portal

The GraphiQL tool is NOT a sandbox environment and all changes will be made on real, live, production data. Use with care!

API Schema

API Schema

API Examples

Admin API Examples

Authentication and Security

The Admin API is protected by cryptographic keys. Learn how to generate a valid JWT to authorize your request in this article.

Accessing the Admin API GraphQL endpoint

Accessing the Admin API GraphQL endpoint requires your server to generate a valid JWT and include it as Authorization HTTP header.

Obtaining the private key for signing JWT

  • Go to Advanced -> Admin API

  • Click Download to download the private key. Make it available to your server.

  • Copy the key ID. Make it available to your server.

Generating the JWT with the private key

Sample code to generate the JWT

Here is the sample code of how to generate the JWT with the private key.

package main

import (
	"encoding/json"
	"fmt"
	"os"
	"time"

	"github.com/lestrrat-go/jwx/v2/jwa"
	"github.com/lestrrat-go/jwx/v2/jwk"
	"github.com/lestrrat-go/jwx/v2/jws"
	"github.com/lestrrat-go/jwx/v2/jwt"
)

// Replace "myapp" with your project ID here.
// It is the first part of your Authgear endpoint.
// e.g. The project ID is "myapp" for "https://myapp.authgear.cloud"
const ProjectID = "myapp"

// Replace "mykid" with the key ID you see in the portal.
const KeyID = "mykid"

func main() {
	// Replace the following call with your own way to get the private key.
	f, err := os.Open("private-key.pem")
	if err != nil {
		panic(err)
	}
	defer f.Close()
	jwkSet, err := jwk.ParseReader(f, jwk.WithPEM(true))
	if err != nil {
		panic(err)
	}
	key, _ := jwkSet.Key(0)
	key.Set("kid", KeyID)

	now := time.Now().UTC()
	payload := jwt.New()
	_ = payload.Set(jwt.AudienceKey, ProjectID)
	_ = payload.Set(jwt.IssuedAtKey, now.Unix())
	_ = payload.Set(jwt.ExpirationKey, now.Add(5*time.Minute).Unix())

	// The alg MUST be RS256.
	alg := jwa.RS256
	hdr := jws.NewHeaders()
	hdr.Set("typ", "JWT")

	buf, err := json.Marshal(payload)
	if err != nil {
		panic(err)
	}

	token, err := jws.Sign(buf, jws.WithKey(alg, key, jws.WithProtectedHeaders(hdr)))
	if err != nil {
		panic(err)
	}

	fmt.Printf("%v\n", string(token))
}
import jwt
from datetime import datetime, timedelta

private_key = open("private-key.pem", "r").read()

# Replace "myapp" with your project ID here. 
# It is the first part of your Authgear endpoint. 
# e.g. The project ID is "myapp" for "https://myapp.authgear.cloud"
PROJECT_ID = "myapp"

# Replace "mykid" with the key ID you see in the portal.
KEY_ID = "mykid"

now = datetime.now()

payload = {
    "aud": [PROJECT_ID],
    "iat": int(now.timestamp()),
    "exp": int((now + timedelta(minutes=5)).timestamp()),
}

token = jwt.encode(
    payload,
    private_key,
    "RS256",
    headers={
        "kid": KEY_ID,
    },
)

print(token)

This example uses Express.js and the JsonWebToken package. So, first install both packages using the following commands:

npm install express

and

npm install jsonwebtoken

Here's the code for the Express.js app that generates the JWT:

const express = require("express");
const node_jwt = require('jsonwebtoken');
const fs = require('fs');
const app = express();
const port = 3002;

app.get('/', (request, response) => {
    // Your project ID is the first part of your Authgear endpoint. 
    // e.g. The project ID is "myapp" for "https://myapp.authgear.cloud"
    // You can find your key ID in the Portal.
    
    const project_id = ""; //Place your Authgear project id
    const key_id = ""; // Place your Authgear key ID
    const expiresAt = Math.floor(Date.now() / 1000) + (60 * 5); //the current value means token will expire in 5 minutes.
    
    //Payload to include in JWT
    const claims = {
        aud: project_id,
        iat: Math.floor(Date.now() / 1000),
        exp: expiresAt

    }

    const privateKey = fs.readFileSync("key.pem"); //Read value from the downloaded key file
    const header = {"typ": "JWT", "kid": key_id, "alg": "RS256"}
    const jwt = node_jwt.sign(claims, privateKey, { header: header });

    response.send("Generated JWT: " + jwt);
});

app.listen(port, () => {
    console.log("server started on port " + port);
});

First, install the Firebase PHP JWT package using this command:

composer require firebase/php-jwt

The PHP code for generating JWT:

<?php
require 'vendor/autoload.php';
use Firebase\JWT\JWT;

// Your project ID is the first part of your Authgear endpoint. 
// e.g. The project ID is "myapp" for "https://myapp.authgear.cloud"
// You can find your key ID in the Portal.

$project_id = ""; // Place your Authgear project id
$key_id = ""; // Place your Authgear key ID
$expiresAt = time() + (60*5); //the current value means token will expire in 5 minutes.

//Payload to include in JWT
$claims = [
    "aud" => $project_id,
    "iat" => time(),
    "exp" => $expiresAt
];

$privateKey = file_get_contents("./key.pem"); //Read value from the downloaded key file
$header = [
    "typ" => "JWT",
        "kid" => $key_id,
        "alg" => "RS256"
    ];
$jwt = JWT::encode($claims, $privateKey, "RS256", null, $header);

echo $jwt;

Example of the JWT header

{
  "alg": "RS256",
  "kid": "REPLACE_YOUR_KEY_ID_HERE",
  "typ": "JWT"
}

Example of the JWT payload

{
  "aud": [
    "REPLACE_YOUR_PROJECT_ID_HERE"
  ],
  "exp": 1136257445,
  "iat": 1136171045
}

Including the JWT in the HTTP request

After generating the JWT, you must include it in EVERY request you send to the Admin API endpoint. Here is how it looks like

Authorization: Bearer <JWT>

The header is the standard Authorization HTTP header. The token type MUST be Bearer.

Optional: Caching the JWT

As you can see in the sample code, you expiration time of the JWT is 5 minutes. You make it last longer and cache it to avoid generating it on every request.

Admin API Key rotation

You should regularly change the API key used to authenticate API requests. It enhances security by minimizing the impact of compromised keys.

To rotate the API key

  1. Go to Portal > Advanced > Admin API

  2. Under "List of Admin API keys", click "Generate new key pair"

  3. At this point both keys can be used to authenticate the admin API requests.

  4. Make sure all your systems is updated to use the new key

  5. Delete the old API key

API Schema

Specification overview

The Authgear Admin API follows GraphQL Cursor Connections Specification to handle pagination of results.

Read more about the Connection model to understand the types like "Edge", "Node", and "Cursor" in GraphQL Cursor Connections Specification.

Allowed Operations

Queries and mutations are allowed in the Admin API

Schema

Download the latest schema here:

📖 adminapi/schema.graphql

You can interactively access the same schema via the Explorer Doc sidebar

Admin API Examples

In this section of the Authgear documentation, you'll learn about all the GraphQL queries and mutations the Admin API supports.

Authgear provides a GraphQL API that you can use to manage users and other resources right from your application or using the GraphiQL Explorer in Authgear Portal > Advanced > Admin API.

The following section shows a detailed description and examples of supported queries and mutations.

1. Queries

1.1. auditLogs

The auditLogs query returns a list of all activities (logs) from the audit log.

Schema:

auditLogs(
first: Int
last: Int
userIDs: [ID!]
sortDirection: SortDirection
before: String
after: String
rangeFrom: DateTime
rangeTo: DateTime
activityTypes: [AuditLogActivityType!]
): AuditLogConnection

Example:

query {
  auditLogs(first: 4) {
    edges {
      node {
        id
        activityType
        createdAt
      }
    }
  }
}
{
  "data": {
    "auditLogs": {
      "edges": [
        {
          "node": {
            "activityType": "USER_AUTHENTICATED",
            "createdAt": "2023-09-11T09:23:51Z",
            "id": "QXVkaXRMb2c6MDAwMDAwMDAwMDA0ZDVjOQ"
          }
        }
      ]
    }
  }
}

1.2. users

You can use this query to fetch all registered users on your application. The users query returns a list of type User.

The users query depends on a search index. Hence, the data it returns is NOT immediately consistent as it requires reindexing before the most recent data and updates are included. If getting real-time user data is important for your use case, consider using the node /nodes or getUser/getUsers queries instead.

Schema:

users(
first: Int
last: Int
searchKeyword: String
sortBy: UserSortBy
sortDirection: SortDirection
before: String
after: String
): UserConnection

Example:

query {
  users(first: 2) {
    edges {
      node {
        id
        standardAttributes
      }
    }
  }
}
{
  "data": {
    "users": {
      "edges": [
        {
          "node": {
            "id": "VXNlcjo4ZGM4ZDgyjjkoKA0LTRjZGEtODZiOC03OTY4MGUwYzA5OGM",
            "standardAttributes": {
              "email": "myuser@gmail.com",
              "email_verified": true,
              "family_name": "John",
              "given_name": "Doe",
              "updated_at": 1686820949
            }
          }
        },
        {
          "node": {
            "id": "VXNlcjplMzA3OTAyaxKJuILTRjMjQtOTFjMS1jMmNkNjNhNmE0YWY",
            "standardAttributes": {
              "email": "user2@gmail.com",
              "email_verified": true,
              "family_name": "Eliano",
              "given_name": "Don",
              "updated_at": 1694359032
            }
          }
        }
      ]
    }
  }
}

1.3. node

A node represents a single object of different Types. The node query allows you to query a single object using the node ID. You learn more about node ID here: https://docs.authgear.com/reference/apis/admin-api/node-id.

Schema:

node(id: ID!): Node

Example:

You can specify different object types to the node query to fetch an item of that type. Examples of node Types include User, AuditLog, Session, Authenticator, Authorization, and Identity.

The following example uses the AuditLog node type.

query {
  node(id: "QXVkaXRMb2c6MDAwHJKwMDAwMDA0ZDViOQ") {
    id
    ... on AuditLog {
      id
      activityType
      createdAt
    }
  }
}
{
  "data": {
    "node": {
      "activityType": "USER_AUTHENTICATED",
      "createdAt": "2023-09-11T09:23:51Z",
      "id": "QXVkaXRMb2c6MDAwHJKwMDAwMDA0ZDViOQ"
    }
  }
}

1.4. nodes

The nodes query returns a list of nodes. This works similarly to the node query except that instead of supplying a single ID, you can provide a list of IDs for the objects you are querying for.

Schema:

nodes(ids: [ID!]!): [Node]!

Example:

query {
  nodes(ids: ["<NODE ID1>","<NODE ID2>"]) {
    id
    ... on AuditLog {
      id
      activityType
      createdAt
    }
  }
}
{
  "data": {
    "nodes": [
      {
        "activityType": "USER_AUTHENTICATED",
        "createdAt": "2023-09-11T09:23:51Z",
        "id": "QXKytXRMb4n6MDAwMDAwMDAwMDA0ZDVjUK"
      },
      {
        "activityType": "USER_PROFILE_UPDATED",
        "createdAt": "2023-09-14T06:57:27Z",
        "id": "QXVkaXABb7c6MDAwMDAwMDAwMDA0ZGKkZA"
      }
    ]
  }
}

1.5 groups

The groups query returns a list of all groups in an Authgear project. It will return nothing if no group has been created yet. Groups can be a field in the roles query.

Schema:

groups(
searchKeyword: String
excludedIDs: [ID!]
after: String
first: Int
last: Int
before: String
): GroupConnection

Example:

query {
  groups(first: 10) {
    edges {
      cursor
      node {
        id
        key
        description
      }
    }
  }
}
{
  "data": {
    "groups": {
      "edges": [
        {
          "cursor": "b2Zmc2V0OjA",
          "node": {
            "description": "Staff members with super admin permissions",
            "id": "R3JvdXA6OTU4YTA2ODIXRMb4n6MDAwMDAwMDAwMDA0ZDVjUKx",
            "key": "admin_staff"
          }
        },
        {
          "cursor": "b2Zmc2V0OjE",
          "node": {
            "description": "Group for quickly applying team_member role to batch users.",
            "id": "R3JvdXA6XRMb4n6MDAwMDAwMDAwMDA0ZDVjUKJl",
            "key": "regular_staff"
          }
        }
      ]
    }
  }
}

1.6 roles

You can use this query to get all the roles available in an Authgear project. The roles query will return nothing if no roles have been created for the Authgear project. Roles can also be a field in the node of the groups query. See Manage Users Roles and Groups to learn more about roles and groups.

Schema:

roles(
excludedIDs: [ID!]
last: Int
before: String
after: String
first: Int
searchKeyword: String
): RoleConnection

Example:

query {
  roles(first: 10) {
    edges {
      cursor
      node {
        id
        key
        description
        groups {
          edges{
            node {
              key
            }
          }
        }
      }
    }
  }
}
{
  "data": {
    "roles": {
      "edges": [
        {
          "cursor": "b2Zmc2V0OjA",
          "node": {
            "description": "Leads a specific department where they also work.",
            "groups": {
              "edges": []
            },
            "id": "Um9sZTozMjc5NWRiNhOTgtOTzMzZkZGNi1hOWVkLTE2MC0RlOWFkMTM",
            "key": "department_lead"
          }
        },
        {
          "cursor": "b2Zmc2V0OjE",
          "node": {
            "description": "Regular staff working in a specific department.",
            "groups": {
              "edges": [
                {
                  "node": {
                    "key": "regular_staff"
                  }
                }
              ]
            },
            "id": "Um9sZToyMjc5NWRiNhOTgtOTzMzZkZGNi1hOWVkLTE2MC0RlOWFkZTA",
            "key": "team_member"
          }
        }
      ]
    }
  }
}

1.7 getUser and getUsers Queries

The getUser and getUsers queries are a collection of Admin API queries for getting details about a single user or multiple users using specific attributes as the search key and in real-time. Unlike the users() query, the result from the getUser and getUsers queries is immediately consistent.

Learn more about all the queries in this collection here.

2. Mutations

With mutations, you can modify data from your application using the Admin API GraphQL. For example, you can use mutation to update

2.1. anonymizeUser

Calling this mutation will change a specific user account to an anonymous account. In other words, this query anonymizes a specific user. This action will delete the user's data like name and gender.

Schema:

anonymizeUser(input: AnonymizeUserInput!): AnonymizeUserPayload!

Example:

mutation {
  anonymizeUser(input: {userID: "<ENCODED USER ID>"}) {
    anonymizedUserID
  }
}
{
  "data": {
    "anonymizeUser": {
      "anonymizedUserID": "XYQlcjo4ZGM4ZDg5OC1jNjA0ERRjZGEtODZiOC134TY4MGUwYzA5OGM"
    }
  }
}

2.2. createIdentity

The createIdentity mutation creates a new identity for a user.

Schema:

createIdentity(input: CreateIdentityInput!): CreateIdentityPayload!

Example:

mutation {
  createIdentity(input: {userID: "<ENCODED USER ID>", definition: {loginID: {key: "email", value: "user@gmail.com"}}, password: "@x1ujD-9$"}) {
    identity {
      id
      claims
    }
  }
}
{
  "data": {
    "createIdentity": {
      "identity": {
        "claims": {
          "email": "user@gmail.com",
          "https://authgear.com/claims/login_id/key": "email",
          "https://authgear.com/claims/login_id/original_value": "user@gmail.com",
          "https://authgear.com/claims/login_id/type": "email",
          "https://authgear.com/claims/login_id/value": "user@gmail.com"
        },
        "id": "SWRlbnRpdHk6YjHiZGVhNjctABCwMy00OWU2LWIyOTMtNTIwMGU3KKUkMTBl"
      }
    }
  }
}

2.3. createUser

The createUser mutation makes it possible to create a new user account from the Admin API.

Schema:

createUser(input: CreateUserInput!): CreateUserPayload!

Example:

mutation {
  createUser(input: {definition: {loginID: {key: "email", value: "user@gmail.com"}}, password:"my$ecurepa55"}) {
    user{
      id
      standardAttributes
    }
  }
}
{
  "data": {
    "createUser": {
      "user": {
        "id": "VXNlciklODRkMzdjZi1hZDQ5LTRiZDItOTMzZJ2tOGY1YThlYjc34RE",
        "standardAttributes": {
          "email": "user@gmail.com",
          "email_verified": false,
          "updated_at": 1694713743
        }
      }
    }
  }
}

2.4. deleteAuthenticator

This mutation deletes an authenticator for a specific user.

Schema:

deleteAuthenticator(input: DeleteAuthenticatorInput!): DeleteAuthenticatorPayload!

Example:

mutation {
  deleteAuthenticator(input: {authenticatorID: "<ENCODED AUTHENTICATOR ID>"}) {
    user {
      authenticators {
        edges {
          node {
            id
          }
        }
      }
    }
  }
}
{
    "deleteAuthenticator": {
        "user": {
            "authenticators": {
                "edges": [
                    {
                        "node": {
                            "id": "QXV0aGVudGljYXRvcjpkGHczOGM0Yy0yNmY2LTQyOWMtODc0OS1kYTA3NjYxZjE0ABC"
                        }
                    }
                ]
            }
        }
    }
}

2.5. deleteAuthorization

You can use the deleteAuthorization mutation to delete an existing authorization for a user.

Schema:

deleteAuthorization(input: DeleteAuthorizationInput!): DeleteAuthorizationPayload!

Example:

mutation {
  deleteAuthorization(input: {authorizationID: "<ENCODED AUTHORIZATION ID>"}) {
    user {
      authorizations {
        edges {
          node {
            id
          }
        }
      }
    }
  }
}
{
    "deleteAuthorization": {
        "user": {
            "authorizations": {
                "edges": [
                    {
                        "node": {
                            "id": "QXV0aG9yaXphdGlvbjpkHFczOGM0Yy0yNmY2LTQyOWMtODc0OS1kYTA3NjYxZjE0EFG"
                        }
                    }
                ]
            }
        }
    }
}

2.6. deleteIdentity

The deleteIdentity mutation deletes the identity of a user.

Schema:

deleteIdentity(input: DeleteIdentityInput!): DeleteIdentityPayload!

Example:

mutation {
  deleteIdentity(
    input: {identityID: "<ENCODED IDENTITY ID>"}) {
    user {
      identities {
        edges {
          node {
            id
          }
        }
      }
    }
  }
}
{
  "data": {
    "deleteIdentity": {
      "user": {
        "identities": {
          "edges": [
            {
              "node": {
                "id": "SWRlbgsgdggGj7776JJkDc1My00ZTM2LWEyNTktZjg0ZjUyOER4NWJi"
              }
            }
          ]
        }
      }
    }
  }
}

2.7. deleteUser

This mutation allows you to delete a specific user using the Admin API.

Schema:

deleteUser(input: DeleteUserInput!): DeleteUserPayload!

Example:

mutation {
  deleteUser(input: { userID: "<ENCODED USER ID>"}) {
    deletedUserID
  }
}
{
  "data": {
    "deleteUser": {
      "deletedUserID": "VXNxcjowOKKcMzdjZi1hZDQ5LTRiZDItOTMzZC0yOGY1YThlYja86DQ"
    }
  }
}

2.8. generateOOBOTPCode

Calling the generateOOBOTPCode mutation will generate a new OOB OTP Code for a user. This mutation allows you to specify the purpose and target of the OTP as input.

Schema:

generateOOBOTPCode(input: GenerateOOBOTPCodeInput!): GenerateOOBOTPCodePayload!

Example:

mutation {
  generateOOBOTPCode(input: {purpose: LOGIN, target: "user@gmail.com"}) {
    code
  }
}
{
  "data": {
    "generateOOBOTPCode": {
      "code": "552660"
    }
  }
}

2.9. resetPassword

The resetPassword mutation lets you rest a user's password from the Admin API.

Schema:

resetPassword(input: ResetPasswordInput!): ResetPasswordPayload!

Example 1:

mutation {
  resetPassword(input: {userID: "<ENCODED USER ID>", password: "n3w-p4$s"}) {
    user {
      id
      standardAttributes
    }
  }
}
{
  "data": {
    "resetPassword": {
      "user": {
        "id": "VXNlcjowNGUyJJO4Mi04NmEzLTRjYjItOGQxNy14ZWU0Y2FlNzQ5Kse",
        "standardAttributes": {
          "email": "user@gmail.com",
          "email_verified": false,
          "updated_at": 1694742340
        }
      }
    }
  }
}

Example 2 (send new password to user):

You can include sendPassword: true and setPasswordExpired: true in the input for the resetPassword mutation to send the new password to a user and set it as expired so they can set a new one the next time they log in. Here is an example of the mutation:

mutation {
  resetPassword(input: {userID: "<ENCODED USER ID>", password: "n3w-p4$s", sendPassword: true, setPasswordExpired: true}) {
    user {
      id
      standardAttributes
    }
  }
}

2.10. revokeAllSessions

With the revokeAllSessions mutation, you can revoke all sessions for a specific user.

Schema:

revokeAllSessions(input: RevokeAllSessionsInput!): RevokeAllSessionsPayload!

Example:

mutation {
  revokeAllSessions(input: {userID: "<ENCODED USER ID>"}) {
    user {
      id
      standardAttributes
    }
  }
}
{
  "data": {
    "revokeAllSessions": {
      "user": {
        "id": "VXNlcjowNGUyJJO4Mi04NmEzLTRjYjItOGQxNy14ZWU0Y2FlNzQ5Kse",
        "standardAttributes": {
          "email": "user@gmail.com",
          "email_verified": false,
          "updated_at": 1694742340
        }
      }
    }
  }
}

2.11. revokeSession

This mutation revokes a specific user session. You can specify the session using the session ID.

Schema:

revokeSession(input: RevokeSessionInput!): RevokeSessionPayload!

Example:

mutation {
  revokeSession(input: {sessionID: "<ENCODED SESSION ID>"}) {
    user {
      id
      standardAttributes
    }
  }
}
{
  "data": {
    "revokeSession": {
      "user": {
        "id": "VXNlcjowNGUyJJO4Mi04NmEzLTRjYjItOGQxNy14ZWU0Y2FlNzQ5Kse",
        "standardAttributes": {
          "email": "user@gmail.com",
          "email_verified": false,
          "updated_at": 1694742340
        }
      }
    }
  }
}

2.12. scheduleAccountAnonymization

The scheduleAccountAnonymization mutation provides a means to schedule a user account anonymization from the Admin API.

Schema:

scheduleAccountAnonymization(input: ScheduleAccountAnonymizationInput!): ScheduleAccountAnonymizationPayload!

Example:

mutation {
  scheduleAccountAnonymization(input: {userID: "<ENCODED USER ID>"}) {
    user {
      id
      standardAttributes
    }
  }
}
{
  "data": {
    "scheduleAccountAnonymization": {
      "user": {
        "id": "VXNlcjowNGUyJJO4Mi04NmEzLTRjYjItOGQxNy14ZWU0Y2FlNzQ5Kse",
        "standardAttributes": {
          "email": "user@gmail.com",
          "email_verified": false,
          "updated_at": 1694742340
        }
      }
    }
  }
}

2.13. scheduleAccountDeletion

The scheduleAccountDeletion mutation provides a means to schedule a user account deletion from the Admin API.

Schema:

scheduleAccountDeletion(input: ScheduleAccountDeletionInput!): ScheduleAccountDeletionPayload!

Example:

mutation {
  scheduleAccountDeletion(input: {userID: "<ENCODED USER ID>"}) {
    user {
      id
      standardAttributes
    }
  }
}
{
  "data": {
    "scheduleAccountDeletion": {
      "user": {
        "id": "VXNlcjowNGUyJJO4Mi04NmEzLTRjYjItOGQxNy14ZWU0Y2FlNzQ5Kse",
        "standardAttributes": {
          "email": "user@gmail.com",
          "email_verified": false,
          "updated_at": 1694742340
        }
      }
    }
  }
}

2.14. sendResetPasswordMessage

You can send a password reset message to a user from the Admin API using the sendResetPasswordMessage mutation.

Schema:

sendResetPasswordMessage(input: SendResetPasswordMessageInput!): Boolean

Example:

mutation {
  sendResetPasswordMessage(input: {loginID: "<USER LOGIN ID LIKE EMAIL>"})  
}
{
  "data": {
    "sendResetPasswordMessage": null
  }
}

2.15. setDisabledStatus

The setDisabledStatus mutation enables you to enable or disable a user's account.

Schema:

setDisabledStatus(input: SetDisabledStatusInput!): SetDisabledStatusPayload!

Example:

mutation {
  setDisabledStatus(input: {userID: "<ENCODED USER ID>", isDisabled: true, reason: "Test"}) {
    user {
      id
      isDeactivated
    }
  } 
}
{
  "data": {
    "setDisabledStatus": {
      "user": {
        "id": "VXNlcjowNGUyJJO4Mi04NmEzLTRjYjItOGQxNy14ZWU0Y2FlNzQ5Kse",
        "isDeactivated": false
      }
    }
  }
}

2.16. setVerifiedStatus

You can use the setVerifiedStatus mutation to set a user as verified and unveried from the Admin API.

Schema:

setVerifiedStatus(input: SetVerifiedStatusInput!): SetVerifiedStatusPayload!

Example:

mutation {
  setVerifiedStatus(input: {userID: "<ENCODED USER ID>", claimName: "email", claimValue: "user@gmail.com", isVerified: true}) {
    user {
      id
      verifiedClaims {
        name
        value
      }
    }
  } 
}
{
  "data": {
    "setVerifiedStatus": {
      "user": {
        "id": "VXNlcjowNGUyJJO4Mi04NmEzLTRjYjItOGQxNy14ZWU0Y2FlNzQ5Kse",
        "verifiedClaims": [
          {
            "name": "email",
            "value": "myapkneeds@gmail.com"
          }
        ]
      }
    }
  }
}

2.17. unscheduleAccountAnonymization

This mutation allows you to cancel a previously scheduled mutation.

Schema:

unscheduleAccountAnonymization(input: UnscheduleAccountAnonymizationInput!): UnscheduleAccountAnonymizationPayload!

Example:

mutation {
  unscheduleAccountAnonymization(input: {userID: "<ENCODED USER ID>"}) {
    user {
      id
    }
  } 
}
{
  "data": {
    "unscheduleAccountAnonymization": {
      "user": {
        "id": "VXNlcjowNGUyJJO4Mi04NmEzLTRjYjItOGQxNy14ZWU0Y2FlNzQ5Kse"
      }
    }
  }
}

2.18. unscheduleAccountDeletion

This mutation allows you to cancel a previously scheduled deletion.

Schema:

unscheduleAccountDeletion(input: UnscheduleAccountDeletionInput!): UnscheduleAccountDeletionPayload!

Example:

mutation {
  unscheduleAccountDeletion(input: {userID: "<ENCODED USER ID>"}) {
    user {
      id
    }
  } 
}
{
  "data": {
    "unscheduleAccountDeletion": {
      "user": {
        "id": "VXNlcjowNGUyJJO4Mi04NmEzLTRjYjItOGQxNy14ZWU0Y2FlNzQ5Kse"
      }
    }
  }
}

2.19. updateIdentity

The updateIdentity mutation updates an existing identiy of a user.

Schema:

updateIdentity(input: UpdateIdentityInput!): UpdateIdentityPayload!

Example:

mutation {
  updateIdentity(input: { definition: {loginID: {key: "email", value: "user@gmail.com"}}, userID: "<ENCODED USER ID>", identityID: "<ENCODED IDENTITY ID>"}) {
    user {
      id
    }
  } 
}
{
  "data": {
    "updateIdentity": {
      "user": {
        "id": "VXNlcjowNGUyJJO4Mi04NmEzLTRjYjItOGQxNy14ZWU0Y2FlNzQ5Kse"
      }
    }
  }
}

2.20. updateUser

You can use this mutation to update an existing user's details. You can update standard attributes such as email and phone for the user. Or you can modify custom fields using the customAttributes argument.

Schema:

updateUser(input: UpdateUserInput!): UpdateUserPayload!

Example 1 (Standard Attributes):

For this updateUser example, we will be updating the standard attributes for a user. The first thing to do is to extract all the current values of the user's standard attributes into a variable. Then, add new fields or modify existing fields in the variable with new values.

Note: It is important to include the current values of the fields that you don't wish to update but still want to keep. The Admin API will delete any existing fields you omit in the variable.

The following block of code shows an example variable. If you're using GraphiQL, simply create the variable in the variable tab of GraphiQL like this:

{
  "standardAttributes": {
    "family_name": "John",
    "given_name": "Doe",
    "gender": "male"
  }
}
mutation ($standardAttributes: UserStandardAttributes) {
  updateUser(input: {userID: "<ENCODED USER ID>", standardAttributes: $standardAttributes}) {
    user {
      id
      standardAttributes
    }
  }
}
{
  "data": {
    "updateUser": {
      "user": {
        "id": "VXNlcjowNGUyJJO4Mi04NmEzLTRjYjItOGQxNy14ZWU0Y2FlNzQ5Kse",
        "standardAttributes": {
          "email": "user@gmail.com",
          "email_verified": true,
          "family_name": "John",
          "gender": "male",
          "given_name": "Doe",
          "updated_at": 1694947082
        }
      }
    }
  }
}

Example 2 (Custom Attributes)

The following example shows how to update custom attributes.

Note: You must have created the custom attributes you wish to update in Authgear Portal > User Profile > Custom Attributes.

Create a variable and extract the current custom attributes into it. Modify the values of the attributes you wish to update or add new attributes.

Note: Again, it is important to include the current values of the fields that you don't wish to update but still want to keep. The Admin API will delete any existing fields you omit in the variable.

The following block of code shows an example of the variable. You can set the variable in the variable tab of GraphiQL.

{
  "customAttributes": {
    "town": "Lagos"
  }
}
mutation ($customAttributes: UserCustomAttributes) {
  updateUser(input: {userID: "<ENCODED USER ID>", customAttributes: $customAttributes}) {
    user {
      id
      customAttributes
    }
  }
}
{
  "data": {
    "updateUser": {
      "user": {
        "customAttributes": {
          "town": "John"
        },
        "id": "VABlcjo2Y2I3KBU9Zi0zNGYwLTRhNTPdYjQ3ZS0wYWWeMWYzNzQyA1A"
      }
    }
  }
}

2.21 createGroup

Run this mutation to add a new access management group to your Authgear application.

Schema:

createGroup(input: CreateGroupInput!): CreateGroupPayload!

Example:

mutation {
  createGroup(input: {key: "test_group", name: "Test group", description: "This is a test group created using the Admin API"}) {
    group {
      id
    }
  }
}
{
  "data": {
    "createGroup": {
      "group": {
        "id": "R3JvdXA6YTUxYTNmMWQtMDE0ZC00N2JmLTgwNDQtMjEzOTczZDJlMTkx"
      }
    }
  }
}

Note: The value of key can not be empty, must be between 1 and 40 characters long, accepted characters are [a-zA-Z0-9:_] and the prefix authgear: is reserved for Authgear internal use.

2.22 createRole

You can use this mutation to add a new access management role to your Authgear application.

Schema:

createRole(input: CreateRoleInput!): CreateRolePayload!

Example:

mutation {
  createRole(input: {key: "test_role", name: "Test role", description: "This is a test role created using the Admin API"}) {
    role {
      id
    }
  }
}
{
  "data": {
    "createRole": {
      "role": {
        "id": "Um9sZTo2NzNhZGE3Mi1mYWI1LTRiMmMtOTBmYy1hMjY1YmQxY2Q2YjA"
      }
    }
  }
}

Note: The value of key can not be empty, must be between 1 and 40 characters long, accepted characters are [a-zA-Z0-9:_] and the prefix authgear: is reserved for Authgear internal use.

2.23 addRoleToGroups

Use this mutation to add a role to one or more groups in a single operation.

Schema:

addRoleToGroups(input: AddRoleToGroupsInput!): AddRoleToGroupsPayload!

Example:

mutation {
  addRoleToGroups(input: {roleKey: "test_role", groupKeys: ["test_group", "another_group"]}) {
    role {
      id
    }
  }
}
{
  "data": {
    "addRoleToGroups": {
      "role": {
        "id": "Um9sZTo2NzNhZGE3Mi1mYWI1LTRiMmMtOTBmYy1hMjY1YmQxY2Q2YjA"
      }
    }
  }
}

2.24 addGroupToRoles

Adds a group to one or more roles in a single operation.

Schema:

addGroupToRoles(input: AddGroupToRolesInput!): AddGroupToRolesPayload!

Example:

mutation {
  addGroupToRoles(input: {groupKey: "test_group", roleKeys: ["test_role", "another_role"]}) {
    group {
      id
    }
  }
}
{
  "data": {
    "addGroupToRoles": {
      "group": {
        "id": "R3JvdXA6YTUxYTNmMWQtMDE0ZC00N2JmLTgwNDQtMjEzOTczZDJlMTkx"
      }
    }
  }
}

2.25 addUserToRoles

Adds a user to one or more roles in a single operation.

Schema:

addUserToRoles(input: AddUserToRolesInput!): AddUserToRolesPayload!

Example:

mutation {
  addUserToRoles(input: {userID: "<ENCODED USER ID>", roleKeys: ["test_role", "another_role"]}) {
    user {
      id
      standardAttributes
    }
  }
}
{
  "data": {
    "addUserToRoles": {
      "user": {
        "id": "VXNlcjomMyOS02ZGIzlmZWQxN2LTRhMTgtYWE3My03NzQxM5YzcxZmQ",
        "standardAttributes": {
          "email": "user2@example.com",
          "email_verified": false,
          "family_name": "Doe",
          "given_name": "John",
          "name": "John Doe",
          "updated_at": 1712213796
        }
      }
    }
  }
}

2.26 addRoleToUsers

Adds a role to one or more users in a single operation.

Schema:

addRoleToUsers(input: AddRoleToUsersInput!): AddRoleToUsersPayload!

Example:

mutation {
  addRoleToUsers(input: {roleKey: "test_role", userIDs: ["<ENCODED USER ID>", "<ANOTHER ENCODED USER ID>"]}) {
    role {
      id
    }
  }
}
{
  "data": {
    "addRoleToUsers": {
      "role": {
        "id": "Um9sZTo2NzNhZGE3Mi1mYWI1LTRiMmMtOTBmYy1hMjY1YmQxY2Q2YjA"
      }
    }
  }
}

2.27 addUserToGroups

Adds a user to one or more groups in a single operation.

Schema:

addUserToGroups(input: AddUserToGroupsInput!): AddUserToGroupsPayload!

Example:

mutation {
  addUserToGroups(input: {userID: "<ENCODED USER ID>", groupKeys: ["test_group", "another_group"]}) {
    user {
      id
      standardAttributes
    }
  }
}
{
  "data": {
    "addUserToGroups": {
      "user": {
        "id": "VXNlcjo5YzcxZmMyOS02ZGI2LTRhMTgtYWE3My03NzQxMzlmZWQxNmQ",
        "standardAttributes": {
          "email": "user2@example.com",
          "email_verified": false,
          "family_name": "Doe",
          "given_name": "John",
          "name": "John Doe",
          "updated_at": 1712213796
        }
      }
    }
  }
}

2.28 addGroupToUsers

Adds a group to one or more user in a single operation.

Schema:

addGroupToUsers(input: AddGroupToUsersInput!): AddGroupToUsersPayload!

Example:

mutation {
  addGroupToUsers(input: {groupKey: "test_group", userIDs: ["<ENCODED USER ID>", "<ANOTHER ENCODED USER ID>"]}) {
    group {
      id
    }
  }
}
{
  "data": {
    "addGroupToUsers": {
      "group": {
        "id": "R3JvdXA6YTUxYTNmMWQtMDE0ZC00N2JmLTgwNDQtMjEzOTczZDJlMTkx"
      }
    }
  }
}

2.29 updateRole

Updates details about an existing role.

Schema:

updateRole(input: UpdateRoleInput!): UpdateRolePayload!

Example:

mutation {
  updateRole(input: {id:"<ENCODED ROLE ID>", key: "test_role_updated", name: "Test Role Updated", description: "Updated version of this role"}) {
    role {
      id
    }
  }
}
{
  "data": {
    "updateRole": {
      "role": {
        "id": "Um9sZTo2ODk1YWVhZi0yM2U4LTQ5ODYtYWQ3NC1mY2VlZWEwNWQwMzU"
      }
    }
  }
}

Note: Pass null as the value of key, name or description if you do not wish to update them and pass and empty string ("") to delete the value of name and description. Also, some GrahpQL libraries may not allow you to pass a literal null directly in the query, in such cases, use a variable to defind the value of input.

2.30 updateGroup

Updates details about an existing group.

Schema:

updateGroup(input: UpdateGroupInput!): UpdateGroupPayload!

Example:

mutation {
  updateGroup(input: {id:"<ENCODED GROUP ID>", key: "test_group_updated", name: "Test Group Updated", description: "Updated version of this group"}) {
    group {
      id
    }
  }
}
{
  "data": {
    "updateGroup": {
      "group": {
        "id": "R3JvdXA6NzI3MTMxNDgtMzIzMy00ZWVjLTlhOGMtYWNiYjg2MWY5OTlk"
      }
    }
  }
}

Note: Pass null as the value of key, name or description if you do not wish to update them and pass and empty string ("") to delete the value of name and description. Also, some GrahpQL libraries may not allow you to pass a literal null directly in the query, in such cases, use a variable to defind the value of input.

2.31 removeUserFromGroups

Removes a user from one or more groups they're currently in.

Schema:

removeUserFromGroups(input: RemoveUserFromGroupsInput!): RemoveUserFromGroupsPayload!

Example:

mutation {
  removeUserFromGroups(input: {userID: "<ENCODED USER ID>", groupKeys: ["test_group", "another_group"]}) {
    user {
      id
      standardAttributes
    }
  }
}
{
  "data": {
    "removeUserFromGroups": {
      "user": {
        "id": "VXNlcjo5YzcxZmMyOS02ZGI2LTRhMTgtYWE3My03NzQxMzlmZWQxNmQ",
        "standardAttributes": {
          "email": "user2@example.com",
          "email_verified": false,
          "family_name": "Doe",
          "given_name": "John",
          "name": "John Doe",
          "updated_at": 1712213796
        }
      }
    }
  }
}

2.32 removeRoleFromGroups

Removes a role from one or more groups.

Schema:

removeRoleFromGroups(input: RemoveRoleFromGroupsInput!): RemoveRoleFromGroupsPayload!

Example:

mutation {
  removeRoleFromGroups(input: {roleKey: "test_role", groupKeys: ["test_group", "another_role"]}) {
    role {
      id
    }
  }
}
{
  "data": {
    "removeRoleFromGroups": {
      "role": {
        "id": "Um9sZToyOWIwMDM3Yy01ZDEyLTQ3ZjQtYWVhOS1mMGRjMGJiYjk2ZTA",
      }
    }
  }
}

2.33 removeUserFromRoles

Removes a user from one or more roles.

Schema:

removeUserFromRoles(input: RemoveUserFromRolesInput!): RemoveUserFromRolesPayload!

Example:

mutation {
  removeUserFromRoles(input: {userID: "<ENCODED USER ID>", roleKeys: ["test_role", "another_role"]}) {
    user {
      id
      standardAttributes
    }
  }
}
{
  "data": {
    "removeUserFromRoles": {
      "user": {
        "id": "VXNlcjo5YzcxZmMyOS02ZGI2LTRhMTgtYWE3My03NzQxMzlmZWQxNmQ",
        "standardAttributes": {
          "email": "user2@example.com",
          "email_verified": false,
          "family_name": "Doe",
          "given_name": "John",
          "name": "John Doe",
          "updated_at": 1712213796
        }
      }
    }
  }
}

2.34 removeGroupFromRoles

Removes a group from one or more roles in a single operation.

Schema:

removeGroupFromRoles(input: RemoveGroupFromRolesInput!): RemoveGroupFromRolesPayload!

Example:

mutation {
  removeGroupFromRoles(input: {groupKey: "test_group", roleKeys: ["test_role", "another_role"]}) {
    group {
      id
    }
  }
}
{
  "data": {
    "removeGroupFromRoles": {
      "group": {
        "id": "R3JvdXA6OTU4YTA2ODItMDU3ZS00ZmJjLTg3MzItNGRhMDliNWQxNTAx",
      }
    }
  }
}

2.35 removeRoleFromUsers

Removes a role from one or more users in a single operation.

Schema:

removeRoleFromUsers(input: RemoveRoleFromUsersInput!): RemoveRoleFromUsersPayload!

Example:

mutation {
  removeRoleFromUsers(input: {roleKey: "test_role", userIDs: ["<ENCODED USER ID>", "<ANOTHER ENCODED USER ID>"]}) {
    role {
      id
    }
  }
}
{
  "data": {
    "removeRoleFromUsers": {
      "role": {
        "id": "Um9sZTozMjc5NWRiNi1hOWVkLTRhOTgtOTE2MC0zMzZkZGNlOWFkMTM",
      }
    }
  }
}

2.36 removeGroupFromUsers

Removes group from one or more users in a single operation.

Schema:

removeGroupFromUsers(input: RemoveGroupFromUsersInput!): RemoveGroupToUsersPayload!

Example:

mutation {
  removeGroupFromUsers(input: {groupKey: "test_group", userIDs: ["<ENCODED USER ID>", "<ANOTHER ENCODED USER ID>"]}) {
    group {
      id
    }
  }
}
{
  "data": {
    "removeGroupFromUsers": {
      "group": {
        "id": "R3JvdXA6OTU4YTA2ODItMDU3ZS00ZmJjLTg3MzItNGRhMDliNWQxNTAx",
      }
    }
  }
}

2.37 deleteGroup

Use this mutation to delete an existing group.

Schema:

deleteGroup(input: DeleteGroupInput!): DeleteGroupPayload!

Example:

mutation {
  deleteGroup(input: {id: "<ENCODED GROUP ID>"}) {
    ok
  }
}
{
  "data": {
    "deleteGroup": {
      "ok": true
    }
  }
}

2.38 deleteRole

Use this mutation to delete an existing role.

Schema:

deleteRole(input: DeleteRoleInput!): DeleteRolePayload!

Example:

mutation {
  deleteRole(input: {id: "<ENCODED ROLE ID>"}) {
    ok
  }
}
{
  "data": {
    "deleteRole": {
      "ok": true
    }
  }
}

Using global node IDs

The node id is a globally unique identifier of an object. It is needed when you call the GraphQL query and mutation. In this section, we will go through how to generate the node ID for calling the Admin GraphQL API.

The node id is a base64url encoded string with the format of <NODE_TYPE>:<ID>. For example, in User:97b1c929-842c-415c-a7df-6967efdda160 , the node is "User" while "97b1c929-842c-415c-a7df-6967efdda160" is the ID for a specific user.

1. Generate id for User node type

You can use your preferred programming language or tool to encode node IDs to base64url as shown below:

package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	nodeID := base64.RawURLEncoding.EncodeToString([]byte("User:97b1c929-842c-415c-a7df-6967efdda160"))
	fmt.Println(nodeID)
}
import base64

base64.urlsafe_b64encode(b'User:97b1c929-842c-415c-a7df-6967efdda160').replace(b'=', b'')
<?php
function base64url_encode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

$encoded_id = base64url_encode("User:97b1c929-842c-415c-a7df-6967efdda160");
echo $encoded_id;
const encoder = require('base64-url');

const encoded_id = encoder.encode("User:97b1c929-842c-415c-a7df-6967efdda160");
console.log(encoded_id);

Fetch the User object example

The query:

query {
  node(id: "<BASE64URL_ENCODED_USER_NODE_ID>") {
    ... on User {
      id
      standardAttributes
    }
  }
}

2. Generate id for AuditLog node type

package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	nodeID := base64.RawURLEncoding.EncodeToString([]byte("AuditLog:000000000004d2e7"))
	fmt.Println(nodeID)
}
import base64

base64.urlsafe_b64encode(b'AuditLog:000000000004d2e7').replace(b'=', b'')
<?php
function base64url_encode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

$encoded_id = base64url_encode("AuditLog:000000000004d2e7");
echo $encoded_id;
const encoder = require('base64-url');

const encoded_id = encoder.encode("AuditLog:000000000004d2e7");
console.log(encoded_id);

Fetch AuditLog object example

Query:

{
  node(id: "<BASE64URL_ENCODED_AUDIT_LOG_NODE_ID>") {
    ... on AuditLog {
      id
      data
    }
  }
}

3. Generate id for Session node type

package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	nodeID := base64.RawURLEncoding.EncodeToString([]byte("Session:8891767c-992c-4c09-bbae-9a8337ae661k"))
	fmt.Println(nodeID)
}
import base64

base64.urlsafe_b64encode(b'Session:8891767c-992c-4c09-bbae-9a8337ae661k').replace(b'=', b'')
<?php
function base64url_encode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

$encoded_id = base64url_encode("Session:8891767c-992c-4c09-bbae-9a8337ae661k");
echo $encoded_id;
const encoder = require('base64-url');

const encoded_id = encoder.encode("Session:8891767c-992c-4c09-bbae-9a8337ae661k");
console.log(encoded_id);

Fetch Session object example

Query:

{
  node(id: "<BASE64URL_ENCODED_SESSION_NODE_ID>") {
    ... on Session {
      id
      displayName
      type
      createdAt
    }
  }
}

4. Generate id for Authenticator node type

package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	nodeID := base64.RawURLEncoding.EncodeToString([]byte("Authenticator:95435c90-8501-4735-a8b6-412601605a25"))
	fmt.Println(nodeID)
}
import base64

base64.urlsafe_b64encode(b'Authenticator:95435c90-8501-4735-a8b6-412601605a25').replace(b'=', b'')
<?php
function base64url_encode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

$encoded_id = base64url_encode("Authenticator:95435c90-8501-4735-a8b6-412601605a25");
echo $encoded_id;
const encoder = require('base64-url');

const encoded_id = encoder.encode("Authenticator:95435c90-8501-4735-a8b6-412601605a25");
console.log(encoded_id);

Fetch Authenticator object example

Query:

{
  node(id: "<BASE64URL_ENCODED_AUTHENTICATOR_NODE_ID>") {
    id
    ... on Authenticator {
      id
      kind
      createdAt
    }
  }
}

5. Generate id for Authorization node type

package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	nodeID := base64.RawURLEncoding.EncodeToString([]byte("Authorization:12345a90-7801-41d5-c3b6-655501605b56"))
	fmt.Println(nodeID)
}
import base64

base64.urlsafe_b64encode(b'Authorization:12345a90-7801-41d5-c3b6-655501605b56').replace(b'=', b'')
<?php
function base64url_encode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

$encoded_id = base64url_encode("Authorization:12345a90-7801-41d5-c3b6-655501605b56");
echo $encoded_id;
const encoder = require('base64-url');

const encoded_id = encoder.encode("Authorization:12345a90-7801-41d5-c3b6-655501605b56");
console.log(encoded_id);

Fetch Authorization object example

Query:

{
  node(id: "<BASE64URL_ENCODED_AUTHORIZATION_NODE_ID>") {
    id
    ... on Authorization {
      id
      clientID
      scopes
      createdAt
    }
  }
}

6. Generate id for Identity node type

package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	nodeID := base64.RawURLEncoding.EncodeToString([]byte("Identity:12345a90-7801-41d5-c3b6-655501605b56"))
	fmt.Println(nodeID)
}
import base64

base64.urlsafe_b64encode(b'Identity:12345a90-7801-41d5-c3b6-655501605b56').replace(b'=', b'')
<?php
function base64url_encode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

$encoded_id = base64url_encode("Identity:12345a90-7801-41d5-c3b6-655501605b56");
echo $encoded_id;
const encoder = require('base64-url');

const encoded_id = encoder.encode("Identity:12345a90-7801-41d5-c3b6-655501605b56");
console.log(encoded_id);

Fetch Identity object example

Query:

{
  node(id: "<BASE64URL_ENCODED_IDENTITY_NODE_ID>") {
    id
    ... on Identity {
      id
      claims
      type
    }
  }
}

Retrieving users using Admin API

Overview and examples for the getUser/getUsers queries

The getUser and getUsers queries are a collection of Admin API queries for getting details about a single user or multiple users using specific attributes as the search key and in real-time.

Queries in the collection vary by the type of attribute they support as a search key. The queries are:

  • getUsersByStandardAttribute(attributeName: String!, attributeValue: String!)

  • getUserByLoginID(loginIDKey: String!, loginIDValue: String!)

  • getUserByOAuth(oauthProviderAlias: String!, oauthProviderUserID: String!)

Difference Between Users query and the getUser/getUsers queries

The users query is another type of query used to retrieve users. In the following section, we'll discuss the difference between the getUser/getUsers queries and the users query.

  • Immediately Consistent: the getUser and getUsers queries search the database directly for users while the users query depends on a search index. As a result, the users query may not return details about a recently edited user, while getUser and getUsers queries are immediately consistent.

  • Exact Match: the getUser and getUsers queries only return a result that is an exact match. While calling the users query may return users when there is a partial match of a user's email, phone number, or name.

  • Specific attribute: with the getUser and getUsers queries, you need to specify to retrieve the user by their email, username, or phone number. While the users query uses a single searchKeyword field.

Use the users query to search for users without the search term being an exact match. For example, using "John" to search for a user with the full name "John Doe".

Use the getUser and getUsers queries to retrieve the user data after a recent write operation. Note that you can not use any of the getUser and getUsers queries to search for users by their names or any additional attributes outside the supported ones mentioned on this page.

The following section contains details and examples for each query in the getUser and getUsers queries:

1. getUsersByStandardAttribute

The getUsersByStandardAttribute query provides a way to retrieve users using a predefined standard attribute as the search key. The following are the standard attributes (attributeName) that you can use:

  • email

  • preferred_username

  • phone_number

You can use the getUsersByStandardAttribute query to get details for a user that registered with a loginID or OAuth connection. For example, you can use the email field in the standard attribute as a search key to find a user who linked an email address from an OAuth connection or registered using the email and password login method.

Schema:

getUsersByStandardAttribute(
attributeName: String!
attributeValue: String!
): [User!]!

Inputs:

  • attributeName: The name of the standard attribute that will be used as the search key. The value can only be: email, preferred_username, or phone_number.

  • attributeValue: The actual value for the user's standard attribute that you're using (attributeName) as the search key. For example, the full email address of the user if you are using email as the value for attributeName.

Example:

query {
  getUsersByStandardAttribute(attributeName: "email", attributeValue: "user@example.com") {
    id,
    standardAttributes
  }
}
{
  "data": {
    "getUsersByStandardAttribute": [
      {
        "id": "VXNlciklODRkMzdjZi1hZDQ5LTRiZDItOTMzZJ2tOGY1YThlYjc34RE",
        "standardAttributes": {
          "email": "user@example.com",
          "email_verified": true,
          "family_name": "Aboyi",
          "given_name": "John",
          "name": "John Doe",
          "nickname": "Pius",
          "picture": "https://platform-lookaside.fbsbx.com/.../",
          "updated_at": 1724858514
        }
      }
    ]
  }
}

2. getUserByLoginID

Use the getUserByLoginID query to retrieve details about a user using their loginID as the search key. The following are the types of loginID supported:

  • email

  • username

  • phone

Note: An email address linked to a user's account via social/enterprise login (OAuth) provider only can not be used as a search key in the getUserByLoginID query. Use getUsersByStandardAttribute instead to search for email addresses linked via OAuth provider only.

Schema:

getUserByLoginID(
  loginIDValue: String!
  loginIDKey: String!
): User

Inputs:

  • loginIDKey: the value of this field should be the type of loginID associated with the user's account ( email, phone or username).

  • loginIDValue: enter the exact value of the identity associated with the user's account. For example, the user's full email address if their identity is email. For phone, use the full phone number including the "+" sign and country code, e.g. +441234567890.

Example:

The following example shows a getUserByLoginID query and a response when a user is found.

query {
  getUserByLoginID(loginIDKey: "email", loginIDValue: "user@example.com") {
    id,
    standardAttributes
  }
}
{
  "data": {
    "getUserByLoginID": {
      "id": "VXNlciklODRkMzdjZi1hZDQ5LTRiZDItOTMzZJ2tOGY1YThlYjc34RE",
      "standardAttributes": {
        "email": "user@example.com",
        "email_verified": true,
        "family_name": "Doe",
        "given_name": "John",
        "updated_at": 1724854753
      }
    }
  }
}

3. getUserByOAuth

The getUserByOAuth query allows you to retrieve details about a user that linked an identity using a social/enterprise provider. For example, you can use the getUserByOAuth query to search for a user that linked their account to Facebook using the User ID (sub) issued by Facebook OAuth provider as the search key.

Schema:

getUserByOAuth(
  oauthProviderAlias: String!
  oauthProviderUserID: String!
): User

Inputs:

  • oauthProviderAlias: This is an identifier for each OAuth provider that can be set in Authgear portal via Authentication > Social / Enterprise Login. The default for value is google, facebook, github, apple for respective social login providers.

  • oauthProviderUserID: The value for this field should be the sub (User ID) returned by the OAuth provider. You can see the value of a user's oauthProviderUserID in their oauthConnections.claims under the id field. See the official documentation for each OAuth provider to learn more about their sub. This page shows an example of sub from Facebook.

Example

query {
  getUserByOAuth(oauthProviderAlias: "facebook", oauthProviderUserID: "1234567812730389") {
    id,
    oauthConnections {
      claims
    }
  }
}
{
  "data": {
    "getUserByOAuth": {
      "id": "VXNlciklODRkMzdjZi1hZDQ5LTRiZDItOTMzZJ2tOGY1YThlYjc34RE",
      "oauthConnections": [
        {
          "claims": {
            "email": "user@example.com",
            "family_name": "Doe",
            "given_name": "John",
            "https://authgear.com/claims/oauth/profile": {
              "email": "user@example.com",
              "first_name": "John",
              "id": "1234567812730389",
              "last_name": "Doe",
              "name": "John Doe",
              "name_format": "{first} {last}",
              "picture": {
                "data": {
                  "height": 50,
                  "is_silhouette": false,
                  "url": "https://platform-lookaside.fbsbx.com/..../",
                  "width": 50
                }
              },
              "short_name": "John"
            },
            "https://authgear.com/claims/oauth/provider_alias": "facebook",
            "https://authgear.com/claims/oauth/provider_type": "facebook",
            "https://authgear.com/claims/oauth/subject_id": "1234567812730389",
            "name": "John Doe",
            "nickname": "John",
            "picture": "https://platform-lookaside.fbsbx.com/../"
          }
        }
      ]
    }
  }
}

User Management Examples

Learn how to perform common actions from the examples

User Management

In this section of the documentation, we've provided detailed guides showing examples of common user management actions you can perform using the Admin API. Click on any of the links below to view the corresponding guide:

Search for usersUpdate user's standard attributesUpdate user's pictureGenerate OTP code

Looking for more examples? See our full Admin API GraphQL queries and mutations examples page linked below:

Admin API Examples

Search for users

Authgear Admin GraphQL API supports searching user by keywords. Keywords include email, phone number, username, SSO subject id and standard attributes.

Search users by email

You can use the user search query to search user by email and obtains the user details.

In the following example, the project wants to search the user by email and check if they haven't set up the TOTP authenticator.

You can adjust the fields in the query based on your needs. To explore more supporting fields, you can try it out via the GraphiQL tool.

The query has a maximum limit of 20, pagination parameters should be provided to obtain all the results. See detail.

The query

query {
  users(
    searchKeyword: "user@example.com"
  ) {
    edges {
      node {
        id
        createdAt
        lastLoginAt
        isAnonymous
        isDisabled
        disableReason
        isDeactivated
        deleteAt
        standardAttributes
        loginIDs {
          id
          claims
        }
        secondaryTOTPAuthenticators {
          id
          claims
        }
      }
    }
    totalCount
  }
}

The sample response

{
  "data": {
    "users": {
      "edges": [
        {
          "node": {
            "id": "VXNlcjphZTNjMGFiZS02YjdkLTQ1ZjktOWIzZS1jMDUwYjVmY2Q3NjI",
            "lastLoginAt": "2006-01-02T03:04:05.123456Z",
            "createdAt": "2006-01-02T03:04:05.123456Z",
            "deleteAt": null,
            "isDisabled": false,
            "disableReason": null,
            "isAnonymous": false,
            "isDeactivated": false,
            "standardAttributes": {
              "email": "user@example.com",
              "email_verified": true,
              "name": "user01",
              "updated_at": 1136171045
            },
            "loginIDs": [
              {
                "claims": {
                  "email": "user@example.com",
                  "https://authgear.com/claims/login_id/key": "email",
                  "https://authgear.com/claims/login_id/original_value": "user@example.com",
                  "https://authgear.com/claims/login_id/type": "email",
                  "https://authgear.com/claims/login_id/value": "user@example.com"
                },
                "id": "SWRlbnRpdHk6NDNhMzZhMTEtM2VkNS00YjczLWE0ZjktMjQ1MWYyMzM5MmVj"
              }
            ],
            "secondaryTOTPAuthenticators": [
              {
                "claims": {
                  "https://authgear.com/claims/totp/display_name": "TOTP @ 2006-01-02T03:04:05Z"
                },
                "id": "QXV0aGVudGljYXRvcjo3NGY0NWUzNi0xMGEyLTQ0MjctYjMxYS0yY2Q3NjBjZDU4MTc"
              }
            ]
          }
        }
      ],
      "totalCount": 1
    }
  }
}

Pagination

The query

query {
  users(
    first: 5
    after: "b2Zmc2V0OjQ"
    searchKeyword: ""
    sortBy: CREATED_AT
    sortDirection: DESC
  ) {
    edges {
      node {
        id
      }
      cursor
    }
    totalCount
  }
}

The sample response

{
  "data": {
    "users": {
      "edges": [
        {
          "cursor": "b2Zmc2V0OjU",
          "node": {
            "id": "VXNlcjo2YTExYjkxNy0yNTg0LTRmNWEtOTkyMS0xN2E3ZmMzMWZjZWU"
          }
        },
        {
          "cursor": "b2Zmc2V0OjY",
          "node": {
            "id": "VXNlcjo0ZTFhZjZmYy0zM2VjLTQ5NjAtOGI2ZC00YTc5YjkxM2Q5N2Y"
          }
        },
        {
          "cursor": "b2Zmc2V0Ojc",
          "node": {
            "id": "VXNlcjphZDJjZWY5Ny0xYzk2LTQ4N2ItOWQzZS01NGVjMzJhYzUxYjY"
          }
        },
        {
          "cursor": "b2Zmc2V0Ojg",
          "node": {
            "id": "VXNlcjphMWIzMzVhMC1jYTdiLTRjMTItYmVmNC04NmNiZTQ4OGMxNzI"
          }
        },
        {
          "cursor": "b2Zmc2V0Ojk",
          "node": {
            "id": "VXNlcjphOWU2YTYwYy0wYTQ1LTQxMzctYTM3MC0wNWM1MjBlZWFkZmU"
          }
        }
      ],
      "totalCount": 30
    }
  }
}

Parameters

  • searchKeyword: Search for users by specified keyword.

  • first: The number of items to be returned. Maximum is 20.

  • after: A cursor for use in pagination. You can pass the cursor value of the last edges item to a subsequent call to fetch the next page of results.

  • sortBy: The field in which to order users. Supported values: CREATED_AT or LAST_LOGIN_AT.

  • sortDirection: The direction in which to order users by the specified field. Supported values: ASC or DESC.

Update user's standard attributes

Overview

To update the user's standard attributes:

  1. Fetch the user's original standard attributes by query first.

  2. Change the attributes payload and update the user's standard attributes by mutation.

API Details

Generate the user node id

Follow the document here to generate the user node id.

Fetch the user's standard attributes by query

The query:

query {
  node(id: "<BASE64URL_ENCODED_USER_NODE_ID>") {
    ... on User {
      standardAttributes
    }
  }
}

The sample response:

{
  "data": {
    "node": {
      "standardAttributes": {
        "name": "Name",
        "given_name": "Given Name",
        "family_name": "Family Name",
        "middle_name": "Middle Name",
        "nickname": "Nickname",
        "profile": "https://<PROFILE_URL>",
        "picture": "https://<PICTURE_URL>",
        "website": "https://<WEBSITE_URL>",
        "gender": "male",
        "birthdate": "2020-01-01",
        "zoneinfo": "Europe/London",
        "locale": "en",
        "address": {
          "country": "GB",
          "locality": "locality",
          "postal_code": "postal code",
          "region": "region",
          "street_address": "full street address"
        },
        "updated_at": 1649428136
      }
    }
  }
}

Update the user's standard attributes by mutation

Make sure to copy the original standard attributes as any attributes that are missing in the payload will be deleted. Next, change the values for attributes that you want to update.

The query:

mutation ($userID: ID!, $standardAttributes: UserStandardAttributes!) {
  updateUser(input: {userID: $userID, standardAttributes: $standardAttributes}) {
    user {
      id
      standardAttributes
      updatedAt
    }
  }
}

The variables:

{
  "userID": "<BASE64URL_ENCODED_USER_NODE_ID>",
  "standardAttributes": {
    /* Include all the original standard attributes from the previous response */
    /* and change the attributes that you want to update */
    /* The attributes that are missing in the payload will be deleted */
  }
}

The sample variables:

{
  "userID": "<BASE64URL_ENCODED_USER_NODE_ID>",
  "standardAttributes": {
    "name": "Name",
    "given_name": "Given Name",
    "family_name": "Family Name",
    "middle_name": "Middle Name",
    "nickname": "Nickname",
    "profile": "https://<PROFILE_URL>",
    "picture": "https://<PICTURE_URL>",
    "website": "https://<WEBSITE_URL>",
    "gender": "male",
    "birthdate": "2020-01-01",
    "zoneinfo": "Europe/London",
    "locale": "en",
    "address": {
      "country": "GB",
      "locality": "locality",
      "postal_code": "postal code",
      "region": "region",
      "street_address": "full street address"
    }
  }
}

The sample response:

{
  "data": {
    "updateUser": {
      "user": {
        "id": "VXNlcjo5N2IxYzkyOS04NDJjLTQxNWMtYTdkZi02OTY3ZWZkZGExNjA",
        "standardAttributes": {
          "name": "Name",
          "given_name": "Given Name",
          "family_name": "Family Name",
          "middle_name": "Middle Name",
          "nickname": "Nickname",
          "profile": "https://<PROFILE_URL>",
          "picture": "https://<PICTURE_URL>",
          "website": "https://<WEBSITE_URL>",
          "gender": "male",
          "birthdate": "2020-01-01",
          "zoneinfo": "Europe/London",
          "locale": "en",
          "address": {
            "country": "GB",
            "locality": "locality",
            "postal_code": "postal code",
            "region": "region",
            "street_address": "full street address"
          },
          "updated_at": 1649428136
        },
        "updatedAt": "2022-04-08T14:40:16.410087Z"
      }
    }
  }
}

Updating Custom Attributes

To learn how to update a user's custom attributes, see the update custom attribute example.

Update user's picture

Authgear allows your server to update the user's picture via the Admin APIs.

Overview

To update the user's picture:

  1. Make a GET request to /_api/admin/images/upload to obtain the pre-signed upload url.

  2. Make a POST request to the pre-signed upload url to upload the image file. This call returns the result url once the upload is finished.

  3. Call the Admin GraphQL API /_api/admin/graphql to update the user's standard attributes. Update the picture attribute with the result url returned by the previous call.

API Details

Obtain the per-signed upload url

Make a GET request to /_api/admin/images/upload to obtain the pre-signed upload url.

The call will look like this:

GET /_api/admin/images/upload HTTP/1.1
Host: <YOUR_APP>.authgear.cloud
Authorization: Bearer <JWT>

The call returns the pre-signed upload url:

{
  "result": {
    "upload_url": "<PRESIGNED_UPLOAD_URL>"
  }
}

Upload the picture

Upload the picture to the pre-signed upload url. We recommend you to pre-process the image before uploading. The image should be cropped into square and should be less than 10 MB.

Upload the file with FormData and the field name is file. You can construct the multipart/form-data request by most HTTP libraries.

The call will look like this:

POST <PRESIGNED_UPLOAD_URL_PATH> HTTP/1.1
Host: <YOUR_APP>.authgear.cloud
Content-Length: <CONTENT_LENGTH>
Content-Type: multipart/form-data; boundary=----boundary

----boundary
Content-Disposition: form-data; name="file"; filename="image.png"
Content-Type: image/png

<CONTENT_OF_IMAGE_FILE>
----boundary

The call returns the result url once the upload completed, the url is in format of authgearimages:///APP_ID/OBJECT_ID:

{
  "result": {
    "url": "authgearimages:///..."
  }
}

Update user's picture in the standard attributes

Follow the doc of Update user's standard attributes to update the user's picture attribute. Replace the attribute with the new picture url (e.g. authgearimages:///...) obtained by the previous upload.

Generate OTP code

Authgear Admin GraphQL API supports generating OTP code on behalf of end-user when they asks for support.

API Details

The query:

mutation ($target: String!) {
  generateOOBOTPCode(input: { target: $target }) {
    code
  }
}

The variables:

{
  "target": "<USER_EMAIL_OR_PHONE_NUMBER>"
}

The sample variables:

{
  "target": "user@example.com"
}

The sample response:

{
  "data": {
    "generateOOBOTPCode": {
      "code": "123456"
    }
  }
}