Micronaut Azure

Micronaut projects for Microsoft Azure

Version:

1 Introduction

This project provides integrations between Micronaut and Microsoft Azure.

2 Release History

For this project, you can find a list of releases (with release notes) here:

3 Azure SDK

The Azure SDK module provides integration between Micronaut and Microsoft Azure SDK for Java.

First you need add a dependency on the azure-sdk module:

implementation("io.micronaut.azure:micronaut-azure-sdk:3.2.3")
<dependency>
    <groupId>io.micronaut.azure</groupId>
    <artifactId>micronaut-azure-sdk</artifactId>
    <version>3.2.3</version>
</dependency>

3.1 Authentication

The micronaut-azure-sdk module supports these authentication options:

DefaultAzureCredential

The DefaultAzureCredential is appropriate for most scenarios where the application ultimately runs in the Azure Cloud. It combines credentials that are commonly used to authenticate when deployed, with credentials that are used to authenticate in a development environment.

The DefaultAzureCredential is used when no other credential type is specified or explicitly enabled.

ClientCertificateCredential

The ClientCertificateCredential authenticates the created service principal through its client certificate. Visit Client certificate credential for more details.

The ClientCertificateCredential supports both PFX and PEM certificate file types.

Use of PEM certificate
azure:
  credential:
    client-certificate:
      client-id: <client-id>
      pem-certificate-path: <path to pem certificate>
Use of PFX certificate
azure:
  credential:
    client-certificate:
      client-id: <client-id>
      pfx-certificate-path: <path to pfx certificate>
      pfx-certificate-password: <pfx certificate password>

Optionally you can configure the tenant id by setting the property azure.credential.client-certificate.tenant-id.

ClientSecretCredential

The ClientSecretCredential authenticates the created service principal through its client secret (password). See more on Client secret credential for more details.

Use of client secret credential
azure:
  credential:
    client-secret:
      client-id: <client-id>
      tenant-id: <tenant-id>
      secret: <secret>

UsernamePasswordCredential

The UsernamePasswordCredential helps to authenticate a public client application using the user credentials that don’t require multi-factor authentication. Visit Username password credential for more details.

Use of username password credential
azure:
  credential:
    username-password:
      client-id: <client-id>
      username: <username>
      password: <password>

Optionally you can configure the tenant id by setting the property azure.credential.username-password.tenant-id.

ManagedIdentityCredential

The ManagedIdentityCredential authenticates the managed identity (system or user assigned) of an Azure resource. So, if the application is running inside an Azure resource that supports Managed Identity through IDENTITY/MSI, IMDS endpoints, or both, then this credential will get your application authenticated, and offers a great secretless authentication experience. Visit Managed Identity credential for more details.

Example on how to enable the managed identity credential for system assigned identity
azure:
  credential:
    managed-identity:
      enabled: true

Note, that for user-assigned identity you have to also set the azure.credential.managed-identity.client-id.

AzureCliCredential

The AzureCliCredential authenticates in a development environment with the enabled user or service principal in Azure CLI. It uses the Azure CLI given a user that is already logged into it, and uses the CLI to authenticate the application against Azure Active Directory. Visit Azure CLI credential for more details.

Example on how to enable the azure credential
azure:
  credential:
    cli:
      enabled: true

IntelliJCredential

The IntelliJCredential authenticates in a development environment with the account in Azure Toolkit for IntelliJ. It uses the logged in user information on the IntelliJ IDE and uses it to authenticate the application against Azure Active Directory. Visit IntelliJ credential for more details.

Example on how to enable the azure credential
azure:
  credential:
    intellij:
      enabled: true

Note, that for Windows platform the KeePass database path needs to be set by property azure.credential.intellij.kee-pass-database-path. The KeePass database path is used to read the cached credentials of Azure toolkit for IntelliJ plugin. For macOS and Linux platform native key chain / key ring will be accessed respectively to retrieve the cached credentials.

Optionally you can configure the tenant id by setting the property azure.credential.intellij.tenant-id.

VisualStudioCodeCredential

The VisualStudioCodeCredential enables authentication in development environments where VS Code is installed with the VS Code Azure Account extension. It uses the logged-in user information in the VS Code IDE and uses it to authenticate the application against Azure Active Directory. Visit Visual Studio Code credential for more details.

Example on how to enable the visual studio code credential
azure:
  credential:
    visual-studio-code:
      enabled: true

Optionally you can configure the tenant id by setting the property azure.credential.visual-studio-code.tenant-id.

3.2 Client

The Azure SDK provides long list of management and client libraries. The example below illustrates on how to create a BlobServiceClient. The other Azure clients can be created similar way:

@Factory
public class BlobServiceFactory {  // (1)

