Milesoft Accounts SDK (accounts-sdk)

1. Overview

The Accounts SDK (accounts-sdk) provides a strongly-typed programmatic interface to the identity, tenant management, and authentication engine of the Milesoft platform. Key capabilities include authenticating actors, managing user roles and profiles, configuring custom user classifications, resolving system identifiers, administering subscriber accounts, registering third-party OAuth integrations, and issuing secure nonces.


2. Initialization

2.1 Dependency Installation

The accounts-sdk package is hosted in our secure Google Cloud Artifact Registry repository.

To consume accounts-sdk in your Spring Boot application, apply the Google Cloud Artifact Registry plugin and declare our secure repository in your build.gradle:

plugins {
    id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.5"
}

repositories {
    mavenCentral()
    maven { url "artifactregistry://us-west2-maven.pkg.dev/milesoft-repo/repo-maven" }
}

dependencies {
    // Declaring the standard accounts-sdk library dependency
    implementation "io.milesoft:accounts-sdk:2.1.0"
}

2.2 Central Spring Boot Configuration

The SDK components are designed for easy injection within Spring-managed applications. Instantiation requires a PlatformClient (specifying base endpoint URL and platform API key) and a PlatformTokenProvider that handles token propagation securely.

import io.milesoft.accounts.client.v2.AccountClient;
import io.milesoft.accounts.client.v2.AppClient;
import io.milesoft.accounts.client.v2.AuthClient;
import io.milesoft.accounts.client.v2.IdClient;
import io.milesoft.accounts.client.v2.NonceClient;
import io.milesoft.accounts.client.v2.OauthClient;
import io.milesoft.accounts.client.v2.ProfileClient;
import io.milesoft.accounts.client.v2.TypeClient;
import io.milesoft.accounts.client.v2.UserClient;
import io.milesoft.clients.PlatformClient;
import io.milesoft.clients.strategy.PlatformTokenProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AccountsSdkConfig {

    private final PlatformClient platformClient;
    private final PlatformTokenProvider tokenProvider;
    private final AuthClient authClient;
    private final AppClient appClient;
    private final AccountClient accountClient;
    private final UserClient userClient;
    private final ProfileClient profileClient;
    private final IdClient idClient;
    private final NonceClient nonceClient;
    private final OauthClient oauthClient;
    private final TypeClient typeClient;

    public AccountsSdkConfig(@Value("${milesoft.accounts.baseUrl}") String baseUrl, 
                             @Value("${milesoft.apiKey}") String apiKey) {
        
        // Initialize underlying communication layer
        this.platformClient = new PlatformClient(baseUrl, apiKey);
        this.tokenProvider = new PlatformTokenProvider(platformClient);
        
        // Instantiate specific service clients
        this.authClient = new AuthClient(baseUrl, tokenProvider);
        this.appClient = new AppClient(baseUrl, tokenProvider);
        this.accountClient = new AccountClient(baseUrl, tokenProvider);
        this.userClient = new UserClient(baseUrl, tokenProvider);
        this.profileClient = new ProfileClient(baseUrl, tokenProvider);
        this.idClient = new IdClient(baseUrl, tokenProvider);
        this.nonceClient = new NonceClient(baseUrl, tokenProvider);
        this.oauthClient = new OauthClient(baseUrl, tokenProvider);
        this.typeClient = new TypeClient(baseUrl, tokenProvider);
    }

    @Bean
    public PlatformClient platformClient() { return platformClient; }

    @Bean
    public AuthClient authClient() { return authClient; }

    @Bean
    public AppClient appClient() { return appClient; }

    @Bean
    public AccountClient accountClient() { return accountClient; }

    @Bean
    public UserClient userClient() { return userClient; }

    @Bean
    public ProfileClient profileClient() { return profileClient; }

    @Bean
    public IdClient idClient() { return idClient; }

    @Bean
    public NonceClient nonceClient() { return nonceClient; }

    @Bean
    public OauthClient oauthClient() { return oauthClient; }

    @Bean
    public TypeClient typeClient() { return typeClient; }
}

