Groovy / Gradle

LDAP and database authentication providers

Learn how to create an LDAP and a database authentication provider in a Micronaut application.

Sergio del Amo
On this guide
In this section

Getting Started

In this guide, we will create a Micronaut application written in Groovy.

The application uses multiple authentication providers; an LDAP and a database authentication provider.

diagram ldap authentication.provider

What you will need

To complete this guide, you will need the following:

Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

Writing the Application

Create an application using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app example.micronaut.micronautguide \
    --features=validation,security-jwt,security-ldap,data-jdbc,jdbc-hikari,h2,spring-security-crypto,reactor \
    --build=gradle \
    --lang=groovy \
    --test=spock
Note
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.
If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

If you use Micronaut Launch, select Micronaut Application as application type and add validation, security-jwt, security-ldap, data-jdbc, jdbc-hikari, h2, spring-security-crypto, and reactor features.

Note
If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features, and apply those changes to your application.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

Note
If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features, and apply those changes to your application.

The generated application.properties includes configuration settings that enable security:

src/main/resources/application.properties

Security LDAP

The Micronaut framework supports authentication with LDAP out of the box.

We will use the open Debian LDAP service for this guide.

Create the configuration properties matching those of the LDAP Server.

src/main/resources/application.properties

Micronaut Data JDBC

Add Micronaut Data JDBC dependencies to the project:

build.gradle
compileOnly("io.micronaut.data:micronaut-data-processor")
implementation("io.micronaut.data:micronaut-data-jdbc")
implementation("io.micronaut.sql:micronaut-jdbc-hikari")
runtimeOnly("com.h2database:h2")

And the database configuration:

src/main/resources/application.properties
datasources.default.password=
datasources.default.dialect=H2
datasources.default.schema-generate=CREATE_DROP
datasources.default.url=jdbc\:h2\:mem\:devDb;LOCK_TIMEOUT\=10000;DB_CLOSE_ON_EXIT\=FALSE
datasources.default.username=sa
datasources.default.driver-class-name=org.h2.Driver

Entities

A domain class fulfills the M in the Model View Controller (MVC) pattern and represents a persistent entity that is mapped onto an underlying database table.

User

Create a UserState interface to model the user state.

groovy/src/main/groovy/example/micronaut/UserState.groovy
package example.micronaut

interface UserState {

    String getUsername()

    String getPassword()

    boolean isEnabled()

    boolean isAccountExpired()

    boolean isAccountLocked()

    boolean isPasswordExpired()
}

Create User domain class to store users within our application.

groovy/src/main/groovy/example/micronaut/domain/User.groovy
Role

Create a Role domain class to store authorities within the application.

groovy/src/main/groovy/example/micronaut/domain/Role.groovy
UserRole

Create a UserRole which stores a many-to-many relationship between User and Role.

groovy/src/main/groovy/example/micronaut/domain/UserRole.groovy
groovy/src/main/groovy/example/micronaut/domain/UserRoleId.groovy

JDBC Repositories

Create the following JDBC repositories:

groovy/src/main/groovy/example/micronaut/UserJdbcRepository.groovy
groovy/src/main/groovy/example/micronaut/RoleJdbcRepository.groovy
groovy/src/main/groovy/example/micronaut/UserRoleJdbcRepository.groovy

Password Encoder

Create an interface to handle password encoding:

groovy/src/main/groovy/example/micronaut/PasswordEncoder.groovy
package example.micronaut

import io.micronaut.core.annotation.NonNull

import jakarta.validation.constraints.NotBlank

interface PasswordEncoder {
    String encode(@NotBlank @NonNull String rawPassword)

    boolean matches(@NotBlank @NonNull String rawPassword,
                    @NotBlank @NonNull String encodedPassword)
}

To provide an implementation, first include a dependency to Spring Security Crypto to ease password encoding.

Add the dependencies:

build.gradle
implementation("org.springframework.security:spring-security-crypto:@spring-security-cryptoVersion@")
implementation("org.slf4j:jcl-over-slf4j")

Then, write the implementation:

groovy/src/main/groovy/example/micronaut/BCryptPasswordEncoderService.groovy

Register Service

We will register a user when the application starts up.

Create RegisterService

groovy/src/main/groovy/example/micronaut/RegisterService.groovy
package example.micronaut

import example.micronaut.domain.Role
import example.micronaut.domain.User
import example.micronaut.domain.UserRole
import example.micronaut.domain.UserRoleId
import groovy.transform.CompileStatic

import jakarta.inject.Singleton
import jakarta.transaction.Transactional
import jakarta.validation.constraints.Email
import jakarta.validation.constraints.NotBlank

@CompileStatic
@Singleton
class RegisterService {

    private final RoleJdbcRepository roleGormService
    private final UserJdbcRepository userGormService
    private final UserRoleJdbcRepository userRoleGormService
    private final PasswordEncoder passwordEncoder

    RegisterService(RoleJdbcRepository roleGormService,
                    UserJdbcRepository userGormService,
                    PasswordEncoder passwordEncoder,
                    UserRoleJdbcRepository userRoleGormService) {
        this.roleGormService = roleGormService
        this.userGormService = userGormService
        this.userRoleGormService = userRoleGormService
        this.passwordEncoder = passwordEncoder
    }

