Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 140 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ This repository contains the STACKIT SDKs for Java.

Requires Java 8 or higher.

The release artifacts of the STACKIT Java SDK are available on [Maven Central](https://central.sonatype.com/namespace/cloud.stackit.sdk).
The release artifacts of the STACKIT Java SDK are available on [Maven Central](https://central.sonatype.com/namespace/cloud.stackit.sdk).
See below how to use them in your Java project.

### Maven

Add the dependencies for the services you want to interact with to your project's POM, e.g. `iaas` and `resourcemanager` (replace `<SDK_VERSION>` with the latest version of each SDK submdoule):
Add the dependencies for the services you want to interact with to your project's POM, e.g. `iaas` and `resourcemanager` (replace `<SDK_VERSION>` with the latest version of each SDK submdoule):

```xml
<dependency>
Expand Down Expand Up @@ -59,6 +59,144 @@ Add the dependencies to your project's build file (replace `<SDK_VERSION>` with

Examples on services, configuration and authentication possibilities can be found in the [examples folder](https://github.com/stackitcloud/stackit-sdk-java/tree/main/examples).

## Authorization

To authenticate to the SDK, you will need a [service account](https://docs.stackit.cloud/stackit/en/service-accounts-134415819.html). Create it in the STACKIT Portal and assign it the necessary permissions, e.g. `project.owner`.

The Java SDK supports only Key flow for authentication.

When setting up authentication, the SDK will search for credentials in several locations, following a specific order:

1. Explicit configuration, e.g. by using the option `new CoreConfiguration().serviceAccountKeyPath("path/to/sa_key.json")`
2. Environment variable, e.g. by setting `STACKIT_SERVICE_ACCOUNT_KEY_PATH`
3. Credentials file

The SDK will check the credentials file located in the path defined by the `STACKIT_CREDENTIALS_PATH` env var, if specified,
or in `$HOME/.stackit/credentials.json` as a fallback.
The credentials file should be a json and each credential should be set using the name of the respective environment variable, as stated below in each flow. Example:

```json
{
"STACKIT_SERVICE_ACCOUNT_KEY_PATH": "path/to/sa_key.json",
"STACKIT_PRIVATE_KEY_PATH": "(OPTIONAL) when the private key isn't included in the Service Account key"
}
```

### Example

The following instructions assume that you have created a service account and assigned it the necessary permissions, e.g. `project.owner`.

To use the key flow, you need to have a service account key, which must have an RSA key-pair attached to it.

When creating the service account key, a new pair can be created automatically, which will be included in the service account key.
This will make it much easier to configure the key flow authentication in the SDK, by just providing the service account key.

> **Optionally**, you can provide your own private key when creating the service account key, which will then require you to also provide it explicitly to the SDK, additionally to the service account key.
> Check the STACKIT Knowledge Base for an [example of how to create your own key-pair](https://docs.stackit.cloud/stackit/en/usage-of-the-service-account-keys-in-stackit-175112464.html#UsageoftheserviceaccountkeysinSTACKIT-CreatinganRSAkey-pair).

To configure the key flow, follow this steps:

1. Create a service account key:
- Use the STACKIT Portal: go to the `Service Accounts` tab, choose a `Service Account` and go to `Service Account Keys` to create a key. For more details, see [Create a service account key](https://docs.stackit.cloud/stackit/en/create-a-service-account-key-175112456.html).
2. Save the content of the service account key by copying it and saving it in a JSON file. The expected format of the service account key is **JSON** with the following structure:

```json
{
"id": "uuid",
"publicKey": "public key",
"createdAt": "2023-08-24T14:15:22Z",
"validUntil": "2023-08-24T14:15:22Z",
"keyType": "USER_MANAGED",
"keyOrigin": "USER_PROVIDED",
"keyAlgorithm": "RSA_2048",
"active": true,
"credentials": {
"kid": "string",
"iss": "[email protected]",
"sub": "uuid",
"aud": "string",
"privateKey": "(OPTIONAL) private key when generated by the SA service"
}
}
```

3. Configure the service account key for authentication in the SDK by following one of the alternatives below:

- using the configuration options:

```java
CoreConfiguration config =
new CoreConfiguration()
...
.serviceAccountKeyPath("/path/to/service_account_key.json");

ResourceManagerApi api = new ResourceManagerApi(config);
```

- setting the environment variable: `STACKIT_SERVICE_ACCOUNT_KEY_PATH`
- setting `STACKIT_SERVICE_ACCOUNT_KEY_PATH` in the credentials file (see above)

> **Optionally, only if you have provided your own RSA key-pair when creating the service account key**, you also need to configure your private key (takes precedence over the one included in the service account key, if present). **The private key must be PEM encoded** and can be provided using one of the options below:
>
> - using the configuration options:
> ```java
> CoreConfiguration config =
> new CoreConfiguration()
> ...
> .privateKeyPath("/path/to/private_key.pem");
> ```
> - setting the environment variable: `STACKIT_PRIVATE_KEY_PATH`
> - setting `STACKIT_PRIVATE_KEY_PATH` in the credentials file (see above)

> **Alternatively, if you can't store the credentials in a file, e.g. when using it in a pipeline**, you can store the credentials in environment variables:
>
> - setting the environment variable `STACKIT_SERVICE_ACCOUNT_KEY` with the content of the service account key
> - (OPTIONAL) setting the environment variable `STACKIT_PRIVATE_KEY` with the content of the private key

4. The SDK will search for the keys and, if valid, will use them to get access and refresh tokens which will be used to authenticate all the requests.

Check the [authentication example](examples/authentication/src/main/java/cloud/stackit/sdk/authentication/examples/AuthenticationExample.java) for more details.

## Using custom endpoints

The example below shows how to use the STACKIT Java SDK in custom STACKIT enviroments.

```java
import cloud.stackit.sdk.core.config.CoreConfiguration;
import cloud.stackit.sdk.resourcemanager.api.ResourceManagerApi;
import cloud.stackit.sdk.resourcemanager.model.ListOrganizationsResponse;

import java.io.IOException;

class CustomEndpointExample {
public static void main(String[] args) {
CoreConfiguration config =
new CoreConfiguration()
.serviceAccountKey("/path/to/sa_key.json")
.customEndpoint("https://resource-manager.api.stackit.cloud")
.tokenCustomUrl("https://service-account.api.stackit.cloud/token");

try {
ResourceManagerApi resourceManagerApi = new ResourceManagerApi(config);

/* list all organizations */
ListOrganizationsResponse response =
resourceManagerApi.listOrganizations(
null,
"[email protected]",
null,
null,
null
);

System.out.println(response);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
```

## Reporting issues

If you encounter any issues or have suggestions for improvements, please open an issue in the repository or create a ticket in the [STACKIT Help Center](https://support.stackit.cloud/).
Expand Down
2 changes: 2 additions & 0 deletions examples/authentication/build.gradle
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
dependencies {
implementation project (':services:resourcemanager')
}

ext.mainClassName = 'cloud.stackit.sdk.authentication.examples.AuthenticationExample'
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,113 @@
import cloud.stackit.sdk.core.config.CoreConfiguration;
import cloud.stackit.sdk.resourcemanager.api.ResourceManagerApi;
import cloud.stackit.sdk.resourcemanager.model.ListOrganizationsResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

class AuthenticationExample {
public static void main(String[] args) {
String SERVICE_ACCOUNT_KEY_PATH = "/path/to/your/sa/key.json";
String SERVICE_ACCOUNT_MAIL = "[email protected]";
public static void main(String[] args) throws IOException {
///////////////////////////////////////////////////////
// Option 1: setting the paths to service account key (and private key) as configuration
///////////////////////////////////////////////////////
final String SERVICE_ACCOUNT_KEY_PATH = "/path/to/sa_key.json";
final String PRIVATE_KEY_PATH = "/path/to/private_key.pem";
final String SERVICE_ACCOUNT_MAIL = "[email protected]";

CoreConfiguration config =
new CoreConfiguration().serviceAccountKeyPath(SERVICE_ACCOUNT_KEY_PATH);
try {
ResourceManagerApi api =
new ResourceManagerApi(
new CoreConfiguration()
.serviceAccountKeyPath(SERVICE_ACCOUNT_KEY_PATH)
// Optional: if private key not included in service account key
.privateKeyPath(PRIVATE_KEY_PATH));

/* list all organizations */
ListOrganizationsResponse response =
api.listOrganizations(null, SERVICE_ACCOUNT_MAIL, null, null, null);

System.out.println(response);
} catch (Exception e) {
throw new RuntimeException(e);
}

///////////////////////////////////////////////////////
// Option 2: setting the service account key (and private key) as configuration
///////////////////////////////////////////////////////

// read key content from a file, in production you can also read it e.g. from STACKIT
// secrets manager, so it's only kept in-memory
String serviceAccountKeyPath = // replace it with the path to your service account key
"examples/authentication/src/main/java/cloud/stackit/sdk/authentication/examples/dummy_credentials/dummy-service-account-key.json";
File serviceAccountKeyFile = new File(serviceAccountKeyPath);
StringBuilder serviceAccountKeyContent = new StringBuilder();
try (Scanner myReader = new Scanner(serviceAccountKeyFile)) {
while (myReader.hasNextLine()) {
serviceAccountKeyContent.append(myReader.nextLine());
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}

String privateKeyPath = // replace it with the path to your private key
"examples/authentication/src/main/java/cloud/stackit/sdk/authentication/examples/dummy_credentials/dummy-private-key.pem";
File privateKeyFile = new File(privateKeyPath);
StringBuilder privateKeyContent = new StringBuilder();
try (Scanner myReader = new Scanner(privateKeyFile)) {
while (myReader.hasNextLine()) {
privateKeyContent.append(myReader.nextLine());
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}

String serviceAccountKey = serviceAccountKeyContent.toString();
String privateKey = privateKeyContent.toString();

try {
ResourceManagerApi api =
new ResourceManagerApi(
new CoreConfiguration()
.serviceAccountKey(serviceAccountKey)
// Optional: if private key not included in service account key
.privateKey(privateKey));

/* list all organizations */
ListOrganizationsResponse response =
api.listOrganizations(null, SERVICE_ACCOUNT_MAIL, null, null, null);

System.out.println(response);
} catch (Exception e) {
throw new RuntimeException(e);
}

///////////////////////////////////////////////////////
// Option 3: setting the service account key (and private key) as environment variable
///////////////////////////////////////////////////////
// Set the service account key via environment variable:
// - STACKIT_SERVICE_ACCOUNT_KEY_PATH=/path/to/sa_key.json
// - STACKIT_SERVICE_ACCOUNT_KEY="<content of service account key>"
//
// If the private key is not included in the service account key, set also:
// - STACKIT_PRIVATE_KEY_PATH=/path/to/private_key.pem
// - STACKIT_PRIVATE_KEY="<content of private key>"
//
// If no environment variable is set, fallback to credentials file in
// "$HOME/.stackit/credentials.json".
// Can be overridden with the environment variable `STACKIT_CREDENTIALS_PATH`
// The credentials file must be a json:
// {
// "STACKIT_SERVICE_ACCOUNT_KEY_PATH": "path/to/sa_key.json",
// "STACKIT_PRIVATE_KEY_PATH": "(OPTIONAL) when the private key isn't included in the
// Service Account key",
// // Alternative:
// "STACKIT_SERVICE_ACCOUNT_KEY": "<content of private key>",
// "STACKIT_PRIVATE_KEY": "(OPTIONAL) when the private key isn't included in the Service
// Account key",
// }
try {
ResourceManagerApi api = new ResourceManagerApi(config);
ResourceManagerApi api = new ResourceManagerApi();

/* list all organizations */
ListOrganizationsResponse response =
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-----BEGIN PRIVATE KEY-----
MIIJQw...ZL+U
...
lm+dqO...xQ8=
-----END PRIVATE KEY-----
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"id": "uuid",
"publicKey": "public key",
"createdAt": "2023-08-24T14:15:22Z",
"validUntil": "2023-08-24T14:15:22Z",
"keyType": "USER_MANAGED",
"keyOrigin": "USER_PROVIDED",
"keyAlgorithm": "RSA_2048",
"active": true,
"credentials": {
"kid": "string",
"iss": "[email protected]",
"sub": "uuid",
"aud": "string",
"privateKey": "(OPTIONAL) private key when generated by the SA service"
}
}