3. Core SDK Clients & Method Specifications

Programmatic execution is split across logical client wrappers which completely abstract the underlying REST layer.

3.1 AuthClient

Manages token issuance, active sessions, and password lifecycle routines.

  • LoggedIn login(Login payload): Executes email/password credentials verification.
  • LoggedIn loginGoogle(GoogleLogin payload): Performs SSO via Google Sign-In ID Token.
  • LoggedIn loginGuest(GuestLogin payload): Spawns a transient guest session.
  • LoggedIn refresh(String refreshToken): Renews an expired access token using a long-lived refresh token.
  • void revoke(RevokeSession payload): Explicitly terminates and invalidates a refresh session.
  • Accounts listAccounts(Actor actor): Discovers tenant accounts authorized for the acting user context.
  • LoggedIn switchAccount(SwitchAccounts payload, Actor actor): Swaps the active subscriber context, returning an updated JWT.
  • void updatePassword(ChangePassword payload, Actor actor): Updates the password of the active user.
  • void forgotPassword(ForgotPassword payload): Triggers a secure recovery token to user communication channels.
  • void recoverPassword(RecoverPassword payload): Sets a new password via a verified recovery token.
  • Nonce requestLinkCode(RequestLinkCode payload): Requests a link code to pair alternative sessions or hardware devices.
  • LoggedIn submitLinkCode(SubmitLinkCode payload): Submits link code to establish a paired active session.

3.2 AccountClient

Manages subscriber tenant accounts, custom portal configurations, and metadata branding.

  • MyAccount load(Actor actor): Returns detailed active tenant configuration (MyAccount).
  • MyAccount update(SaveMyAccount payload, Actor actor): Modifies primary settings, company links, and branding hexes.
  • Account join(JoinAccount payload): Joins an existing subscriber account via a validation registration code.
  • LoggedIn joinAdditional(JoinAdditionalAccount payload, Actor actor): Chains another account context to an active user portfolio.

3.3 AppClient

Administers base application context parameters.

  • MyApp load(): Retrives active application configuration mapping.
  • Version getVersion(): Resolves compile version metrics.
  • Ads getAds(): Retrieves active promotional assets.

3.4 UserClient

Handles standard provisioning, profile scoping, and team administrators.

  • Users list(String cursor, Integer limit, Actor actor): Paged retrieval of tenant users.
  • Users listAdmins(Actor actor): Retrieves list of tenant system administrators.
  • Users listRemoved(Actor actor): Identifies soft-deleted team records.
  • User find(String emailOrAlias, Actor actor): Queries an individual user profile.
  • Users loadBulk(Ids payload, Actor actor): Performs high-efficiency batch loading from user ID arrays.
  • User create(CreateUser payload, Actor actor): Provisions and registers a new pending user under the tenant scope.
  • User update(String userId, SaveUser payload, Actor actor): Modifies roles, types, and settings of a managed user.
  • void delete(String userId, Actor actor): Soft-deletes a team member from active rosters.
  • void reinvite(String userId, Actor actor): Re-issues invitation notifications to pending registrations.

3.5 ProfileClient

Enables users to manage their own digital identity settings.

  • Profile load(Actor actor): Loads detailed active user context.
  • Profile update(SaveProfile payload, Actor actor): Modifies nicknames, surnames, and picture references.
  • Profile acceptEula(Actor actor): Signs EULA acceptance records with current timestamps.

3.6 TypeClient

Classifies standard authorization groups and default roles.

  • Types list(String cursor, Integer limit, Actor actor): Lists active classification structures.
  • Type create(SaveType payload, Actor actor): Appends custom user classification type.
  • Type update(String typeId, SaveType payload, Actor actor): Updates default roles and classifications.
  • void delete(String typeId, Actor actor): Removes custom classification rules.

