CreateKey

CreateKey( param_object )
CreateKey( param_object )
CreateKey( param_object )
CreateKey( param_object )
create_key( param_object )
CreateKey( param_object )

Description

The CreateKey function creates a new key, based on the settings in param_object, which can be used to access the current database. If you provide an optional Reference to a child database, the key is associated with (and provides access to) that database. An admin key must be used when calling CreateKey.

Once the key is created, the key’s secret can be used to connect to Fauna and execute queries within the associated database, with the permissions associated with the key’s role.

If you would prefer to use Fauna’s Attribute-based access control (ABAC), you should use the Login function instead.

Parameters

Argument Type Definition and Requirements

param_object

The param_object fields are described below.

param_object

Field Name Field Type Definition and Requirements

role

String, Reference to a user-defined user-defined role, or an Array of user-defined role references

The built-in access roles include admin, server, server-readonly, client, or one or more user-defined roles.

database

Optional - A ref of an existing child database. If not provided, the new key grants access to the current database.

priority

Optional - A relative weight between 1 and 500, inclusive, indicating how many resources this key should be allowed to utilize. Defaults to 1. A higher number means more resources.

The priority option is deprecated as of release 2.10.0. You should avoid specifying priority. In some future Fauna release, priority will be removed. See Deprecations for more details.

data

Optional - Contains user-defined metadata for the key. It is provided for the developer to store key-relevant information.

.name

Optional - A name to apply to the key, to help differentiate this key from any others that may exist. If provided, this field must exist within the data field.

Returns

An object containing the metadata about the results of CreateKey operations.

Field Name Field Type Definition and Requirements

ref

The Reference is an automatically-generated, unique identifier within the database to the key that was created.

database

The Reference of the database that the key belongs to.

role

The access role for this key.

data

Returned only when provided as a CreateKey parameter, and when returned, its value is identical to the value provided.

.name

Returned only when provided as a CreateKey parameter, and when returned, its value is identical to the value provided.

ts

The timestamp, with microsecond resolution, associated with the creation of the key.

secret

The key’s authentication secret. It is only present at creation. You must copy the key’s secret and store it securely for future use.

hashed_secret

The key’s hashed authentication secret.

Examples

The following query creates a key for the prydain database with an access role of server:

try
{
    Value result = await client.Query(
        CreateKey(
            Obj("database", Database("prydain"), "role", "server")
        )
    );
    Console.WriteLine(result);
}
catch (Exception e)
{
    Console.WriteLine($"ERROR: {e.Message}");
}
ObjectV(ref: RefV(id = "280491289873482240", collection = RefV(id = "keys")),ts: LongV(1603756189140000),database: RefV(id = "prydain", collection = RefV(id = "databases")),role: StringV(server),secret: StringV(fnAD5IFXj4ACAHEArhW3oKlskzXWbls6MrFQcyxr),hashed_secret: StringV($2a$05$G0OyeKLOQUK6zuStl6gHbulOXe6UYlCImIfh9ROp/EiX2edV6DtLa))
result, err := client.Query(
	f.CreateKey(
		f.Obj{"database": f.Database("prydain"), "role": "server"}))

if err != nil {
	fmt.Fprintln(os.Stderr, err)
} else {
	fmt.Println(result)
}
map[database:{prydain 0xc0000af470 0xc0000af470 <nil>} hashed_secret:$2a$05$8fx.ey/kjuBqC24rJnPFeud6eJgANXrM6VCKLwkbTa/zkHq8/CUT2 ref:{280481798553600512 0xc0000af380 0xc0000af380 <nil>} role:server secret:fnAD5Hi1sMACACNy_iktsZt_JnfMqXzS2fqsF0qS ts:1603747137510000]
System.out.println(
    client.query(
        CreateKey(
            Obj(
                "database", Database(Value("prydain")),
                "role", Value("server")
            )
        )
    ).get());
{ref: ref(id = "269699833648906752", collection = ref(id = "keys")), ts: 1593464654500000, database: ref(id = "prydain", collection = ref(id = "databases")), role: "server", secret: "fnADviqR3KACAIavBlIQnHz3eXMSyzgO3Ig3Xp1c", hashed_secret: "$2a$05$WbmfUL1yqFcU3Wh3nKZTm.HrWNGBA7Bjc.uaIqk2LeDMj3GHNmFmG"}
client.query(
  q.CreateKey({
    database: q.Database('prydain'),
    role: 'server',
  })
)
.then((ret) => console.log(ret))
.catch((err) => console.error('Error: %s', err))
{
  ref: Ref(Keys(), "268220607958614528"),
  ts: 1592053954950000,
  database: Database("prydain"),
  role: 'server',
  secret: 'fnADuOk4ytACAMKkYwdY6_SYMpAit84dtYsUsXFF',
  hashed_secret: '$2a$05$7w6fYT43jPB0A.R7i8JayuTLn6kXxsL2Y5nkNjrWZurL9L9pgxo/y'
}
result = client.query(
  q.create_key({
    "database": q.database("prydain"),
    "role": "server"
  })
)
print(result)
{'ref': Ref(id=269061973282390528, collection=Ref(id=keys)), 'ts': 1592856343450000, 'database': Ref(id=prydain, collection=Ref(id=databases)), 'role': 'server', 'secret': 'fnADu-ZwbBACAGltDvSmU9jtXyMC7ccUjiKZlrhS', 'hashed_secret': '$2a$05$Vr7fLfa78XBrAKvWz4iZwezuG9l8kXII259nL6BFi0jmFkrAakrB6'}
try {
  println(Await.result(
    client.query(
  CreateKey(
    Obj("database" -> Database("prydain"), "role" -> "server"))),
    5.seconds
  ))
} catch {
  case unknown: Throwable => println("Error: " + unknown.getMessage())
}
{secret: "fnADwfe0j-ACAKBBcqprw_y2n6vPGefoftXZ5zce", database: ref(id = "prydain", collection = ref(id = "databases")), role: "server", ts: 1594485061080000, ref: ref(id = "270769807498936832", collection = ref(id = "keys")), hashed_secret: "$2a$05$gHA5ioUpzscPNtNkVmnf3OCLaVg4/mU4UG.zX8WB80MGnd0DgwEmq"}

