DEV Community

Cover image for Fortanix Library: Authentication and Security Object Retrieval
≀Paulo Portela
≀Paulo Portela

Posted on

Fortanix Library: Authentication and Security Object Retrieval

Introduction

This chapter explores the functionalities of the Fortanix library, focusing on authentication and retrieving security objects. Fortanix provides encryption and cryptographic key management services essential for secure data handling. This chapter will guide you through the process of initializing the library, authenticating with the Fortanix API, and retrieving security object content.

Index

  • Initialisation
  • Authentication
  • Retrieving Security Objects

Initialisation

The Fortanix library requires an API key and the desired environment to operate. Upon initialization, the library sets up the necessary configurations and prepares for authentication.

from dataclasses import dataclass
import json
import logging
import requests

@dataclass
class Configuration(object):
    url_base: str = None
    token: str = None

@dataclass
class Response:
    status_code: int
    content: dict | None = None

class Fortanix(object):
    def __init__(self, api_key: str, env: str) -> None:
        """
        Initializes the Fortanix client and performs authentication.

        Args:
            api_key (str): The Fortanix Application API Key.
            env (str): The environment (Production or Development).
        """
        logging.basicConfig(level=logging.INFO)
        self.session: requests.sessions.Session = requests.sessions.Session()
        self.__configuration = self.auth(api_key=api_key, env=env)

    def __del__(self) -> None:
        """
        Cleans up resources and closes the session.
        """
        logging.info(msg="Closing session")
        self.session.close()

    def auth(self, api_key: str, env: str) -> Configuration:
        """
        Performs authentication to obtain the token.

        Args:
            api_key (str): The Fortanix Application API Key.
            env (str): The environment (Production or Development).

        Returns:
            Configuration: Configuration object containing URL base and token.
        """
        logging.info(msg="Obtaining token")
        configuration = Configuration()

        if env.lower() == "production":
            url_base = r"https://kms.xxxxxx.com"
        else:
            url_base = r"https://kms-test.xxxxxx.com"

        url_query = fr"{url_base}/sys/v1/session/auth"
        headers = {"Authorization": f"Basic {api_key}"}
        response = self.session.post(url=url_query, headers=headers, verify=True)
        logging.info(msg=f"HTTP Status Code {response.status_code}")

        if response.status_code != 200:
            raise Exception("Fortanix authentication failed - Check App permissions")

        configuration.url_base = url_base
        configuration.token = json.loads(response.content)["access_token"]

        return configuration
Enter fullscreen mode Exit fullscreen mode

Authentication

Authentication is a crucial step to access Fortanix services securely. This section outlines the authentication process, including obtaining a token from the Fortanix API.

# Initialize Fortanix with API key and environment
fortanix_client = Fortanix(api_key="your_api_key_here", env="production")

# Authenticate with Fortanix API
# fortanix_client.auth(api_key="your_api_key_here", env="production")
Enter fullscreen mode Exit fullscreen mode

Retrieving Security Objects

Once authenticated, you can retrieve security objects from Fortanix. This section demonstrates how to retrieve the content of a security object by its name.

    def get_security_object(self, name: str) -> Response:
        """
        Retrieves the content of a security object by its name.

        Args:
            name (str): The name of the Fortanix Security Object.

        Returns:
            Response: Object containing JSON content and response status.
        """
        logging.info(msg=f"Retrieving Security Object {name}")

        url_query = f"{self.__configuration.url_base}/crypto/v1/keys/export"
        headers = {"Authorization": f"Bearer {self.__configuration.token}"}
        body = {"name": name}
        response = self.session.post(url=url_query, json=body, headers=headers, verify=True)
        logging.info(msg=f"HTTP Status Code {response.status_code}")

        if response.status_code != 200:
            raise Exception("Fortanix security object retrieval failed")

        return Response(status_code=response.status_code, content=json.loads(response.content))
Enter fullscreen mode Exit fullscreen mode

Code Examples

Below are examples demonstrating the usage of the Fortanix library:

# Initialize Fortanix with API key and environment
fortanix_client = Fortanix(api_key="your_api_key_here", env="production")

# Authenticate with Fortanix API
# fortanix_client.auth(api_key="your_api_key_here", env="production")

# Retrieve security object content
security_object = fortanix_client.get_security_object(name="your_security_object_name")
Enter fullscreen mode Exit fullscreen mode

Conclusion

The Fortanix library simplifies authentication and security object retrieval processes, ensuring secure data handling. By following the steps outlined in this chapter, you can seamlessly integrate Fortanix functionalities into your applications.

For more information about Fortanix and their comprehensive security solutions, visit Fortanix's website.

Top comments (0)