How-to guide·3D viewerJavaScript · Java · .NET · PHP

Show your users' models in your web app

Your backend keeps the API token and gives each visitor a short-lived versions token for the models they may see; your page loads the 3D viewer with that token and asks for a new one when it expires.

This guide is for an application whose users sign in to your software and should see models stored in BIM.works. It has two halves. Your backend holds the API token and has an endpoint that answers each visitor with a versions token: a signed auth token for the versions that visitor may see, with three scopes, valid for minutes. Your page fetches that token, creates its client from it, shows the 3D viewer, and asks your backend for a new token when the old one expires.

Why the API token stays on the server#

Everything in a web page can be read by whoever opens it, in the page source, the browser's developer tools or the network log. An API token in a page would give every visitor what the token gives your backend: every model under its node, with every scope it holds, until the token expires, which by default is a month after its creation and can be as late as three years. The only way to stop a leaked API token is to delete it, which stops your backend too.

A versions token taken from the page names a handful of versions, allows reading them and nothing else, expires in minutes, and cannot create tokens of its own. Tokens and delegation explains the pattern; this guide builds it.

Live demo#

A page on a versions tokenLive demo
Loads the demo model in this page with the demo API token of your account: open BIM.works and sign in once in this browser.

The demo plays both halves in one frame. Your demo API token stands in for the backend and mints a versions token for the model, with fs:read, geometry:read and query:run, valid for 30 seconds. A second client is created from that token alone, and the viewer loads the model through it. Run a query works, because the token has query:run. Download the IFC is refused with NON_AUTHORIZED_SCOPE, because downloading the source file needs model:read. After 30 seconds the token has expired: the next call first goes through the expired-token handler, which mints a new token, and the log shows the refresh. The lifetime select sets the lifetime of the next token.

Before you start#

  • An API token for your backend, created on a node that contains the models (Create an API token). If you gave the token an explicit scope list, it must include tokens:issue and the three scopes the backend hands out (fs:read, geometry:read and query:run): a credential can never issue a scope it does not hold. Keep the token in the server's configuration or a secret store, never in code that is sent to a browser.
  • Your own sign-in. The endpoint decides per visitor which versions they may see, so it needs to know who is asking: your session cookie, your own bearer token, whatever your application already uses.
  • The JavaScript packages in your page (JavaScript and TypeScript), bundled or served as explained in Embed the viewer.

1. Add a token endpoint to your backend#

