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

Create a recursive-node token

Issue a short-lived token for one folder and everything below it, and use it in the browser.

For a backend where each user's models live in one folder. A recursive-node token names a single node and grants that node, every node below it and every version of them, now and later. One token per user session, created at login, is enough; it never needs updating when models are added. Use it with care: a token on a folder high in the tree grants a lot.

Before you start#

1. Choose the lifetime#

expires_seconds is required and the token cannot be revoked; a recursive token in particular should not outlive the user's session (Refresh an expired token).

2. Create the token in the backend#

Classic SDK
const result = await client.tokens.createRecursiveNodeToken(
	folderUuid, 60 * 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 com.fasterxml.jackson.databind.node.ObjectNode;
import nl.bimbase.bimworks.client.Scope;

ObjectNode auth = client.tokens.createRecursiveNodeToken(folderUuid, Duration.ofHours(1),
		EnumSet.of(Scope.FS_READ, Scope.GEOMETRY_READ, Scope.QUERY_RUN), null, false);
ISet<Scope> scopes = new HashSet<Scope> { Scope.FS_READ, Scope.GEOMETRY_READ, Scope.QUERY_RUN };
CreateRecursiveNodeTokenResponse response = client.Tokens.CreateRecursiveNodeToken(
    new CreateRecursiveNodeTokenRequest(folderUuid, scopes, TimeSpan.FromHours(1)));
string forBrowser = response.GetAuth().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.CreateRecursiveNodeTokenRequest;
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
        CreateRecursiveNodeTokenRequest request = client.getObjectMapper().readValue("""
                {
                  "node_uuid": "<folder uuid>",
                  "expires_seconds": 3600,
                  "scopes": [
                    "fs:read",
                    "geometry:read",
                    "query:run"
                  ]
                }
                """, CreateRecursiveNodeTokenRequest.class);

        // 3. The call
        var result = new AuthApi(client).createRecursiveNodeToken(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<CreateRecursiveNodeTokenRequest>("""
    {
      "node_uuid": "<folder uuid>",
      "expires_seconds": 3600,
      "scopes": [
        "fs:read",
        "geometry:read",
        "query:run"
      ]
    }
    """, json);

// 3. The call
var response = await client.GetRequiredService<IAuthApi>().CreateRecursiveNodeTokenAsync(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, CreateRecursiveNodeTokenRequestFromJSON } 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 = CreateRecursiveNodeTokenRequestFromJSON({
  "node_uuid": "<folder uuid>",
  "expires_seconds": 3600,
  "scopes": [
    "fs:read",
    "geometry:read",
    "query:run"
  ]
});

// 3. The call
const result = await new AuthApi(client).createRecursiveNodeToken({ createRecursiveNodeTokenRequest: 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\CreateRecursiveNodeTokenRequest;
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_uuid": "<folder uuid>",
  "expires_seconds": 3600,
  "scopes": [
    "fs:read",
    "geometry:read",
    "query:run"
  ]
}
JSON, CreateRecursiveNodeTokenRequest::class);

// 3. The call
$result = (new AuthApi(config: $client))->createRecursiveNodeToken($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.CreateRecursiveNodeTokenRequest.from_json(r"""
{
  "node_uuid": "<folder uuid>",
  "expires_seconds": 3600,
  "scopes": [
    "fs:read",
    "geometry:read",
    "query:run"
  ]
}
""")

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

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

The methods: createRecursiveNodeToken on Tokens and TokensApi, CreateRecursiveNodeToken on Tokens, AuthApi::createRecursiveNodeToken in PHP SDK; over HTTP CreateRecursiveNodeToken:

POST/openapi/auth/CreateRecursiveNodeTokenCreateRecursiveNodeToken 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/CreateRecursiveNodeToken" \
  -H "Authorization: Bearer $BIMWORKS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
  "node_uuid": "<folder uuid>",
  "expires_seconds": 3600,
  "scopes": ["fs:read", "geometry:read", "query:run"]
}'
Send to see the response

The fields are those of the versions token with a single node_uuid.

3. Use it in the browser#

Create the page's client with createClientWithAuth(auth) as for a versions token (how-to/auth/create-a-versions-token#use). The token's node is the client's root: fs.getNodeByPath("/") returns the folder, fs.listNodes(uuid) lists what is below it (Fs), and paths are relative to the folder.

Check#

With the browser client, fs.getNodeByPath("/") returns the folder you named, and a model anywhere below it can be queried by its last_version_uuid. The folder's parent cannot be reached: fs.getNodeByUuid(parentUuid) fails with AuthorizationError.NO_READ_RIGHTS.