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

Log in with a username and password

Log in with an account's credentials for development and testing, and know why production code uses an API token instead.

For trying the API from a development machine with the account you also use in the UI. Every SDK supports it; production code should use an API token instead, which is revocable, scoped to one folder and not tied to a person's password.

Before you start#

  • A BIM.works account whose e-mail address is validated. An unvalidated account cannot log in (EMAIL_ADDRESS_NOT_VALIDATED).
  • An account without two-factor authentication. With it, the password step answers a twofa challenge that the SDKs do not complete; use an API token for such accounts.

1. Log in#

Classic SDK
const factory = new BimWorksClientFactory("https://bim.works");
const client = await factory.createClientWithUsernamePassword("you@example.com", "your password");
try (BimWorksClientFactory factory = new BimWorksClientFactory("https://bim.works");
		BimWorksClient client = factory.createClientWithUsernamePassword("you@example.com", "your password")) {
	// use the client
}
using (BimWorksClientFactory factory = new BimWorksClientFactory(new Uri("https://bim.works")))
using (BimWorksClient client = factory.CreateClientWithUsernamePassword("you@example.com", "your password"))
{
    // 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.LoginWithUsernamePasswordRequest;

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

        // 2. The request
        LoginWithUsernamePasswordRequest request = client.getObjectMapper().readValue("""
                {
                  "username": "you@example.com",
                  "password": "your password"
                }
                """, LoginWithUsernamePasswordRequest.class);

        // 3. The call
        var result = new AuthApi(client).loginWithUsernamePassword(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 (LoginWithUsernamePassword 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<LoginWithUsernamePasswordRequest>("""
    {
      "username": "you@example.com",
      "password": "your password"
    }
    """, json);

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

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

// 2. The request
const request = LoginWithUsernamePasswordRequestFromJSON({
  "username": "you@example.com",
  "password": "your password"
});

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

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

// 2. The request
$request = ObjectSerializer::deserialize(<<<'JSON'
{
  "username": "you@example.com",
  "password": "your password"
}
JSON, LoginWithUsernamePasswordRequest::class);

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

# 2. The request
request = bimworks.LoginWithUsernamePasswordRequest.from_json(r"""
{
  "username": "you@example.com",
  "password": "your password"
}
""")

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

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

The factory method is createClientWithUsernamePassword (Classic JavaScript SDK, Classic Java SDK) or CreateClientWithUsernamePassword (Classic .NET SDK); PHP calls AuthApi::loginWithUsernamePassword (PHP SDK). The HTTP operation is LoginWithUsernamePassword; it also returns the bearer token in the Authorization response header:

POST/openapi/auth/LoginWithUsernamePasswordLoginWithUsernamePassword 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/LoginWithUsernamePassword" \
  -H "Authorization: Bearer $BIMWORKS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
  "username": "you@example.com",
  "password": "your password",
  "response_format": "base64"
}'
Send to see the response

2. Know what you got#

  • The auth token lives 7 days (auth.username_password_token_validity); the UI's "remember me" variant lives 90 days.
  • The root node is the account's own folder; organisation folders the account can see are listed under it.
  • The scopes are the account's, so the token can do everything you can do in the UI, including creating API tokens and delegated tokens.
  • A wrong password, an unknown address or a deleted account all answer AuthenticationError.INVALID_LOGIN (a deleted account ACCOUNT_DELETED), and repeated failures are throttled per account and per address.
Warning

The username is an e-mail address and the password is the one you type in the UI. Do not put them in a configuration file that ships with an application; create an API token on the folder the application needs and give it that (Create an API token).

Check#

Classic SDK
const root = await client.fs.getNodeByPath("/");
console.log(root.name);   // your account's folder
System.out.println(client.fs.getRootNode().getName());
Console.WriteLine(client.Fs.GetRootNode().Name);
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.GetNodeRequest;
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
        GetNodeRequest request = client.getObjectMapper().readValue("""
                {
                  "path": "/"
                }
                """, GetNodeRequest.class);

        // 3. The call
        var result = new FsApi(client).getNode(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<GetNodeRequest>("""
    {
      "path": "/"
    }
    """, json);

// 3. The call
var response = await client.GetRequiredService<IFsApi>().GetNodeAsync(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, FsApi, GetNodeRequestFromJSON, NodeToJSON } 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 = GetNodeRequestFromJSON({
  "path": "/"
});

// 3. The call
const result = await new FsApi(client).getNode({ getNodeRequest: request });

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

use BIMworks\Api\AuthApi;
use BIMworks\Api\FsApi;
use BIMworks\Configuration;
use BIMworks\Model\GetNodeRequest;
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'
{
  "path": "/"
}
JSON, GetNodeRequest::class);

// 3. The call
$result = (new FsApi(config: $client))->getNode($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.GetNodeRequest.from_json(r"""
{
  "path": "/"
}
""")

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

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

The root node's name is your account's folder name. The calls: getNodeByPath/getRootNode on Fs, FileSystemApi and Fs, FsApi::getNode in PHP SDK, GetNode over HTTP.