    @Singleton
    public BlobServiceClient blobServiceClient(@NonNull TokenCredential tokenCredential){  // (2)
        return new BlobServiceClientBuilder()  // (3)
                .credential(tokenCredential)
                .endpoint(System.getenv("AZURE_BLOB_ENDPOINT"))
                .buildClient();
    }
}
1 The class is a factory bean.
2 The method returns the singleton of BlobServiceClient class. Note the injected credential bean is of type TokenCredential. It is an interface that provides token based credential authentication.
3 The client builder is used to create the client by providing the credential bean and the blob service endpoint. Note that every client builder class like BlobServiceClientBuilder offers additional configuration options.

4 Azure Function Support

The Azure function module provides support for writing Serverless functions with Micronaut that target the Azure Function environment.

4.1 Simple Azure Functions

There are two modules, the first of which (micronaut-azure-function) is more low level and allows you to define functions that can be dependency injected with Micronaut.

To get started follow the instructions to create an Azure Function project with Gradle or with Maven.

Then add the following dependency to the project:

implementation("io.micronaut.azure:micronaut-azure-function:3.2.3")
<dependency>
    <groupId>io.micronaut.azure</groupId>
    <artifactId>micronaut-azure-function</artifactId>
    <version>3.2.3</version>
</dependency>

And ensure the Micronaut annotation processors are configured:

annotationProcessor("io.micronaut.azure:micronaut-inject-java")
<annotationProcessorPaths>
    <path>
        <groupId>io.micronaut.azure</groupId>
        <artifactId>micronaut-inject-java</artifactId>
    </path>
</annotationProcessorPaths>

You can then write a function that subclasses AzureFunction and it will be dependency injected when executed. For example:

package example;

import com.microsoft.azure.functions.annotation.BlobOutput;
import com.microsoft.azure.functions.annotation.BlobTrigger;
import com.microsoft.azure.functions.annotation.FunctionName;
import com.microsoft.azure.functions.annotation.StorageAccount;
import io.micronaut.azure.function.AzureFunction;
import io.micronaut.context.event.ApplicationEvent;
import io.micronaut.context.event.ApplicationEventPublisher;

import jakarta.inject.Inject;

public class BlobFunction extends AzureFunction { // (1)
    @Inject
    ApplicationEventPublisher eventPublisher; // (2)

    @FunctionName("copy")
    @StorageAccount("AzureWebJobsStorage")
    @BlobOutput(name = "$return", path = "samples-output-java/{name}") // (3)
    public String copy(@BlobTrigger(
            name = "blob",
            path = "samples-input-java/{name}") String content) {
        eventPublisher.publishEvent(new BlobEvent(content)); // (4)
        return content;
    }

    public static class BlobEvent extends ApplicationEvent {
        public BlobEvent(String content) {
            super(content);
        }
    }
}
package example

import com.microsoft.azure.functions.annotation.BlobOutput
import com.microsoft.azure.functions.annotation.BlobTrigger
import com.microsoft.azure.functions.annotation.FunctionName
import com.microsoft.azure.functions.annotation.StorageAccount
import io.micronaut.azure.function.AzureFunction
import io.micronaut.context.event.ApplicationEvent
import io.micronaut.context.event.ApplicationEventPublisher

import jakarta.inject.Inject

class BlobFunction extends AzureFunction { // (1)
    @Inject
    ApplicationEventPublisher eventPublisher // (2)

    @FunctionName("copy")
    @StorageAccount("AzureWebJobsStorage")
    @BlobOutput(name = '$return', path = "samples-output-java/{name}") // (3)
    String copy(@BlobTrigger(
            name = "blob",
            path = "samples-input-java/{name}") String content) {
        eventPublisher.publishEvent(new BlobEvent(content)) // (4)
        return content
    }

    static class BlobEvent extends ApplicationEvent {
        BlobEvent(String content) {
            super(content)
        }
    }
}
package example

import com.microsoft.azure.functions.annotation.BlobOutput
import com.microsoft.azure.functions.annotation.BlobTrigger
import com.microsoft.azure.functions.annotation.FunctionName
import com.microsoft.azure.functions.annotation.StorageAccount
import io.micronaut.azure.function.AzureFunction
import io.micronaut.context.event.ApplicationEvent
import io.micronaut.context.event.ApplicationEventPublisher
import jakarta.inject.Inject

class BlobFunction : AzureFunction() { // (1)
    @Inject
    lateinit var eventPublisher : ApplicationEventPublisher<Any> // (2)

    @FunctionName("copy")
    @StorageAccount("AzureWebJobsStorage")
    @BlobOutput(name = "\$return", path = "samples-output-java/{name}") // (3)
    fun copy(@BlobTrigger(name = "blob", path = "samples-input-java/{name}") content: String): String {
        eventPublisher.publishEvent(BlobEvent(content)) // (4)
        return content
    }