    @Transactional
    void register(@Email String email, @NotBlank String username,
                  @NotBlank String rawPassword, List<String> authorities) {

        User user = userGormService.findByUsername(username).orElse(null)
        if (!user) {
            final String encodedPassword = passwordEncoder.encode(rawPassword)
            user = userGormService.save(new User(email: email, username: username, password: encodedPassword, enabled: true, accountExpired: false, accountLocked: false, passwordExpired: false))
        }

        if (user && authorities) {
            for (String authority : authorities) {
                Role role = roleGormService.findByAuthority(authority).orElseGet(() -> roleGormService.save(authority))
                UserRoleId userRoleId = new UserRoleId(user.id, role.id)
                if (userRoleGormService.findById(userRoleId).isEmpty()) {
                    userRoleGormService.save(new UserRole(userRoleId))
                }
            }
        }
    }
}

Update the Application class to be an event listener, and use RegisterService to create a user:

groovy/src/main/groovy/example/micronaut/Application.groovy

Delegating Authentication Provider

We will set up a AuthenticationProvider as described in the next diagram.

delegating authentication provider

Next, we create interfaces and implementations for each of the pieces of the previous diagram.

User Fetcher

Create an interface to retrieve a UserState given a username.

groovy/src/main/groovy/example/micronaut/UserFetcher.groovy
package example.micronaut

import io.micronaut.core.annotation.NonNull

import jakarta.validation.constraints.NotBlank

interface UserFetcher {
    Optional<UserState> findByUsername(@NotBlank @NonNull String username)
}

Provide an implementation:

groovy/src/main/groovy/example/micronaut/UserFetcherService.groovy

Authorities Fetcher

Create an interface to retrieve roles given a username.

groovy/src/main/groovy/example/micronaut/AuthoritiesFetcher.groovy
package example.micronaut

interface AuthoritiesFetcher {
    List<String> findAuthoritiesByUsername(String username)
}

Provide an implementation:

groovy/src/main/groovy/example/micronaut/AuthoritiesFetcherService.groovy

Authentication Provider

Create an authentication provider which uses the interfaces you wrote in the previous sections.

groovy/src/main/groovy/example/micronaut/DelegatingAuthenticationProvider.groovy
Important
It is critical that any blocking I/O operations (such as fetching the user from the database in the previous code sample) are offloaded to a separate thread pool that does not block the event loop.

LDAP Authentication Provider test

Create a test to verify an LDAP user can log in.

groovy/src/test/groovy/example/micronaut/LoginLdapSpec.groovy

Login Testing

Test the /login endpoint. We verify both LDAP and database authentication providers work.

groovy/src/test/groovy/example/micronaut/LoginControllerSpec.groovy
package example.micronaut

import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpResponse
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.http.client.exceptions.HttpClientResponseException
import io.micronaut.security.authentication.Authentication
import io.micronaut.security.authentication.UsernamePasswordCredentials
import io.micronaut.security.token.jwt.validator.ReactiveJsonWebTokenValidator
import io.micronaut.security.token.render.AccessRefreshToken
import io.micronaut.test.extensions.spock.annotation.MicronautTest
import reactor.core.publisher.Flux
import spock.lang.Shared
import spock.lang.Specification

import jakarta.inject.Inject

import static io.micronaut.http.HttpMethod.POST
import static io.micronaut.http.MediaType.APPLICATION_JSON_TYPE

@MicronautTest
class LoginControllerSpec extends Specification {

    @Inject
    @Client('/')
    HttpClient client

    @Shared
    @Inject
    ReactiveJsonWebTokenValidator tokenValidator

    @Inject
    UserJdbcRepository userGormService

    void 'attempt to access /login without supplying credentials server responds BAD REQUEST'() {
        when:
        HttpRequest request = HttpRequest.create(POST, '/login')
            .accept(APPLICATION_JSON_TYPE)
        client.toBlocking().exchange(request)

        then:
        HttpClientResponseException e = thrown()
        e.status.code == 400
    }

    void '/login with valid credentials for a database user returns 200 and access token'() {
        expect:
        userGormService.count() > 0

        when:
        HttpRequest request = HttpRequest.create(POST, '/login')
            .accept(APPLICATION_JSON_TYPE)
            .body(new UsernamePasswordCredentials('sherlock', 'elementary'))
        HttpResponse<AccessRefreshToken> rsp = client.toBlocking().exchange(request, AccessRefreshToken)

        then:
        noExceptionThrown()
        rsp.status.code == 200
        rsp.body.present
        rsp.body.get().accessToken

        when:
        String accessToken = rsp.body.get().accessToken
        Authentication authentication = Flux.from(tokenValidator.validateToken(accessToken, request)).blockFirst()

        then:
        authentication.attributes
        authentication.attributes.containsKey('roles')
        authentication.attributes.containsKey('iss')
        authentication.attributes.containsKey('exp')
        authentication.attributes.containsKey('iat')
    }
}

Testing the Application

To run the tests:

./gradlew test

Then open build/reports/tests/test/index.html in a browser to see the results.

Running the Application

To run the application, use the ./gradlew run command, which starts the application on port 8080.

Next Steps

Explore more features with Micronaut Guides.

Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.

License

Note
All guides are released with an Apache License 2.0 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images).