The following query creates a key for the current database with a user-defined role:

try
{
    Value result = await client.Query(
        CreateKey(
            Obj(
                "role", Role("employees"),
                "data", Obj(
                    "name", "For employees"
                )
            )
        )
    );
    Console.WriteLine(result);
}
catch (Exception e)
{
    Console.WriteLine($"ERROR: {e.Message}");
}
ObjectV(ref: RefV(id = "285195865600033280", collection = RefV(id = "keys")),ts: LongV(1608242822180000),role: RefV(id = "employees", collection = RefV(id = "roles")),data: ObjectV(name: StringV(For employees)),secret: StringV(fnAD9Tgg9IACAKAIGxuFjqVNyQXz5MKm5SAqhJuk),hashed_secret: StringV($2a$05$vDPXveFBl5XT9tdhAIizdODVu54u07v4BsX59357o5YKiOW538J4O))
result, err := client.Query(
	f.CreateKey(
		f.Obj{
			"role": f.Role("employees"),
			"data": f.Obj{
				"name": "For employees",
			}}))

if err != nil {
	fmt.Fprintln(os.Stderr, err)
} else {
	fmt.Println(result)
}
map[data:map[name:For employees] hashed_secret:$2a$05$zK1Zd/fRGIFYMQq5qqPnCu85J9rhiwoC2wKG0j7BrrZvBymwJG.1W ref:{285195867337523712 0xc000146120 0xc000146120 <nil>} role:{employees 0xc000146240 0xc000146240 <nil>} secret:fnAD9TghXBACANplvoVk6GcpyoCj_-m-Dc7DP1Jr ts:1608242823840000]
System.out.println(
    client.query(
        CreateKey(
            Obj(
                "role", Role("employees"),
                "data", Obj(
                    "name", Value("For employees")
                )
            )
        )
    )
    .get());
{ref: ref(id = "285195918398980608", collection = ref(id = "keys")), ts: 1608242872570000, role: ref(id = "employees", collection = ref(id = "roles")), data: {name: "For employees"}, secret: "fnAD9TgtP5ACAHC5iOLNKqlKvl1mLD--wZ6rvP1S", hashed_secret: "$2a$05$KlS256qB0ivenm3ubGdSCeIMVHrQ2AlKpCf9.DA6AA0kOIFQ.M.Vq"}
client.query(
  q.CreateKey({
    role: q.Role('employees'),
    data: {
      name: 'For employees',
    },
  })
)
.then((ret) => console.log(ret))
.catch((err) => console.error('Error: %s', err))
{
  ref: Ref(Keys(), "285195918840431104"),
  ts: 1608242872990000,
  role: Role("employees"),
  data: { name: 'For employees' },
  secret: 'fnAD9TgtWeACAHKpRO6F72OxRD1dRvBLqixtBPPX',
  hashed_secret: '$2a$05$/Ft/mYSFoGkSUfOzOEmhSeDu1TSHd8TTVu0JRCemqTef8Szku3dOa'
}
result = client.query(
  q.create_key({
    "role": q.role("employees"),
    "data": {
      "name": "For employees"
    }
  })
)
print(result)
{'ref': Ref(id=285196421681906176, collection=Ref(id=keys)), 'ts': 1608243352500000, 'role': Ref(id=employees, collection=Ref(id=roles)), 'data': {'name': 'For employees'}, 'secret': 'fnAD9TiibZACAKxSQ00bgn1caRIF3fZ4SlK9bJfp', 'hashed_secret': '$2a$05$Mtghtu5ehdcFnx.jgakc/.pdZwyeeloAceC4av7svtXX/UK7gX/Ga'}
try {
  println(Await.result(
    client.query(
        CreateKey(
            Obj(
                "role" -> Role("employees"),
                "data" -> Obj(
                    "name" -> "For employees"
                )
            )
        )
    ),
    5.seconds
))} catch {
  case unknown: Throwable => println("Error: " + unknown.getMessage())
}
{secret: "fnAD9TjYBpACADmt9XsuGnKNydk0YNxqCkV9chmP", role: ref(id = "employees", collection = ref(id = "roles")), data: {name: "For employees"}, ts: 1608243572050000, ref: ref(id = "285196651882086912", collection = ref(id = "keys")), hashed_secret: "$2a$05$WbBgd4JbxgiShDeFPmwvSemn7kdlwmc2YGFaXZgbXeBhgzOd2EpX2"}

Was this article helpful?

We're sorry to hear that.
Tell us how we can improve!
Visit Fauna's Discourse forums or email docs@fauna.com

Thank you for your feedback!