3.7 NonceClient

Manages single-use secure cryptographically generated identifiers.

  • Nonce create(SaveNonce payload, Actor actor): Registers transient session nonces.
  • Nonce consume(String nonceId): Verifies and invalidates requested single-use nonces.

3.8 OauthClient

Connects first-party workflows to third-party secure providers (Salesforce, QuickBooks).

  • OauthIntegrations listIntegrations(String cursor, Integer limit, Actor actor): Lists configured third-party integrations.
  • OauthIntegration createIntegration(SaveOauthIntegration payload, Actor actor): Registers redirect credentials and permissions.
  • OauthIntegration updateIntegration(String id, SaveOauthIntegration payload, Actor actor): Updates configuration mappings.
  • void deleteIntegration(String id, Actor actor): Purges registered provider settings.
  • OauthTokens getTokens(String integrationId, Actor actor): Loads valid tokens for provider execution.
  • OauthTokens saveTokens(SaveOauthTokens payload, Actor actor): Registers/updates OAuth token credential scopes.
  • void deleteTokens(String integrationId, Actor actor): Revokes and purges active integration tokens.

4. Built-In SDK Capabilities

Under the hood, the SDK implements several enterprise resilience patterns automatically:

  • Automatic Token Refreshing: Integrated PlatformTokenProvider checks token validity periods prior to request execution. If a JWT is nearing expiry, it executes a silent renew cycle before issuing the user's call.
  • Actor Context Propagation: Every active state modification requires an explicit Actor instance. This parameter ensures downstream operations are securely audited under valid corporate security policies.
  • Connection Pooling & Retry Engine: Thread-safe HTTP connection clients manage reuse policies, and automatically apply exponential backoff on intermittent system failures (503 Service Unavailable, connection limits).

5. Code Examples

5.1 Programmatic Login & Tenant Switch

import io.milesoft.accounts.client.v2.AuthClient;
import io.milesoft.accounts.client.v2.dto.Login;
import io.milesoft.accounts.client.v2.dto.LoggedIn;
import io.milesoft.accounts.client.v2.dto.SwitchAccounts;
import io.milesoft.primitives.actor.Actor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AuthenticationService {

    private final AuthClient authClient;

    @Autowired
    public AuthenticationService(AuthClient authClient) {
        this.authClient = authClient;
    }

    public LoggedIn performLoginAndContextSwap(String email, String password, String targetAccountId) {
        // Authenticate base user credentials
        Login login = new Login();
        login.setEmail(email);
        login.setPassword(password);
        
        LoggedIn session = authClient.login(login);
        System.out.println("Authenticated! Session JWT: " + session.getAccessToken());

        // Construct context-swap scope
        SwitchAccounts swap = new SwitchAccounts();
        swap.setAccountId(targetAccountId);
        
        // Propagate current user context as Actor
        Actor actor = Actor.builder()
            .userId(session.getProfile().getId())
            .accessToken(session.getAccessToken())
            .build();

        return authClient.switchAccount(swap, actor);
    }
}

5.2 Team Provisioning

import io.milesoft.accounts.client.v2.UserClient;
import io.milesoft.accounts.client.v2.dto.CreateUser;
import io.milesoft.accounts.client.v2.dto.User;
import io.milesoft.primitives.actor.Actor;
import org.springframework.stereotype.Component;
import java.util.List;

@Component
public class ProvisioningEngine {

    private final UserClient userClient;

    public ProvisioningEngine(UserClient userClient) {
        this.userClient = userClient;
    }

    public User provisionNewOperator(Actor managerActor, String firstName, String lastName, String email) {
        CreateUser operator = new CreateUser();
        operator.setFirstName(firstName);
        operator.setLastName(lastName);
        operator.setEmail(email);
        operator.setRoles(List.of("OPERATOR"));
        
        // Execute SDK request under Manager identity
        return userClient.create(operator, managerActor);
    }
}

