How-to guide·AuthenticationJavaScript · Java · .NET · PHP

Create a nodes token

Issue a short-lived token for a set of nodes, including the versions they will get later, and use it in the browser.

For a backend whose users follow a model rather than one upload of it. A nodes token names a set of nodes and grants every version of them, the ones that exist now and the ones uploaded while the token is valid. It does not recurse into folders; for that, use a recursive-node token. When you want to pin exact versions, use a versions token.

Before you start#

1. Choose the lifetime#

expires_seconds is required and the token cannot be revoked; keep it short and refresh from the backend (Refresh an expired token).

2. Create the token in the backend#

Classic SDK
const result = await client.tokens.createNodesToken(
	[nodeUuid1, nodeUuid2], 30 * 60,
	null, false, false, ["fs:read", "geometry:read", "query:run"]);
const auth = result.auth;   // the JSON to send to the browser
import java.time.Duration;
import java.util.EnumSet;
import java.util.Set;
import java.util.UUID;
import com.fasterxml.jackson.databind.node.ObjectNode;
import nl.bimbase.bimworks.client.Scope;

ObjectNode auth = client.tokens.createNodesToken(Set.of(nodeUuid1, nodeUuid2), Duration.ofMinutes(30),
		EnumSet.of(Scope.FS_READ, Scope.GEOMETRY_READ, Scope.QUERY_RUN), null, false);
ISet<Guid> nodes = Collections.CreateHashSet(nodeUuid1, nodeUuid2);
ISet<Scope> scopes = new HashSet<Scope> { Scope.FS_READ, Scope.GEOMETRY_READ, Scope.QUERY_RUN };
CreateNodesTokenResponse response = client.Tokens.CreateNodesToken(
    new CreateNodesTokenRequest(nodes, scopes, TimeSpan.FromMinutes(30)));
AuthToken auth = response.GetAuth();
string forBrowser = auth.GetJson().GetRawText();
OpenAPI SDK
import nl.bimbase.bimworks.sdk.api.AuthApi;
import nl.bimbase.bimworks.sdk.client.ApiClient;
import nl.bimbase.bimworks.sdk.model.Auth;
import nl.bimbase.bimworks.sdk.model.CreateNodesTokenRequest;
import nl.bimbase.bimworks.sdk.model.LoginWithApiTokenRequest;

public class Example {
    public static void main(String[] args) throws Exception {
        // 1. Connect to BIM.works and log in with your API token
        ApiClient client = new ApiClient();
        client.updateBaseUri("https://bim.works/openapi");
        Auth auth = new AuthApi(client)
                .loginWithApiToken(new LoginWithApiTokenRequest().token("<your API token>"))
                .getAuth();
        client.setRequestInterceptor(builder -> builder.setHeader("Authorization", "Bearer " + auth.getBase64()));

        // 2. The request
        CreateNodesTokenRequest request = client.getObjectMapper().readValue("""
                {
                  "node_uuids": [
                    "<node uuid>",
                    "<node uuid>"
                  ],
                  "expires_seconds": 1800,
                  "scopes": [
                    "fs:read",
                    "geometry:read",
                    "query:run"
                  ]
                }
                """, CreateNodesTokenRequest.class);

        // 3. The call
        var result = new AuthApi(client).createNodesToken(request);

        // 4. The result
        System.out.println(client.getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(result));
    }
}
using System.Text.Json;
using BIMworks.Sdk.Api;
using BIMworks.Sdk.Client;
using BIMworks.Sdk.Extensions;
using BIMworks.Sdk.Model;
using Microsoft.Extensions.DependencyInjection;

// 1. Connect to BIM.works and log in with your API token
IServiceProvider Connect(string bearer)
{
    var services = new ServiceCollection();
    services.AddApi(options =>
    {
        options.AddTokens(new BearerToken(bearer));
        options.AddApiHttpClients(http =>
        {
            http.BaseAddress = new Uri("https://bim.works" + "/openapi");
            http.Timeout = Timeout.InfiniteTimeSpan;
        });
    });
    return services.BuildServiceProvider();
}
var login = await Connect("").GetRequiredService<IAuthApi>().LoginWithApiTokenAsync(new LoginWithApiTokenRequest("<your API token>"));
var auth = login.Ok()?.Auth ?? throw new HttpRequestException(login.RawContent, null, login.StatusCode);
var client = Connect(auth.Base64);
var json = client.GetRequiredService<JsonSerializerOptionsProvider>().Options;

// 2. The request
var request = JsonSerializer.Deserialize<CreateNodesTokenRequest>("""
    {
      "node_uuids": [
        "<node uuid>",
        "<node uuid>"
      ],
      "expires_seconds": 1800,
      "scopes": [
        "fs:read",
        "geometry:read",
        "query:run"
      ]
    }
    """, json);

