How-to guide·AuthenticationJavaScript · PHP

Use an anonymous token

Give a user without an account a private folder: create an anonymous token, store it, and log in with it for an hour at a time.

For applications whose users have no BIM.works account and should not need one: a try-out page, a one-off upload, a kiosk. An anonymous token is created without any login, comes with its own folder and user features, and is exchanged for a one-hour auth token as often as needed. Whoever holds the token holds the folder; there is no account behind it and no way to recover a lost token.

Before you start#

  • The instance must have anonymous tokens switched on (features.anonymous_tokens in the server configuration, off by default). Otherwise both calls fail with ANONYMOUS_TOKENS_DISABLED.
  • Somewhere to keep the token: browser storage for a page, a database row for a backend.
Note

This is not the same as createAnonymousClient() of the Java, .NET and JavaScript SDKs. That is an anonymous login without any token: a one-hour client that may only call the public operations (the server version, registration, password reset). An anonymous token gives a folder to upload into and query.

1. Create the token#

The operation is CreateAnonymousToken, with an optional identifier (up to 256 characters) that is stored with the token for your own bookkeeping. The reply holds the token, its UUID and the UUID of its folder. The token is shown exactly once.

Classic SDK
// The JavaScript SDK has no typed method yet; use the low-level client of any client, even an anonymous one.
const factory = new BimWorksClientFactory("https://bim.works");
const bootstrap = await factory.createAnonymousClient();
const created = await bootstrap.client.post("BimRepository", "CreateAnonymousToken", {identifier: "kiosk 3"}).execAsPromise();
localStorage.setItem("bimworks-anonymous-token", created.token);   // at-...
console.log(created.root_node_uuid);
OpenAPI SDK
import nl.bimbase.bimworks.sdk.api.AuthApi;
import nl.bimbase.bimworks.sdk.client.ApiClient;
import nl.bimbase.bimworks.sdk.model.CreateAnonymousTokenRequest;

