Authorization in Java SDK

This documentation provides an overview of how to configure and authorize requests to the Aspose Barcode Cloud API using JWT and external authorization methods. It covers key code examples and settings needed to enable secure and authorized API requests.

Note: For manage authorization you should have a Client Id and Client Secret. How to get it described in Quick Start Section

Overview

Aspose Barcode Cloud API supports two main authorization methods:

  • JWT (JSON Web Token) - Allows token-based authentication where tokens are obtained using Client Id and Client Secret.
  • External Authorization - Permits manual setting of JWT tokens for custom authorization.

JWT Authorization

When using JWT, the API classes automatically obtains a token and includes it in each API request.

Setting Up JWT Authorization

To set up JWT authorization, specify the ClientId and ClientSecret:

ApiClient client =
                new ApiClient(
                        "<Your-Client-Id>",
                        "<Your-Client-Secret>");

GenerateApi generateApi = new GenerateApi(client);

Upon setup, the internal SDK methods handles token generation and token refresh:

  • The RequestToken method requests a token using ClientId and ClientSecret.
  • The token is added to the Authorization header for each request.

External Authorization

External authorization allows you to manually manage tokens. Assign your JWT token directly to AccessToken and leave ClientId and ClientSecret blank.

Setting Up External Authorization

Example configuration with External Authorization:

ApiClient client =
                new ApiClient("<Your-External-Jwt-Token>");
                       
                RecognizeApi recognizeApi = new RecognizeApi(client);

In this mode, the API sends the provided JWT in the Authorization header without attempting to generate or refresh the token.

How to Fetch a Token without SDK Internal Methods

To fetch a new token, send a POST request to https://id.aspose.cloud/connect/token with the application/x-www-form-urlencoded content type. In the request body, specify the following parameters:

grant_type=client_credentials
client_id=<Your-Client-Id>
client_secret=<Your-Client-Secret>

A Code example for fetching token:

package com.aspose.barcode.cloud.snippets;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.stream.Collectors;

public class ManualFetchToken {
    public static void main(String[] args) {

        String clientId = "Client Id from https://dashboard.aspose.cloud/applications";
        String clientSecret = "Client Secret from https://dashboard.aspose.cloud/applications";

        // Check the client_id is changed to not break GitHub CI pipeline
        if (clientId.startsWith("Client Id")) {
            System.out.println("client_id not configured. Skip this snippet test");
            return;
        }

        HttpClient client = HttpClient.newHttpClient();

        // Form the payload
        String form =
                Map.of(
                                "grant_type", "client_credentials",
                                "client_id", clientId,
                                "client_secret", clientSecret)
                        .entrySet()
                        .stream()
                        .map(
                                entry ->
                                        URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8)
                                                + "="
                                                + URLEncoder.encode(
                                                        entry.getValue(), StandardCharsets.UTF_8))
                        .collect(Collectors.joining("&"));

        HttpRequest request =
                HttpRequest.newBuilder()
                        .uri(URI.create("https://id.aspose.cloud/connect/token"))
                        .header("Content-Type", "application/x-www-form-urlencoded")
                        .POST(BodyPublishers.ofString(form))
                        .build();

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

            if (response.statusCode() == 200) {

                JsonObject data = JsonParser.parseString(response.body()).getAsJsonObject();
                String token = data.get("access_token").getAsString();
                System.out.println("Token reciewed successfully.");

                // Uncomment next line to view token
                //   System.out.println(token);

            } else {
                System.out.printf("Request failed with status code: %d%n", response.statusCode());
            }
        } catch (Exception ex) {
            System.out.println("An unexpected error occurred: " + ex.getMessage());
        }
    }
}

Conclusion

Configuring authorization in the Aspose.BarCode.Cloud SDK for Java allows secure, authenticated access to barcode-related functionalities. Choose JWT authorization wiht client id and secret for automatic token management or external for custom token handling.

With these examples and explanations, you should be able to set up authorization for the Aspose.BarCode.Cloud SDK for Java.