// 3. The call
var response = await client.GetRequiredService<IAuthApi>().CreateNodesTokenAsync(request);

// 4. The result
var result = response.Ok() ?? throw new HttpRequestException(response.RawContent, null, response.StatusCode);
Console.WriteLine(JsonSerializer.Serialize(result.Auth, json));
import { AuthApi, AuthResultToJSON, Configuration, CreateNodesTokenRequestFromJSON } from "@bimworks/sdk";

// 1. Connect to BIM.works and log in with your API token
const basePath = "https://bim.works/openapi";
const auth = await new AuthApi(new Configuration({ basePath }))
  .loginWithApiToken({ loginWithApiTokenRequest: { token: "<your API token>" } });
const client = new Configuration({ basePath, accessToken: typeof auth === "string" ? auth : auth.base64 });

// 2. The request
const request = CreateNodesTokenRequestFromJSON({
  "node_uuids": [
    "<node uuid>",
    "<node uuid>"
  ],
  "expires_seconds": 1800,
  "scopes": [
    "fs:read",
    "geometry:read",
    "query:run"
  ]
});

// 3. The call
const result = await new AuthApi(client).createNodesToken({ createNodesTokenRequest: request });

// 4. The result
console.log(JSON.stringify(AuthResultToJSON(result), null, 2));
<?php
require __DIR__ . '/vendor/autoload.php';

use BIMworks\Api\AuthApi;
use BIMworks\Configuration;
use BIMworks\Model\CreateNodesTokenRequest;
use BIMworks\Model\LoginWithApiTokenRequest;
use BIMworks\ObjectSerializer;

// 1. Connect to BIM.works and log in with your API token
$client = (new Configuration())->setHost('https://bim.works/openapi');
$auth = (new AuthApi(config: $client))->loginWithApiToken(new LoginWithApiTokenRequest(['token' => "<your API token>"]));
$client->setAccessToken($auth->getBase64());

// 2. The request
$request = ObjectSerializer::deserialize(<<<'JSON'
{
  "node_uuids": [
    "<node uuid>",
    "<node uuid>"
  ],
  "expires_seconds": 1800,
  "scopes": [
    "fs:read",
    "geometry:read",
    "query:run"
  ]
}
JSON, CreateNodesTokenRequest::class);

// 3. The call
$result = (new AuthApi(config: $client))->createNodesToken($request);

// 4. The result
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), PHP_EOL;
import json

import bimworks

# 1. Connect to BIM.works and log in with your API token
client = bimworks.ApiClient(bimworks.Configuration(host="https://bim.works/openapi"))
auth = bimworks.AuthApi(client).login_with_api_token(
    bimworks.LoginWithApiTokenRequest(token="<your API token>"))
client.configuration.access_token = auth.actual_instance.var_base64

# 2. The request
request = bimworks.CreateNodesTokenRequest.from_json(r"""
{
  "node_uuids": [
    "<node uuid>",
    "<node uuid>"
  ],
  "expires_seconds": 1800,
  "scopes": [
    "fs:read",
    "geometry:read",
    "query:run"
  ]
}
""")

# 3. The call
result = bimworks.AuthApi(client).create_nodes_token(request)

# 4. The result
print(json.dumps(client.sanitize_for_serialization(result), indent=2))

The methods: createNodesToken on Tokens and TokensApi, CreateNodesToken on Tokens, AuthApi::createNodesToken in PHP SDK; over HTTP CreateNodesToken:

POST/openapi/auth/CreateNodesTokenCreateNodesToken reference
Authorization
Bearer <auth token>
Content-Type
application/json
Body
1 2 3 4 5
Authorization: Bearer <auth token>
Content-Type: application/json
Accept: application/json
curl -X POST "$BIMWORKS_URL/openapi/auth/CreateNodesToken" \
  -H "Authorization: Bearer $BIMWORKS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
  "node_uuids": ["<node uuid>", "<node uuid>"],
  "expires_seconds": 1800,
  "scopes": ["fs:read", "geometry:read", "query:run"]
}'
Send to see the response

The fields are those of the versions token with node_uuids instead of version_uuids. Every node is checked for read rights; one node you may not read fails the whole call with AuthorizationError.NO_READ_RIGHTS.

3. Use it in the browser#

Create the page's client with createClientWithAuth(auth) exactly as for a versions token (how-to/auth/create-a-versions-token#use). The page resolves a node to its current version with fs.getNodeByUuid(nodeUuid).last_version_uuid (Fs) and loads or queries that.

Check#

With the browser client, fs.getNodeByUuid on one of the nodes answers, and a query on its last_version_uuid returns objects. Upload a new version of the node from the backend; the same token now resolves to the new last_version_uuid. A node outside the set fails with AuthorizationError.NO_READ_RIGHTS.