public class Example {
    public static void main(String[] args) throws Exception {
        // 1. Connect to BIM.works (CreateAnonymousToken needs no login)
        ApiClient client = new ApiClient();
        client.updateBaseUri("https://bim.works/openapi");

        // 2. The request
        CreateAnonymousTokenRequest request = client.getObjectMapper().readValue("""
                {
                  "identifier": "kiosk 3"
                }
                """, CreateAnonymousTokenRequest.class);

        // 3. The call
        var result = new AuthApi(client).createAnonymousToken(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 (CreateAnonymousToken needs no login)
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 client = Connect("");
var json = client.GetRequiredService<JsonSerializerOptionsProvider>().Options;

// 2. The request
var request = JsonSerializer.Deserialize<CreateAnonymousTokenRequest>("""
    {
      "identifier": "kiosk 3"
    }
    """, json);

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

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

// 1. Connect to BIM.works (CreateAnonymousToken needs no login)
const client = new Configuration({ basePath: "https://bim.works/openapi" });

// 2. The request
const request = CreateAnonymousTokenRequestFromJSON({
  "identifier": "kiosk 3"
});

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

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

use BIMworks\Api\AuthApi;
use BIMworks\Configuration;
use BIMworks\Model\CreateAnonymousTokenRequest;
use BIMworks\ObjectSerializer;

// 1. Connect to BIM.works (CreateAnonymousToken needs no login)
$client = (new Configuration())->setHost('https://bim.works/openapi');

// 2. The request
$request = ObjectSerializer::deserialize(<<<'JSON'
{
  "identifier": "kiosk 3"
}
JSON, CreateAnonymousTokenRequest::class);

// 3. The call
$result = (new AuthApi(config: $client))->createAnonymousToken($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 (CreateAnonymousToken needs no login)
client = bimworks.ApiClient(bimworks.Configuration(host="https://bim.works/openapi"))

# 2. The request
request = bimworks.CreateAnonymousTokenRequest.from_json(r"""
{
  "identifier": "kiosk 3"
}
""")

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

# 4. The result
print(json.dumps(client.sanitize_for_serialization(result), indent=2))
POST/openapi/auth/CreateAnonymousTokenCreateAnonymousToken reference
Authorization
Bearer <auth token>
Content-Type
application/json
Body
1 2 3 4
Authorization: Bearer <auth token>
Content-Type: application/json
Accept: application/json
curl -X POST "$BIMWORKS_URL/openapi/auth/CreateAnonymousToken" \
  -H "Authorization: Bearer $BIMWORKS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
  "identifier": "kiosk 3"
}'
Send to see the response

2. Log in with it#

LoginWithAnonymousToken takes the at- token and answers like every login: an auth object whose base64 field is the bearer string. The auth token lives one hour (auth.anonymous_token_validity); log in again when it expires, the token itself stays valid until an administrator deletes it.

Classic SDK
const token = localStorage.getItem("bimworks-anonymous-token");
const login = await bootstrap.client.post("BimRepository", "LoginWithAnonymousToken", {token}).execAsPromise();
const client = await factory.createClientWithAuth(login.auth);
OpenAPI SDK
import nl.bimbase.bimworks.sdk.api.AuthApi;
import nl.bimbase.bimworks.sdk.client.ApiClient;
import nl.bimbase.bimworks.sdk.model.LoginWithAnonymousTokenRequest;

public class Example {
    public static void main(String[] args) throws Exception {
        // 1. Connect to BIM.works (LoginWithAnonymousToken needs no login)
        ApiClient client = new ApiClient();
        client.updateBaseUri("https://bim.works/openapi");

        // 2. The request
        LoginWithAnonymousTokenRequest request = client.getObjectMapper().readValue("""
                {
                  "token": "at-..."
                }
                """, LoginWithAnonymousTokenRequest.class);

        // 3. The call
        var result = new AuthApi(client).loginWithAnonymousToken(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 (LoginWithAnonymousToken needs no login)
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 client = Connect("");
var json = client.GetRequiredService<JsonSerializerOptionsProvider>().Options;

// 2. The request
var request = JsonSerializer.Deserialize<LoginWithAnonymousTokenRequest>("""
    {
      "token": "at-..."
    }
    """, json);

// 3. The call
var response = await client.GetRequiredService<IAuthApi>().LoginWithAnonymousTokenAsync(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, LoginWithAnonymousTokenRequestFromJSON } from "@bimworks/sdk";

// 1. Connect to BIM.works (LoginWithAnonymousToken needs no login)
const client = new Configuration({ basePath: "https://bim.works/openapi" });

// 2. The request
const request = LoginWithAnonymousTokenRequestFromJSON({
  "token": "at-..."
});

// 3. The call
const result = await new AuthApi(client).loginWithAnonymousToken({ loginWithAnonymousTokenRequest: 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\LoginWithAnonymousTokenRequest;
use BIMworks\ObjectSerializer;

// 1. Connect to BIM.works (LoginWithAnonymousToken needs no login)
$client = (new Configuration())->setHost('https://bim.works/openapi');

// 2. The request
$request = ObjectSerializer::deserialize(<<<'JSON'
{
  "token": "at-..."
}
JSON, LoginWithAnonymousTokenRequest::class);

// 3. The call
$result = (new AuthApi(config: $client))->loginWithAnonymousToken($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 (LoginWithAnonymousToken needs no login)
client = bimworks.ApiClient(bimworks.Configuration(host="https://bim.works/openapi"))

# 2. The request
request = bimworks.LoginWithAnonymousTokenRequest.from_json(r"""
{
  "token": "at-..."
}
""")

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

# 4. The result
print(json.dumps(client.sanitize_for_serialization(result), indent=2))
POST/openapi/auth/LoginWithAnonymousTokenLoginWithAnonymousToken reference
Authorization
Bearer <auth token>
Content-Type
application/json
Body
1 2 3 4
Authorization: Bearer <auth token>
Content-Type: application/json
Accept: application/json
curl -X POST "$BIMWORKS_URL/openapi/auth/LoginWithAnonymousToken" \
  -H "Authorization: Bearer $BIMWORKS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
  "token": "at-...",
  "response_format": "base64"
}'
Send to see the response

Java and .NET have no typed method for either call; a backend in those languages obtains the auth object over HTTP and creates a client with createClientWithAuth (Classic Java SDK, Classic .NET SDK). In a browser page, register an expired-token handler that logs in again with the stored token (Refresh an expired token), so the hourly expiry never interrupts the user.

3. Work in the folder#

The client's root node is the token's own folder (a node under the instance's Ephimeral folder, named after the token's UUID). Upload into it, query, and view as with any other login; the node outlives the auth tokens. The token's user features are a copy of the instance defaults at creation time.

Check#

After the login, fs.getRootNodeUuid() (Fs) equals the root_node_uuid from step 1, and an upload into it succeeds. A token without the at- prefix, or an unknown one, fails the login with INVALID_ANONYMOUS_TOKEN; a deleted one with ANONYMOUS_TOKEN_DELETED.