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

Create a versions token

Issue a short-lived token for an exact set of model versions in your backend and use it in the browser.

For a backend that decides which models a user may see and wants the browser to load exactly those. A versions token names a set of versions, possibly from different nodes, and gives access to nothing else; it is the delegated token you want most of the time.

Before you start#

1. Choose the lifetime#

expires_seconds is required and there is no revocation: pick the shortest time the page needs, and refresh from the backend when it runs out (Refresh an expired token). A page that stays open for a working day is better served by refreshing hourly than by an eight-hour token.

2. Create the token in the backend#

Classic SDK
// Node.js backend: 30 minutes, scopes as wire strings
const result = await client.tokens.createVersionsToken(
	["<version uuid of the first demo model>", "<version uuid of the second demo model>"], 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;

Set<UUID> versions = Set.of(UUID.fromString("<version uuid of the first demo model>"), UUID.fromString("<version uuid of the second demo model>"));
ObjectNode auth = client.tokens.createVersionsToken(versions, Duration.ofMinutes(30),
		EnumSet.of(Scope.FS_READ, Scope.GEOMETRY_READ, Scope.QUERY_RUN), null, false);
String forBrowser = auth.toString();   // the JSON to send to the browser
ISet<Guid> versions = Collections.CreateHashSet(Guid.Parse("<version uuid of the first demo model>"), Guid.Parse("<version uuid of the second demo model>"));
ISet<Scope> scopes = new HashSet<Scope> { Scope.FS_READ, Scope.GEOMETRY_READ, Scope.QUERY_RUN };
CreateVersionsTokenResponse response = client.Tokens.CreateVersionsToken(
    new CreateVersionsTokenRequest(versions, scopes, TimeSpan.FromMinutes(30)));
AuthToken auth = response.GetAuth();
string forBrowser = auth.GetJson().GetRawText();   // the JSON to send to the browser
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.CreateVersionsTokenRequest;
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
        CreateVersionsTokenRequest request = client.getObjectMapper().readValue("""
                {
                  "version_uuids": [
                    "<version uuid of the first demo model>",
                    "<version uuid of the second demo model>"
                  ],
                  "expires_seconds": 1800,
                  "scopes": [
                    "fs:read",
                    "geometry:read",
                    "query:run"
                  ]
                }
                """, CreateVersionsTokenRequest.class);

        // 3. The call
        var result = new AuthApi(client).createVersionsToken(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<CreateVersionsTokenRequest>("""
    {
      "version_uuids": [
        "<version uuid of the first demo model>",
        "<version uuid of the second demo model>"
      ],
      "expires_seconds": 1800,
      "scopes": [
        "fs:read",
        "geometry:read",
        "query:run"
      ]
    }
    """, json);

// 3. The call
var response = await client.GetRequiredService<IAuthApi>().CreateVersionsTokenAsync(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, CreateVersionsTokenRequestFromJSON } 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 = CreateVersionsTokenRequestFromJSON({
  "version_uuids": [
    "<version uuid of the first demo model>",
    "<version uuid of the second demo model>"
  ],
  "expires_seconds": 1800,
  "scopes": [
    "fs:read",
    "geometry:read",
    "query:run"
  ]
});

// 3. The call
const result = await new AuthApi(client).createVersionsToken({ createVersionsTokenRequest: 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\CreateVersionsTokenRequest;
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'
{
  "version_uuids": [
    "<version uuid of the first demo model>",
    "<version uuid of the second demo model>"
  ],
  "expires_seconds": 1800,
  "scopes": [
    "fs:read",
    "geometry:read",
    "query:run"
  ]
}
JSON, CreateVersionsTokenRequest::class);

// 3. The call
$result = (new AuthApi(config: $client))->createVersionsToken($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.CreateVersionsTokenRequest.from_json(r"""
{
  "version_uuids": [
    "<version uuid of the first demo model>",
    "<version uuid of the second demo model>"
  ],
  "expires_seconds": 1800,
  "scopes": [
    "fs:read",
    "geometry:read",
    "query:run"
  ]
}
""")

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

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

The methods: createVersionsToken on Tokens and TokensApi, CreateVersionsToken on Tokens, AuthApi::createVersionsToken in PHP SDK. Over HTTP the operation is CreateVersionsToken:

POST/openapi/auth/CreateVersionsTokenCreateVersionsToken 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/CreateVersionsToken" \
  -H "Authorization: Bearer $BIMWORKS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
  "version_uuids": [BIM_WORKS_FIRST_MODEL, BIM_WORKS_SECOND_MODEL],
  "expires_seconds": 1800,
  "scopes": ["fs:read", "geometry:read", "query:run"]
}'
Send to see the response

The fields, for all three delegated tokens:

Field Meaning
expires_seconds Required. Lifetime from now: at most 90 days (the instance's auth.issued_token_max_validity), and never past the expiry of the API token that asks for it. A longer request is cut, not refused.
version_uuids The versions (for nodes and recursive-node tokens: node_uuids or node_uuid).
scopes The scopes granted; at most the issuer's own. Preferred. Left out, a token made with an API token gets that token's scopes, never none.
tasks Deprecated: an allow-list of task names. It does not cover calls added later, and the reply carries a deprecation notice when only tasks is given. On a token made with an API token, a listed task runs with the token's scopes and its own, under the same entitlement checks as scopes.
ip_addresses Addresses that may use the token; empty means any.
lock_to_caller_ip Restrict the token to the address that asks for it. Over HTTP the field is called lock_to_called_ip; the SDKs' task calls accept both names. Ignored when ip_addresses is given.
link_account Record the issuing account in the token, so activity is attributed to it.
response_format HTTP only: auth (the object, default) or base64 (the bearer string).

3. Use it in the browser#

Send the auth JSON to the page over your own channel and create a client from it. The client validates the token with the server; an already expired token is refused before any call is made (TOKEN_EXPIRED).

const factory = new BimWorksClientFactory("https://bim.works");
const client = await factory.createClientWithAuth(auth);   // the object from the backend
const objects = await client.bim.query(["<version uuid of the first demo model>"], "GET qid, attribute.Name WHERE type = IFCDOOR");
// A Java client from a delegated token, for example in a test of the token
try (BimWorksClient delegated = factory.createClientWithAuth(auth)) {
	delegated.bim.query("GET qid WHERE type = IFCDOOR", UUID.fromString("<version uuid of the first demo model>"));
}
using (BimWorksClient delegated = factory.CreateClientWithAuth(auth))
{
    delegated.Bim.Query(Guid.Parse("<version uuid of the first demo model>"), "GET qid WHERE type = IFCDOOR");
}

createClientWithAuth is on the factory of each SDK (Classic JavaScript SDK, Classic Java SDK, Classic .NET SDK); the HTTP equivalent is the base64 string in the Authorization: Bearer header.

Check#

With the browser client, query one of the versions: it answers. Query a version that is not in the token: it fails with AuthorizationError.NO_READ_RIGHTS. Call something outside the scopes, for example a download with only geometry:read: it fails with NON_AUTHORIZED_SCOPE.