6. SDK Data Transfer Objects (DTOs)

LoggedIn

Returned during successful authentication.

Field Type Description / Constraints
accessToken String Secure JSON Web Token (JWT) authorizing API calls. Required / Not Blank.
refreshToken String Long-lived session renewal token.
accounts Accounts Structure of accessible tenant accounts.

Accounts

Encapsulates account list structures and paginated positions.

Field Type Description / Constraints
accounts List<Account> Collection of tenant details. Required.
cursor String Continuation token.

Account

Client-facing summary of a tenant account.

Field Type Description / Constraints
id String System-assigned UUID of the tenant. Required.
status AccountStatus Lifecycle setting: Active or Disabled. Required.
name String Descriptive name of the subscriber tenant. Required.
website String Main URL associated with the tenant company.
branding Branding Aesthetic customization parameters. Required.
created ZonedDateTime Timestamp of entity provisioning. Required.
updated ZonedDateTime Timestamp of latest entity modification. Required.

Branding

Holds customization configurations for customer portals.

Field Type Description / Constraints
logoUrl String Media URL link targeting company branding images.
logoContainsName Boolean Flag indicating if visual text is present inside the image.
primaryColor String Core hex color value (e.g., #FF5733). Required.
secondaryColor String Secondary accent hex color value. Required.

MyAccount

Returned when a logged-in user requests their own active tenant configurations.

Field Type Description / Constraints
id String UUID of the tenant. Required.
status AccountStatus Lifecycle setting: Active or Disabled. Required.
name String Name of the subscriber tenant. Required.
website String Main URL associated with the tenant company.
branding Branding Aesthetic customization parameters. Required.
code String Transient invite code used for registration. Excluded from toString logging.
settings Map<String, Object> Custom metadata or setting configurations mapped to keys.
created ZonedDateTime Timestamp of entity provisioning. Required.
updated ZonedDateTime Timestamp of latest entity modification. Required.

SaveMyAccount

Request payload used to update tenant-specific variables.

Field Type Description / Constraints
name String Name of the subscriber tenant. Required / Not Blank.
website String Main URL associated with the tenant company.
branding Branding Aesthetic customization parameters. Required.
allowJoin Boolean Flag to configure if external callers can self-join. Required.
settings Map<String, Object> Key/value custom configurations.

User

Main user model.

Field Type Description / Constraints
id String System-assigned UUID of the user. Required.
firstName String Given name of the user.
lastName String Surname of the user.
alias String Unique nickname or handle within the ecosystem.
email String Primary email contact.
phone String Primary phone contact.
imageUrl String Profile picture thumbnail URL.
birthday LocalDate User's birthday format: YYYY-MM-DD.
typeId String System user type index pointer.
pending Boolean Flag indicating if user is awaiting invitation acceptance. Required.
roles List<String> Assigned security roles and scopes.
settings Map<String, Object> User personal configuration key/value pairs.
created ZonedDateTime Timestamp of profile registration. Required.
updated ZonedDateTime Timestamp of latest profile update. Required.

CreateUser

Payload used to provision a new user under a tenant.

Field Type Description / Constraints
firstName String Given name of the user.
lastName String Surname of the user.
alias String Nickname or handle within the ecosystem.
email String Primary email address. Required / Not Blank.
phone String Mobile phone contact.
imageUrl String Profile picture resource URL.
birthday LocalDate Birth date format: YYYY-MM-DD.
password String Initial password. Excluded from toString logging.
typeId String System user type reference.
roles List<String> Security scopes. Required (Size >= 1).
settings Map<String, Object> Custom user options.

SaveUser

Payload used to modify an existing user profile's settings or security scopes.

Field Type Description / Constraints
firstName String Given name of the user.
lastName String Surname of the user.
alias String Unique nickname or handle within the ecosystem.
email String Primary contact channel. Required / Not Blank.
phone String Mobile phone contact.
imageUrl String Profile picture resource URL.
birthday LocalDate Birth date format: YYYY-MM-DD.
typeId String System user type reference.
roles List<String> Security scopes. Required (Size >= 1).
settings Map<String, Object> Custom user options.

Profile

User profile record.

Field Type Description / Constraints
id String UUID of the user. Required.
firstName String Given name of the user.
lastName String Surname of the user.
alias String Unique nickname or handle within the ecosystem.
email String Primary contact email. Required.
phone String Mobile phone contact.
imageUrl String Profile picture resource URL.
birthday LocalDate Birth date format: YYYY-MM-DD.
google Boolean Flag indicating if account registration uses Google OAuth. Required.
temporary Boolean Flag indicating if this is a transient guest session. Required.
settings Map<String, Object> Custom metadata or preferences.
eula ZonedDateTime Timestamp of EULA acceptance.
created ZonedDateTime Timestamp of profile registration. Required.
updated ZonedDateTime Timestamp of latest profile update. Required.

SaveProfile

Request payload used to modify the caller's personal profile information.

Field Type Description / Constraints
firstName String Given name of the user.
lastName String Surname of the user.
alias String Unique nickname or handle within the ecosystem.
email String Electronic mail channel. Required / Not Blank.
phone String Mobile phone contact.
imageUrl String Profile picture thumbnail URL.
birthday LocalDate Birth date format: YYYY-MM-DD.
settings Map<String, Object> Personal setting preferences.

Nonce

Temporary cryptographically random single-use identifier.

Field Type Description / Constraints
id String Secure random string. Excluded from toString logging. Required.
metadata Map<String, Object> Custom contextual values associated with the nonce.
created ZonedDateTime Nonce creation timestamp. Required.
updated ZonedDateTime Nonce modification/validation timestamp. Required.

SaveNonce

Payload to provision private nonces.

Field Type Description / Constraints
metadata Map<String, Object> Metadata associated with the transient session.

Type

System classification of a user type, holding default associated role bindings.

Field Type Description / Constraints
id String UUID of the classification. Required.
title String Label name. Required.
description String Descriptive documentation of permissions.
roles List<String> Baseline roles automatically granted to users of this type.
created ZonedDateTime Creation timestamp. Required.
updated ZonedDateTime Last update timestamp. Required.

SaveType

Payload to save system-level user types.

Field Type Description / Constraints
title String Label name of the user classification type. Required / Not Blank.
description String Description of classification.
roles List<String> Baseline roles assigned to users of this type.

OauthIntegration

Holds third-party OAuth provider connection configurations.

Field Type Description / Constraints
id String System UUID of the integration mapping. Required.
title String Descriptive name (e.g., Salesforce-Prod). Required.
authUrl String Target authorization redirect URI. Required.
tokenUrl String Backend OAuth token exchange endpoint. Required.
redirectUrl String Application callback handler endpoint. Required.
clientId String Public provider client identifier. Required.
scope String Requested access scopes (space-delimited). Required.
type OauthType Identifier classification (e.g. Account, User). Required.
environment Environment Targeted stage classification (Production, Sandbox). Required.
ephemeral Boolean Configures if credentials expire immediately. Required.
parameters List<Parameter> Custom metadata parameter list.
created ZonedDateTime Registration timestamp. Required.
updated ZonedDateTime Latest modification timestamp. Required.

OauthTokens

Credentials representing an active third-party connection session.

Field Type Description / Constraints
integrationId String ID of the target OauthIntegration provider settings. Required / Not Blank.
accessToken String Third-party secure access token. Excluded from generic logs.
refreshToken String Third-party secure refresh token. Excluded from generic logs.
expiresAt ZonedDateTime Expiry instant.
metadata Map<String, Object> Provider-specific context.
created ZonedDateTime Integration handshake timestamp. Required.
updated ZonedDateTime Latest credential swap/refresh timestamp. Required.