Skip to content

UCIS Quickstart

Notes: for all this section, we use the following variables:

  • AUTH_URL: Specific to your project, it is provided by our support team.
  • UCIS_URL, UCIS_WS_URL: Specific to your project, it is provided by our support team.
  • YOUR_CLIENT_ID, YOUR_CLIENT_SECRET, USERNAME, PASSWORD: Provided by our support team, see Request a new account
  • SCOPES: See UCIS scopes

Request Access Rights

Request a new account

UCIS account have to be created by our support team. You will have to provide the following information:

  • Name
  • Email
  • Company
  • UCIS services you want to access, depend on the use case (partner's project and role) and submitted for validation from SOpra Steria Team.

You will receive an account with the following information:

  • Client ID : Company ID - this will be the same for all user of a same compagny.
  • Client Secret : Secret for the client, used to authenticate while retrieving the token.
  • Username : Username to use to retrieve token.
  • Password : Temporary password that need to be changed.

Manage an account

You can connect to <AUTH_URL>/auth/realms/UCIS/protocol/openid-connect/auth?client_id=account in order to manage your personnal account. In order to request more or different scope, or modify client secret, please contact our support team.

UCIS scopes

Scope of each API are listed in the OpenAPI or AsyncAPI pages (refer to "authorizations" section of each endpoint). Please refer to this scopes while requesting access.

OpenAPI AsyncAPI


Obtain a OAUTH2 Token

Once you have access rights, follow these sample to obtain a OAUTH2 token using REST API:

YOUR_TOKEN=$(curl -d "client_id=${YOUR_CLIENT_ID}" \
    -d "client_secret=${YOUR_CLIENT_SECRET}" \
    -d "username=${USERNAME}" \
    -d "password=${PASSWORD}" \
    -d "grant_type=password" \
    -d "scope=${SCOPES}" "${AUTH_URL}/auth/realms/UCIS/protocol/openid-connect/token" | jq -r '.access_token')
import requests

def get_auth_token():
    url = f"{AUTH_URL}/auth/realms/UCIS/protocol/openid-connect/token"
    payload = {
        'client_id': YOUR_CLIENT_ID,
        'client_secret': YOUR_CLIENT_SECRET,
        'grant_type': 'password',
        'username': USERNAME,
        'password': PASSWORD,
        'scope': SCOPE
    }
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}

    response = requests.post(url, data=payload, headers=headers)

    if response.status_code == 200:
        token = response.json().get('access_token')
        print('Token:', token)
        return token
    else:
        print('Failed to obtain token:', response.text)
        return None

YOUR_TOKEN = get_auth_token()
// Configuration
const authConfig = {
    url: '<AUTH_URL>',
    clientId: '<YOUR_CLIENT_ID>',
    clientSecret: '<YOUR_CLIENT_SECRET>', 
    username: '<USERNAME>',
    password: '<PASSWORD>',
    scope: '<SCOPES>'
};

async function getToken() {
    const tokenUrl = `${authConfig.url}/auth/realms/UCIS/protocol/openid-connect/token`;

    const params = new URLSearchParams();
    params.append('client_id', authConfig.clientId);
    params.append('username', authConfig.username);
    params.append('password', authConfig.password);
    params.append('grant_type', 'password');
    params.append('client_secret', authConfig.clientSecret);
    params.append('scope', authConfig.scope);

    try {
        const response = await fetch(tokenUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: params.toString()
        });

        if (!response.ok) {
            throw new Error('Network response was not ok');
        }

        const data = await response.json();
        console.log('Token:', data.access_token);

        return data.access_token;
    } catch (error) {
        console.error('Error fetching token:', error);
    }
}

getToken().then((token) => {
    const YOUR_TOKEN = token;
});

Using Maven, add the following dependencies:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.1</version>
</dependency>

