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

Log in with an API token

Create a client from an API token in JavaScript, Java, .NET, PHP or with a plain HTTP call, and know what the login gives you.

For every application that holds an API token: the first lines of code in each SDK. Logging in exchanges the token for an auth token that the client sends with every later call.

Before you start#

  • An API token (Create an API token).
  • The address of your instance, https://host[:port][/base-path], without a trailing slash.
  • The SDK installed (Install).

1. Create a factory#

The factory holds the address and the connection settings and is meant to live as long as your application; one per BIM.works instance you talk to.

2. Log in#

Classic SDK
import {BimWorksClientFactory} from "@bimworks/jssdk";

const factory = new BimWorksClientFactory("https://bim.works");
const client = await factory.createClientWithApiToken("<your API token>");
import nl.bimbase.bimworks.client.BimWorksClient;
import nl.bimbase.bimworks.client.BimWorksClientFactory;

try (BimWorksClientFactory factory = new BimWorksClientFactory("https://bim.works")) {
	try (BimWorksClient client = factory.createClientWithApiToken("<your API token>")) {
		// use the client
	}
}
using System;
using BIM.works_SDK;

using (BimWorksClientFactory factory = new BimWorksClientFactory(new Uri("https://bim.works")))
using (BimWorksClient client = factory.CreateClientWithApiToken("<your API token>"))
{
    // use the client
}
OpenAPI SDK
import nl.bimbase.bimworks.sdk.api.AuthApi;
import nl.bimbase.bimworks.sdk.client.ApiClient;
import nl.bimbase.bimworks.sdk.model.LoginWithApiTokenRequest;

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

        // 2. The request
        LoginWithApiTokenRequest request = client.getObjectMapper().readValue("""
                {
                  "token": "<your API token>"
                }
                """, LoginWithApiTokenRequest.class);

        // 3. The call
        var result = new AuthApi(client).loginWithApiToken(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 (LoginWithApiToken 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<LoginWithApiTokenRequest>("""
    {
      "token": "<your API token>"
    }
    """, json);

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

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

// 2. The request
const request = LoginWithApiTokenRequestFromJSON({
  "token": "<your API token>"
});

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

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

// 2. The request
$request = ObjectSerializer::deserialize(<<<'JSON'
{
  "token": "<your API token>"
}
JSON, LoginWithApiTokenRequest::class);

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

# 2. The request
request = bimworks.LoginWithApiTokenRequest.from_json(r"""
{
  "token": "<your API token>"
}
""")

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

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

The factory method is createClientWithApiToken in JavaScript (Classic JavaScript SDK) and Java (Classic Java SDK) and CreateClientWithApiToken in .NET (Classic .NET SDK); the PHP client calls AuthApi::loginWithApiToken (PHP SDK). Java's and .NET's factory and client are AutoCloseable/IDisposable: close a client you no longer use, it holds a WebSocket connection.

With plain HTTP the operation is LoginWithApiToken. Ask for the base64 response format to receive the bearer token as a string, and send it in the Authorization header of every later call:

POST/openapi/auth/LoginWithApiTokenLoginWithApiToken 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/LoginWithApiToken" \
  -H "Authorization: Bearer $BIMWORKS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
  "token": BIM_WORKS_API_TOKEN,
  "response_format": "base64"
}'
Send to see the response

Without response_format the reply is the full auth object (input, hmac, hmh, base64); the base64 field is the same string.

3. Know what you got#

  • A root node. The client sees the node the token was created on and everything below it, nothing else; paths such as /Project A/house.ifc are relative to it. fs.getRootNodeUuid() returns it.
  • The token's scopes. A call outside them fails with NON_AUTHORIZED_SCOPE.
  • An auth token valid for 90 days (the instance setting auth.api_token_validity), but never beyond the API token's own expiry date. A long-running Java or .NET process creates a new client when its auth token has expired; a browser can do that automatically (Refresh an expired token). For a shorter one, the LoginWithApiToken task (not yet the HTTP operation) takes expires_seconds: a sign-in handed to another device, such as the phone link of Annotations to mobile.
  • Every request is checked against the token again, so deleting or rotating the token in the UI cuts off running clients at once.
Note

The login fails with INVALID_API_TOKEN for an unknown secret, API_TOKEN_DELETED for a deleted one and API_TOKEN_EXPIRED after its expires_on. Repeated failures from one address are throttled and then answer INVALID_API_TOKEN regardless of the secret.

Check#

Ask for the root node; the UUID is the folder the token was created on:

Classic SDK
console.log(await client.fs.getRootNodeUuid());
System.out.println(client.fs.getRootNodeUuid());
Console.WriteLine(client.Fs.GetRootNodeUuid());
OpenAPI SDK
import nl.bimbase.bimworks.sdk.api.AuthApi;
import nl.bimbase.bimworks.sdk.api.FsApi;
import nl.bimbase.bimworks.sdk.client.ApiClient;
import nl.bimbase.bimworks.sdk.model.Auth;
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
        // (GetRootNodeUuid takes no request)

        // 3. The call
        var result = new FsApi(client).getRootNodeUuid();

        // 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
// (GetRootNodeUuid takes no request)

// 3. The call
var response = await client.GetRequiredService<IFsApi>().GetRootNodeUuidAsync();

// 4. The result
var result = response.Ok() ?? throw new HttpRequestException(response.RawContent, null, response.StatusCode);
Console.WriteLine(JsonSerializer.Serialize(result, json));
import { AuthApi, Configuration, FsApi } 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
// (GetRootNodeUuid takes no request)

// 3. The call
const result = await new FsApi(client).getRootNodeUuid();

// 4. The result
console.log(result);
<?php
require __DIR__ . '/vendor/autoload.php';

use BIMworks\Api\AuthApi;
use BIMworks\Api\FsApi;
use BIMworks\Configuration;
use BIMworks\Model\LoginWithApiTokenRequest;

// 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
// (GetRootNodeUuid takes no request)

// 3. The call
$result = (new FsApi(config: $client))->getRootNodeUuid();

// 4. The result
echo $result, 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
# (GetRootNodeUuid takes no request)

# 3. The call
result = bimworks.FsApi(client).get_root_node_uuid()

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

getRootNodeUuid is on the file system API of each SDK: Fs, FileSystemApi, Fs, FsApi in PHP SDK; the HTTP operation is GetRootNodeUuid.