The endpoint checks the visitor, works out which versions they may see, asks BIM.works for a versions token for exactly those, and answers with the token and the version UUIDs. Node.js and Java use their SDK. The .NET example calls the OpenAPI directly with HttpClient (the .NET SDK's CreateVersionsToken takes the scopes as well, Create a versions token), and so does the PHP one, because the generated PHP client predates scopes. Every example answers GET /api/bimworks-token?project=… with the same JSON, {"auth": {…}, "versionUuids": [ … ]}.

// Node.js with Express. The factory and the client live as long as the application.
import express from "express";
import {BimWorksClientFactory} from "@bimworks/jssdk";

const factory = new BimWorksClientFactory("https://bim.works");
// The API token comes from the server's environment, never from code a browser receives
const bimworks = await factory.createClientWithApiToken(process.env.BIMWORKS_API_TOKEN);

const app = express();
app.get("/api/bimworks-token", async (req, res) => {
	const user = req.session?.user;   // your own sign-in
	if (!user) {
		return res.sendStatus(401);
	}
	const versionUuids = await modelsUserMaySee(user, req.query.project);   // your own rules
	if (versionUuids.length === 0) {
		return res.sendStatus(403);
	}
	const result = await bimworks.tokens.createVersionsToken(versionUuids, 15 * 60, null, false, false,
		["fs:read", "geometry:read", "query:run"]);
	res.json({auth: result.auth, versionUuids});
});
app.listen(3000);
// Spring Boot. One factory and one client for the whole application.
import java.security.Principal;
import java.time.Duration;
import java.util.EnumSet;
import java.util.Set;
import java.util.UUID;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import nl.bimbase.bimworks.client.BimWorksClient;
import nl.bimbase.bimworks.client.BimWorksClientFactory;
import nl.bimbase.bimworks.client.BimWorksException;
import nl.bimbase.bimworks.client.Scope;

@RestController
public class BimWorksTokenController {
	private final BimWorksClientFactory factory = new BimWorksClientFactory("https://bim.works");
	private final BimWorksClient bimworks;

	public BimWorksTokenController() throws BimWorksException {
		// The API token comes from the server's environment, never from code a browser receives
		bimworks = factory.createClientWithApiToken(System.getenv("BIMWORKS_API_TOKEN"));
	}

	@GetMapping("/api/bimworks-token")
	public ResponseEntity<String> token(@RequestParam String project, Principal user) throws BimWorksException {
		Set<UUID> versionUuids = modelsUserMaySee(user, project);   // your own rules
		if (versionUuids.isEmpty()) {
			return ResponseEntity.status(403).build();
		}
		ObjectNode auth = bimworks.tokens.createVersionsToken(versionUuids, Duration.ofMinutes(15),
				EnumSet.of(Scope.FS_READ, Scope.GEOMETRY_READ, Scope.QUERY_RUN), null, false);
		ObjectNode body = JsonNodeFactory.instance.objectNode();
		body.set("auth", auth);
		ArrayNode uuids = body.putArray("versionUuids");
		versionUuids.forEach((uuid) -> uuids.add(uuid.toString()));
		return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(body.toString());
	}
}
// ASP.NET Core minimal API, calling the OpenAPI with HttpClient
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json.Nodes;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// Log in once with the API token from the configuration (user secrets, an environment variable)
var bimworks = new HttpClient { BaseAddress = new Uri("https://bim.works" + "/openapi/") };
var login = await bimworks.PostAsJsonAsync("auth/LoginWithApiToken",
    new { token = builder.Configuration["BimWorks:ApiToken"], response_format = "base64" });
login.EnsureSuccessStatusCode();
bimworks.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", await login.Content.ReadFromJsonAsync<string>());

app.MapGet("/api/bimworks-token", async (string project, HttpContext http) =>
{
    string[] versionUuids = ModelsUserMaySee(http.User, project);   // your own rules
    if (versionUuids.Length == 0)
    {
        return Results.StatusCode(403);
    }
    var created = await bimworks.PostAsJsonAsync("auth/CreateVersionsToken", new
    {
        version_uuids = versionUuids,
        expires_seconds = 15 * 60,
        scopes = new[] { "fs:read", "geometry:read", "query:run" }
    });
    created.EnsureSuccessStatusCode();
    var auth = await created.Content.ReadFromJsonAsync<JsonObject>();
    return Results.Json(new { auth, versionUuids });
});

app.Run();
<?php
// bimworks-token.php, with Guzzle (composer require guzzlehttp/guzzle), calling the OpenAPI
require __DIR__ . '/vendor/autoload.php';

session_start();
if (!isset($_SESSION['user'])) {   // your own sign-in
    http_response_code(401);
    exit;
}
$versionUuids = models_user_may_see($_SESSION['user'], $_GET['project'] ?? '');   // your own rules
if (!$versionUuids) {
    http_response_code(403);
    exit;
}

$http = new GuzzleHttp\Client(['base_uri' => "https://bim.works" . '/openapi/']);
// The API token comes from the server's environment, never from code a browser receives
$bearer = json_decode((string) $http->post('auth/LoginWithApiToken', [
    'json' => ['token' => getenv('BIMWORKS_API_TOKEN'), 'response_format' => 'base64'],
])->getBody());
$auth = json_decode((string) $http->post('auth/CreateVersionsToken', [
    'headers' => ['Authorization' => 'Bearer ' . $bearer],
    'json' => [
        'version_uuids' => $versionUuids,
        'expires_seconds' => 15 * 60,
        'scopes' => ['fs:read', 'geometry:read', 'query:run'],
    ],
])->getBody());

header('Content-Type: application/json');
echo json_encode(['auth' => $auth, 'versionUuids' => $versionUuids]);

modelsUserMaySee is yours: the mapping from your users and projects to BIM.works version UUIDs lives in your own database. A node's current version is its last_version_uuid (List the tree). The SDK methods are createVersionsToken in JavaScript and Java; over HTTP the operation is CreateVersionsToken, which needs a bearer from LoginWithApiToken. Create a versions token lists every field of the request.

What to choose:

Choice Value Why
Versions Only those this visitor may see The token gives access to nothing else, so your rules are enforced by the server on every call.
fs:read Required The page asks for the full version object (getNodeVersions) before it loads it.
geometry:read Required The viewer downloads the geometry. It does not include model:read, so the page cannot download the source file.
query:run Required The ModelManager queries each version's objects and storeys while it loads it, so without query:run addModels fails with NON_AUTHORIZED_SCOPE. The page's own BQL needs it too.
gis:read When the page puts the model on a map Reading the model's geo reference and the GIS layers stored in BIM.works.
Lifetime Minutes, not hours There is no revocation: a token copied from the page works until it expires. The page asks for a new one when it needs it (step 3), so a short life costs one request per refresh.

The backend's own login lasts 90 days (auth.api_token_validity), and never longer than the API token's own expiry date. A service that runs longer creates a new client, or logs in again, when BIM.works answers TOKEN_EXPIRED. The PHP example logs in on every request because PHP keeps no state between requests; cache the bearer to save that call.

2. Load the viewer with the token#

The page asks your endpoint for a token, creates its client from the auth object with createClientWithAuth, and loads the versions the endpoint named. The client validates the token with the server and refuses a token that has already expired.

JavaScript#
import {BimWorksClientFactory} from "@bimworks/jssdk";
import {ModelManager, ObjectStateManager} from "@bimworks/viewercommon";
import {Viewer3d} from "@bimworks/viewer3d";

const project = document.body.dataset.project;   // your page knows which project it shows

// Your endpoint (step 1). The browser sends your own session cookie, no BIM.works secret.
async function bimWorksToken() {
	const response = await fetch("/api/bimworks-token?project=" + encodeURIComponent(project), {credentials: "include"});
	if (!response.ok) {
		throw new Error("No BIM.works token: HTTP " + response.status);
	}
	return response.json();   // {auth, versionUuids}
}

const {auth, versionUuids} = await bimWorksToken();
const factory = new BimWorksClientFactory("https://bim.works");
const client = await factory.createClientWithAuth(auth);
// Step 3: before a call goes out with an expired token, the client asks for a new one
client.registerExpiredTokenHandler(async () => (await bimWorksToken()).auth);

const modelManager = new ModelManager(client);
const objectStateManager = new ObjectStateManager(modelManager);
const viewer = new Viewer3d(objectStateManager);
await viewer.initializeViewer();
document.getElementById("viewer").appendChild(viewer.container);

const versions = await client.fs.getNodeVersions(versionUuids);
await modelManager.addModels(versions);
// The models are loaded, with nothing but the versions token

From here on the page is an ordinary viewer page: Embed the viewer covers progress, unloading, clean-up and the viewer settings, and the other guides in this section each add one feature. Every call they make goes out with the versions token, so it can do what the token's scopes allow, on the token's versions, and nothing more.

3. Keep the page working past the expiry#

registerExpiredTokenHandler is what lets a 15-minute token serve a page that stays open all day. How it behaves (Refresh an expired token has the details):

  • Before every call, the client compares the token's expiry with the clock. When the token has expired, the client calls the handler, waits for the new auth object, and then sends the call with it. Calls made while a refresh is running wait for that same refresh, so your endpoint is asked once.
  • Nothing happens while the page makes no calls. What the viewer has loaded stays on screen; the next call, a query your page runs when the user clicks an object, say, refreshes the token first.
  • When the handler throws, because your endpoint answers 401 after the user signed out, say, the call that was waiting fails and carries the error your handler threw. The next call tries the handler again.
  • createClientWithAuth refuses a token that has already expired. When the page creates a client later, for a second viewer say, it fetches a fresh token first.

Try it in one file#

For trying the pattern without a backend, this example plays both halves in one page: a client signed in with the API token stands in for your backend and mints the versions token, and a second client is created from that token alone. Never ship it like this, because the page holds the API token.

const factory = new BimWorksClientFactory("https://bim.works");

// For trying only: this client plays your backend. In your application it runs on your server,
// because whoever has the API token can do everything the token allows
const backend = await factory.createClientWithApiToken("<your API token>");

// What your token endpoint does: one version, three scopes, a short life
async function newToken() {
	const result = await backend.tokens.createVersionsToken(["<version uuid of the first demo model>"], 60, null, false, false,
		["fs:read", "geometry:read", "query:run"]);
	return result.auth;
}

// Here the page starts: it has the auth object and nothing else
const client = await factory.createClientWithAuth(await newToken());

// Before a call goes out with an expired token, the client asks for a new one
client.registerExpiredTokenHandler(() => newToken());

// The ModelManager keeps track of which models are loaded
const modelManager = new ModelManager(client);

// The ObjectStateManager keeps the state of the loaded objects: visibility, colour and selection
const objectStateManager = new ObjectStateManager(modelManager);

const viewer = new Viewer3d(objectStateManager);
await viewer.initializeViewer();
document.body.appendChild(viewer.container);

const version = await client.fs.getNodeVersion("<version uuid of the first demo model>");
await modelManager.addModels([version]);
// The model is loaded; calls made after a minute get a new token first

The backend is simulated in the page, for trying only. The token lives a minute; every call made after that first gets a new token through the handler.

The second example makes the refresh fail on purpose, as when your endpoint is unreachable or the user's session has ended. Click objects after 20 seconds: the first two queries fail with the handler's error, the third gets a new token and answers.

const factory = new BimWorksClientFactory("https://bim.works");

// For trying only: this client plays your backend. In your application it runs on your server
const backend = await factory.createClientWithApiToken("<your API token>");

async function newToken(seconds) {
	const result = await backend.tokens.createVersionsToken(["<version uuid of the first demo model>"], seconds, null, false, false,
		["fs:read", "geometry:read", "query:run"]);
	return result.auth;
}

// A token that lives long enough to load the model, then expires
const client = await factory.createClientWithAuth(await newToken(20));

// The first two refreshes fail, as when your backend is unreachable or the user's session has ended
let failures = 2;
client.registerExpiredTokenHandler(async () => {
	if (failures > 0) {
		failures--;
		throw new Error("The backend gave no new token");
	}
	return newToken(60);
});

const modelManager = new ModelManager(client);
const objectStateManager = new ObjectStateManager(modelManager);

// Click objects after 20 seconds: the first two queries fail with the handler's error,
// the third gets a new token and answers
objectStateManager.addSelectionListener({
	setToSelectionSet: async (selectedQids) => {
		if (selectedQids.size == 0) {
			return;
		}
		const list = Array.from(selectedQids).map((qid) => '"' + qid + '"').join(", ");
		try {
			console.log(await client.bim.query(["<version uuid of the first demo model>"], "GET qid, attribute.Name WHERE qid IN (" + list + ")"));
		} catch (e) {
			console.log("The token expired and the refresh failed", e.error);
		}
	}
});

const viewer = new Viewer3d(objectStateManager);
await viewer.initializeViewer();
document.body.appendChild(viewer.container);

await modelManager.addModels([await client.fs.getNodeVersion("<version uuid of the first demo model>")]);

The handler throws twice before it returns a new token. Each failed refresh fails only the call that was waiting for it.

Check#

  • In the browser's network log, no request carries your API token. The requests to BIM.works carry the auth object your endpoint returned.
  • The model is on screen and a query on it answers. Asking for a version that is not in the token fails with AuthorizationError.NO_READ_RIGHTS. Downloading the source file fails with NON_AUTHORIZED_SCOPE, because the token has no model:read.
  • With a lifetime of 30 seconds in the endpoint, wait a minute and run a query. Your endpoint is called once, the browser console logs "Token has expired" and "Calling expiredTokenHandler", and the query answers.