Then:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class TokenExample {

    // Configuration
    private static final String AUTH_URL = "<AUTH_URL>";
    private static final String CLIENT_ID = "<YOUR_CLIENT_ID>";
    private static final String CLIENT_SECRET = "<YOUR_CLIENT_SECRET>"; 
    private static final String USERNAME = "<USERNAME>";
    private static final String PASSWORD = "<PASSWORD>";
    private static final String SCOPES = "<SCOPES>";

    public static void main(String[] args) {
        try {
            String token = getToken();
            System.out.println("Token: " + token);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String getToken() throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        URI tokenUri = new URI(AUTH_URL + "/auth/realms/UCIS/protocol/openid-connect/token");

        Map<Object, Object> data = new HashMap<>();
        data.put("client_id", CLIENT_ID);
        data.put("client_secret", CLIENT_SECRET);
        data.put("username", USERNAME);
        data.put("password", PASSWORD);
        data.put("grant_type", "password");
        data.put( "scope", SCOPES );

        HttpRequest request = HttpRequest.newBuilder()
                .uri(tokenUri)
                .header("Content-Type", "application/x-www-form-urlencoded")
                .POST(BodyPublishers.ofString(getFormDataAsString(data)))
                .build();

        HttpResponse<String> response = client.send(request, BodyHandlers.ofString());

        if (response.statusCode() == 200) {
            // Parse the JSON response to extract the access token
            String responseBody = response.body();
            String accessToken = extractTokenFromResponse(responseBody);
            return accessToken;
        } else {
            throw new RuntimeException("Failed to get token: " + response.body());
        }
    }

    private static String getFormDataAsString(Map<Object, Object> data) {
        return data.entrySet()
                .stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
    }

    private static String extractTokenFromResponse(String responseBody) {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(responseBody);
        return jsonNode.get("access_token").asText();
    }
}

Access UCIS APIs

REST APIs

Once you have an OAUTH2 Token, follow these steps to access UCIS REST API:

curl -X GET "${UCIS_URL}/v1/dops" \
    --header "Content-Type: application/json" \
    --header "Authorization: Bearer ${YOUR_TOKEN}"
import requests

headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer " + YOUR_TOKEN
}
resp = requests.get(UCIS_URL + "/v1/dops",
                    headers=headers)

print( "Data:", resp.json() )
fetch(UCIS_URL + "/v1/dops", {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + YOUR_TOKEN
}
}).then(response => {
    return response.json();
}).then(data => {
    console.log('Data:', data);
}).catch(error => {
    console.error('API request failed:', error);
});
private static final String UCIS_URL = "<UCIS_URL>";

private static String callApiWithToken(String token) throws Exception {
    HttpClient client = HttpClient.newHttpClient();
    URI apiUri = new URI(UCIS_URL + "/v1/dops");

    HttpRequest request = HttpRequest.newBuilder()
            .uri(apiUri)
            .header("Authorization", "Bearer " + token)
            .GET()
            .build();

    HttpResponse<String> response = client.send(request, BodyHandlers.ofString());

    if (response.statusCode() == 200) {
        return response.body();
    } else {
        throw new RuntimeException("Failed to call API: " + response.body());
    }
}

Websocket

Once you have an OAUTH2 Token, follow these steps to access UCIS REST API:

npm install -g wscat
wscat -c "${UCIS_WS_URL}/dops?bearer=${YOUR_TOKEN}"
from websockets import connect
import json
import asyncio


async def process(message):
    print(json.dumps(json.loads(message), indent=2))


async def main():
    full_url = f"{UCIS_WS_URL}/dops?bearer={YOUR_TOKEN}"
    print("Connecting to %s" % full_url)
    async with connect(full_url) as websocket:
        async for message in websocket:
            await process(message)

asyncio.run(main())

Use the ws librairy :

npm i ws
const WebSocket = require('ws');
let websocket;

function connectWebSocket() {
    const serverUrl = UCIS_WS_URL + "/dops?bearer=" + YOUR_TOKEN;
    websocket = new WebSocket(serverUrl);

    websocket.onopen = function(event) {
        console.log('WebSocket is open now.');
    };

    websocket.onclose = function(event) {
        console.log('WebSocket is closed now.');
    };

    websocket.onmessage = function(event) {
        console.log('Received:', message);
    };

    websocket.onerror = function(event) {
        console.error('WebSocket error observed:', event);
    };
}

Using Maven, add the following dependencies:

<dependency>
    <groupId>jakarta.websocket</groupId>
    <artifactId>jakarta.websocket-client-api</artifactId>
    <version>2.2.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.glassfish.tyrus.bundles</groupId>
    <artifactId>tyrus-standalone-client</artifactId>
    <version>2.0.0-M3</version>
</dependency>

Then:

import jakarta.websocket.ClientEndpoint;
import jakarta.websocket.CloseReason;
import jakarta.websocket.ContainerProvider;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.WebSocketContainer;

import java.net.URI;

@ClientEndpoint
public class WebSocketClient {

    private Session userSession = null;
    private static final String UCIS_WS_URL = "<UCIS_WS_URL>";

    @OnOpen
    public void onOpen(Session userSession) {
        this.userSession = userSession;
        System.out.println("Connected to server");
    }

    @OnClose
    public void onClose(Session userSession, javax.websocket.CloseReason reason) {
        this.userSession = null;
        System.out.println("Disconnected from server: " + reason.getReasonPhrase());
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("Received message: " + message);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.err.println("Error: " + throwable.getMessage());
    }

    public static void main(String[] args) {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        String uri = UCIS_WS_URL + "/dops?bearer=" + YOUR_TOKEN;
        try {
            container.connectToServer(WebSocketClient.class, URI.create(uri));
            System.out.println("Connecting to " + uri);
            // Keep the client running to listen to incoming messages
            Thread.sleep(Long.MAX_VALUE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Support

If you have any questions or issues, feel free to contact our support team.