    class BlobEvent(content: String) : ApplicationEvent(content)
}
1 The class subclasses AzureFunction. Note that a zero argument public constructor is required
2 Use can dependency inject fields with @Inject. In this case we publish an event.
3 You can specify the function bindings as per the Azure Function API
4 Injected objects can be used in your function code

4.2 Azure HTTP Functions

An additional module exists called micronaut-azure-function-http that allows you to write regular Micronaut controllers and have them executed using Azure Function. To get started add the micronaut-azure-function-http module.

implementation("io.microaut.azure:micronaut-azure-function-http:3.2.3")
<dependency>
    <groupId>io.microaut.azure</groupId>
    <artifactId>micronaut-azure-function-http</artifactId>
    <version>3.2.3</version>
</dependency>

You then need to define a function that subclasses AzureHttpFunction and overrides the invoke method:

package example;

import com.microsoft.azure.functions.ExecutionContext;
import com.microsoft.azure.functions.HttpMethod;
import com.microsoft.azure.functions.HttpRequestMessage;
import com.microsoft.azure.functions.HttpResponseMessage;

import com.microsoft.azure.functions.annotation.AuthorizationLevel;
import com.microsoft.azure.functions.annotation.FunctionName;
import com.microsoft.azure.functions.annotation.HttpTrigger;
import io.micronaut.azure.function.http.AzureHttpFunction;
import java.util.Optional;

public class MyHttpFunction extends AzureHttpFunction { // (1)
    @FunctionName("ExampleTrigger") // (2)
    public HttpResponseMessage invoke(
            @HttpTrigger(
                    name = "req",
                    methods = {HttpMethod.GET, HttpMethod.POST}, // (3)
                    route = "{*route}", // (4)
                    authLevel = AuthorizationLevel.ANONYMOUS) // (5)
                    HttpRequestMessage<Optional<String>> request, // (6)
            final ExecutionContext context) {
        return super.route(request, context); // (7)
    }
}
package example

import com.microsoft.azure.functions.ExecutionContext
import com.microsoft.azure.functions.HttpMethod
import com.microsoft.azure.functions.HttpRequestMessage
import com.microsoft.azure.functions.HttpResponseMessage

import com.microsoft.azure.functions.annotation.AuthorizationLevel
import com.microsoft.azure.functions.annotation.FunctionName
import com.microsoft.azure.functions.annotation.HttpTrigger
import io.micronaut.azure.function.http.AzureHttpFunction

class MyHttpFunction extends AzureHttpFunction { // (1)
    @FunctionName("ExampleTrigger") // (2)
    HttpResponseMessage invoke(
            @HttpTrigger(
                    name = "req",
                    methods = [HttpMethod.GET, HttpMethod.POST], // (3)
                    route = "{*route}", // (4)
                    authLevel = AuthorizationLevel.ANONYMOUS) // (5)
                    HttpRequestMessage<Optional<String>> request, // (6)
            final ExecutionContext context) {
        return super.route(request, context) // (7)
    }
}
package example

import com.microsoft.azure.functions.ExecutionContext
import com.microsoft.azure.functions.HttpMethod
import com.microsoft.azure.functions.HttpRequestMessage
import com.microsoft.azure.functions.HttpResponseMessage
import com.microsoft.azure.functions.annotation.AuthorizationLevel
import com.microsoft.azure.functions.annotation.FunctionName
import com.microsoft.azure.functions.annotation.HttpTrigger
import io.micronaut.azure.function.http.AzureHttpFunction
import java.util.Optional

class MyHttpFunction : AzureHttpFunction() { // (1)
    @FunctionName("ExampleTrigger") // (2)
    fun invoke(
            @HttpTrigger(name = "req",
                    methods = [HttpMethod.GET, HttpMethod.POST], // (3)
                    route = "{*route}", // (4)
                    authLevel = AuthorizationLevel.ANONYMOUS) // (5)
            request: HttpRequestMessage<Optional<String>>,  // (6)
            context: ExecutionContext): HttpResponseMessage {
        return super.route(request, context) // (7)
    }
}
1 The function class subclasses AzureHttpFunction and includes a zero argument constructor.
2 The function name can be whatever you prefer
3 You can choose to handle ony specific HTTP methods
4 In general you want a catch all route as in the example, but you can customize it.
5 The auth level specifies who can access the function. Using ANONYMOUS allows everyone.
6 The received request optionally contains the raw bytes
7 The body of the method should just invoke the route method of the super implementation.

With this in place you can write regular Micronaut controllers as documented in the user guide for the HTTP server and incoming function requests will be routed to the controllers and executed.

This approach allows you to develop a regular Micronaut application and deploy slices of the application as Serverless functions as desired.

5 Repository

You can find the source code of this project in this repository: