mn create-app --features=security-jwt,security-ldap,reactor example.micronaut.micronautguide --build=gradle --lang=groovy
LDAP and Database authentication providers
Learn how to create a LDAP and a database authentication provider in a Micronaut Application.
Authors: Sergio del Amo
Micronaut Version: 3.9.2
1. 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.
2. What you will need
To complete this guide, you will need the following:
-
Some time on your hands
-
A decent text editor or IDE
-
JDK 1.8 or greater installed with
JAVA_HOME
configured appropriately
3. 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.
-
Download and unzip the source
4. Writing the Application
Create an application using the Micronaut Command Line Interface or with Micronaut Launch.
If you don’t specify the --build argument, Gradle is used as the build tool. If you don’t specify the --lang argument, Java is used as the language.
|
If you use Micronaut Launch, select Micronaut Application as application type and add the security-jwt
, security-ldap
, and reactor
features.
The previous command creates a Micronaut application with the default package example.micronaut
in a directory named micronautguide
.
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.yml
includes configuration settings that enable security:
micronaut:
application:
name: micronautguide
security:
authentication: bearer (1)
token:
jwt:
signatures:
secret:
generator: (2)
secret: '"${JWT_GENERATOR_SIGNATURE_SECRET:pleaseChangeThisSecretForANewOne}"' (3)
1 | Set micronaut.security.authentication as bearer |
2 | You can create a SecretSignatureConfiguration named generator via configuration as illustrated above. The generator signature is used to sign the issued JWT claims. |
3 | Change this to your own secret and keep it safe (do not store this in your VCS) |
4.1. 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.
micronaut:
security:
ldap:
default: (1)
context:
server: 'ldaps://db.debian.org' (2)
managerDn: 'cn=read-only-admin,dc=debian,dc=org' (3)
managerPassword: 'password' (4)
search:
base: "dc=debian,dc=org" (5)
groups:
enabled: true (6)
base: "dc=debian,dc=org" (7)
1 | LDAP authentication in the Micronaut framework supports configuration of one or more LDAP servers to authenticate with. You need to name each one. In this tutorial, we use default . |
2 | Each server has its own settings and can be enabled or disabled. |
3 | Sets the manager DN |
4 | Sets the manager password. |
5 | Sets the base DN to search. |
6 | Enable group search. |
7 | Sets the base DN to search from. |
4.2. GORM
GORM is a powerful Groovy-based data access toolkit for the JVM. GORM is the data access toolkit used by Grails and provides a rich set of APIs for accessing relational and non-relational data, including implementations for Hibernate (SQL), MongoDB, Neo4j, Cassandra, an in-memory ConcurrentHashMap for testing, and an automatic GraphQL schema generator.
Add GORM dependencies to the project:
implementation("io.micronaut.beanvalidation:micronaut-hibernate-validator")
implementation("io.micronaut.groovy:micronaut-hibernate-gorm")
runtimeOnly("com.h2database:h2")
runtimeOnly("org.apache.tomcat:tomcat-jdbc")
And the database configuration:
dataSource:
url: jdbc:h2:mem:devDb;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
driverClassName: org.h2.Driver
username: sa
password: ''
pooled: true
jmxExport: true
hibernate:
hbm2ddl:
auto: update
cache:
queries: false
use_second_level_cache: false
use_query_cache: false
4.2.1. Domain Classes
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.
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.
package example.micronaut.domain
import example.micronaut.UserState
import grails.gorm.annotation.Entity
import org.grails.datastore.gorm.GormEntity
import io.micronaut.serde.annotation.Serdeable
@Serdeable
@Entity (1)
class User implements GormEntity<User>, UserState { (2)
String email
String username
String password
boolean enabled = true
boolean accountExpired = false
boolean accountLocked = false
boolean passwordExpired = false
static constraints = {
email nullable: false, blank: false
username nullable: false, blank: false, unique: true
password nullable: false, blank: false, password: true
}
static mapping = {
password column: '`password`'
}
}
1 | GORM entities should be annotated with grails.gorm.annotation.Entity . |
2 | Use of GormEntity to aid IDE support. When used inside a Grails context, some IDEs will use the grails-app/domain location as a hint to enable code completion. |
Role
Create Role
domain class to store authorities within our application.
package example.micronaut.domain
import grails.gorm.annotation.Entity
import org.grails.datastore.gorm.GormEntity
import io.micronaut.serde.annotation.Serdeable
@Serdeable
@Entity (1)
class Role implements GormEntity<Role> { (2)
String authority
static constraints = {
authority nullable: false, unique: true
}
}
1 | GORM entities should be annotated with grails.gorm.annotation.Entity . |
2 | Use of GormEntity to aid IDE support. When used inside a Grails context, some IDEs will use the grails-app/domain location as a hint to enable code completion. |
UserRole
Create a UserRole
which stores a many-to-many relationship between User
and Role
.
package example.micronaut.domain
import grails.gorm.annotation.Entity
import org.grails.datastore.gorm.GormEntity
import io.micronaut.serde.annotation.Serdeable
@Serdeable
@Entity (1)
class UserRole implements GormEntity<UserRole> { (2)
User user
Role role
static constraints = {
user nullable: false
role nullable: false
}
}
1 | GORM entities should be annotated with grails.gorm.annotation.Entity . |
2 | Use of GormEntity to aid IDE support. When used inside a Grails context, some IDEs will use the grails-app/domain location as a hint to enable code completion. |
4.2.2. Data Services
GORM Data Services take the work out of implementing service layer logic by adding the ability to automatically implement abstract classes or interfaces using GORM logic.
Create various GORM Data services:
package example.micronaut
import example.micronaut.domain.User
import grails.gorm.services.Service
@Service(User) (1)
interface UserGormService {
User save(String email, String username, String password)
User findByUsername(String username)
User findById(Serializable id)
void delete(Serializable id)
int count()
}
1 | Annotate with @Service to designate a GORM Data Service which is registered as a Singleton . |
package example.micronaut
import example.micronaut.domain.Role
import grails.gorm.services.Service
@Service(Role) (1)
interface RoleGormService {
Role save(String authority)
Role find(String authority)
void delete(Serializable id)
}
1 | Annotate with @Service to designate a GORM Data Service which is registered as a Singleton . |
package example.micronaut
import example.micronaut.domain.Role
import example.micronaut.domain.User
import example.micronaut.domain.UserRole
import grails.gorm.services.Query
import grails.gorm.services.Service
@Service(UserRole) (1)
interface UserRoleGormService {
UserRole save(User user, Role role)
UserRole find(User user, Role role)
void delete(Serializable id)
@Query("""select $r.authority
from ${UserRole ur}
inner join ${User u = ur.user}
inner join ${Role r = ur.role}
where $u.username = $username""") (2)
List<String> findAllAuthoritiesByUsername(String username)
}
1 | Annotate with @Service to designate a GORM Data Service which is registered as a Singleton . |
2 | GORM allows statically-compiled JPA-QL Queries |
4.3. Password Encoder
Create an interface to handle password encoding:
package example.micronaut
import io.micronaut.core.annotation.NonNull
import javax.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 dependency:
implementation("org.springframework.security:spring-security-crypto:@spring-security-cryptoVersion@")
Then, write the implementation:
package example.micronaut
import groovy.transform.CompileStatic
import io.micronaut.core.annotation.NonNull
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder as SpringSecurityPasswordEncoder
import jakarta.inject.Singleton
import javax.validation.constraints.NotBlank
@CompileStatic
@Singleton (1)
class BCryptPasswordEncoderService implements PasswordEncoder {
SpringSecurityPasswordEncoder delegate = new BCryptPasswordEncoder()
String encode(@NotBlank @NonNull String rawPassword) {
delegate.encode(rawPassword)
}
@Override
boolean matches(@NotBlank @NonNull String rawPassword,
@NotBlank @NonNull String encodedPassword) {
delegate.matches(rawPassword, encodedPassword)
}
}
1 | Use jakarta.inject.Singleton to designate a class as a singleton. |
4.4. Register Service
We will register a user when the application starts up.
Create RegisterService
package example.micronaut
import example.micronaut.domain.Role
import example.micronaut.domain.User
import grails.gorm.transactions.Transactional
import groovy.transform.CompileStatic
import jakarta.inject.Singleton
import javax.validation.constraints.Email
import javax.validation.constraints.NotBlank
@CompileStatic
@Singleton
class RegisterService {
private final RoleGormService roleGormService
private final UserGormService userGormService
private final UserRoleGormService userRoleGormService
private final PasswordEncoder passwordEncoder
RegisterService(RoleGormService roleGormService,
UserGormService userGormService,
PasswordEncoder passwordEncoder,
UserRoleGormService 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)
if (!user) {
final String encodedPassword = passwordEncoder.encode(rawPassword)
user = userGormService.save(email, username, encodedPassword)
}
if (user && authorities) {
for (String authority : authorities) {
Role role = roleGormService.find(authority) ?: roleGormService.save(authority)
userRoleGormService.find(user, role) ?: userRoleGormService.save(user, role)
}
}
}
}
Update the Application
class to be an event listener, and use RegisterService
to create a user:
package example.micronaut
import groovy.transform.CompileStatic
import io.micronaut.context.event.ApplicationEventListener
import io.micronaut.runtime.Micronaut
import io.micronaut.runtime.server.event.ServerStartupEvent
import jakarta.inject.Singleton
@CompileStatic
@Singleton
class Application implements ApplicationEventListener<ServerStartupEvent> { (1)
private final RegisterService registerService
Application(RegisterService registerService) { (2)
this.registerService = registerService
}
@Override
void onApplicationEvent(ServerStartupEvent event) { (1)
registerService.register('sherlock@micronaut.example', 'sherlock', 'elementary', ['ROLE_DETECTIVE']) (3)
}
static void main(String[] args) {
Micronaut.run Application, args
}
}
1 | Implements ServerStartupEvent which enables executing a method when the application starts. |
2 | Use constructor injection to inject a bean of type RegisterService . |
3 | Register a new user when the application starts. |
4.5. Delegating Authentication Provider
We will set up a AuthenticationProvider a described in the next diagram.
Next, we create interfaces and implementations for each of the pieces of the previous diagram.
4.5.1. User Fetcher
Create an interface to retrieve a UserState
given a username.
package example.micronaut
import io.micronaut.core.annotation.NonNull
import javax.validation.constraints.NotBlank
interface UserFetcher {
UserState findByUsername(@NotBlank @NonNull String username)
}
Provide an implementation:
package example.micronaut
import io.micronaut.core.annotation.NonNull
import groovy.transform.CompileStatic
import jakarta.inject.Singleton
import javax.validation.constraints.NotBlank
@CompileStatic
@Singleton (1)
class UserFetcherService implements UserFetcher {
private final UserGormService userGormService
UserFetcherService(UserGormService userGormService) { (2)
this.userGormService = userGormService
}
@Override
UserState findByUsername(@NotBlank @NonNull String username) {
userGormService.findByUsername(username) as UserState
}
}
1 | Use jakarta.inject.Singleton to designate a class as a singleton. |
2 | UserGormService is injected via constructor injection. |
4.5.2. Authorities Fetcher
Create an interface to retrieve roles given a username.
package example.micronaut
interface AuthoritiesFetcher {
List<String> findAuthoritiesByUsername(String username)
}
Provide an implementation:
package example.micronaut
import jakarta.inject.Singleton
import groovy.transform.CompileStatic
@CompileStatic
@Singleton (1)
class AuthoritiesFetcherService implements AuthoritiesFetcher {
private final UserRoleGormService userRoleGormService
AuthoritiesFetcherService(UserRoleGormService userRoleGormService) { (2)
this.userRoleGormService = userRoleGormService
}
@Override
List<String> findAuthoritiesByUsername(String username) {
userRoleGormService.findAllAuthoritiesByUsername(username)
}
}
1 | Use jakarta.inject.Singleton to designate a class as a singleton. |
2 | UserRoleGormService is injected via constructor injection. |
4.5.3. Authentication Provider
Create an authentication provider which uses the interfaces you wrote in the previous sections.
package example.micronaut
import io.micronaut.core.annotation.Nullable
import io.micronaut.http.HttpRequest
import io.micronaut.scheduling.TaskExecutors
import io.micronaut.security.authentication.AuthenticationException
import io.micronaut.security.authentication.AuthenticationFailed
import io.micronaut.security.authentication.AuthenticationProvider
import io.micronaut.security.authentication.AuthenticationRequest
import io.micronaut.security.authentication.AuthenticationResponse
import reactor.core.publisher.FluxSink
import reactor.core.publisher.Flux
import reactor.core.scheduler.Scheduler
import reactor.core.scheduler.Schedulers
import org.reactivestreams.Publisher
import jakarta.inject.Named
import jakarta.inject.Singleton
import java.util.concurrent.ExecutorService
import static io.micronaut.security.authentication.AuthenticationFailureReason.ACCOUNT_EXPIRED
import static io.micronaut.security.authentication.AuthenticationFailureReason.ACCOUNT_LOCKED
import static io.micronaut.security.authentication.AuthenticationFailureReason.CREDENTIALS_DO_NOT_MATCH
import static io.micronaut.security.authentication.AuthenticationFailureReason.PASSWORD_EXPIRED
import static io.micronaut.security.authentication.AuthenticationFailureReason.USER_DISABLED
import static io.micronaut.security.authentication.AuthenticationFailureReason.USER_NOT_FOUND
@Singleton
class DelegatingAuthenticationProvider implements AuthenticationProvider {
private final UserFetcher userFetcher
private final PasswordEncoder passwordEncoder
private final AuthoritiesFetcher authoritiesFetcher
private final Scheduler scheduler
DelegatingAuthenticationProvider(UserFetcher userFetcher,
PasswordEncoder passwordEncoder,
AuthoritiesFetcher authoritiesFetcher,
@Named(TaskExecutors.IO) ExecutorService executorService) { (1)
this.userFetcher = userFetcher
this.passwordEncoder = passwordEncoder
this.authoritiesFetcher = authoritiesFetcher
this.scheduler = Schedulers.fromExecutorService(executorService)
}
@Override
Publisher<AuthenticationResponse> authenticate(@Nullable HttpRequest<?> httpRequest,
AuthenticationRequest<?, ?> authenticationRequest) {
Flux.create({ emitter ->
UserState user = fetchUserState(authenticationRequest)
AuthenticationFailed authenticationFailed = validate(user, authenticationRequest)
if (authenticationFailed) {
emitter.error(new AuthenticationException(authenticationFailed))
} else {
emitter.next(createSuccessfulAuthenticationResponse(user))
emitter.complete()
}
}, FluxSink.OverflowStrategy.ERROR)
.subscribeOn(scheduler) (2)
}
private AuthenticationFailed validate(UserState user, AuthenticationRequest authenticationRequest) {
AuthenticationFailed authenticationFailed = null
if (!user) {
authenticationFailed = new AuthenticationFailed(USER_NOT_FOUND)
} else if (!user.enabled) {
authenticationFailed = new AuthenticationFailed(USER_DISABLED)
} else if (user.accountExpired) {
authenticationFailed = new AuthenticationFailed(ACCOUNT_EXPIRED)
} else if (user.accountLocked) {
authenticationFailed = new AuthenticationFailed(ACCOUNT_LOCKED)
} else if (user.passwordExpired) {
authenticationFailed = new AuthenticationFailed(PASSWORD_EXPIRED)
} else if (!passwordEncoder.matches(authenticationRequest.secret.toString(), user.password)) {
authenticationFailed = new AuthenticationFailed(CREDENTIALS_DO_NOT_MATCH)
}
authenticationFailed
}
private UserState fetchUserState(AuthenticationRequest authRequest) {
final String username = authRequest.identity
userFetcher.findByUsername(username)
}
private AuthenticationResponse createSuccessfulAuthenticationResponse(UserState user) {
List<String> authorities = authoritiesFetcher.findAuthoritiesByUsername(user.username)
AuthenticationResponse.success(user.username, authorities)
}
}
1 | The configured I/O executor service is injected |
2 | subscribeOn method schedules the operation on the I/O thread pool |
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. |
4.6. LDAP Authentication Provider test
Create a test to verify an LDAP user can log in.
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.UsernamePasswordCredentials
import io.micronaut.security.token.jwt.generator.claims.JwtClaims
import io.micronaut.security.token.jwt.render.AccessRefreshToken
import io.micronaut.security.token.jwt.validator.JwtTokenValidator
import io.micronaut.test.extensions.spock.annotation.MicronautTest
import reactor.core.publisher.Flux
import org.reactivestreams.Publisher
import spock.lang.Ignore
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 (1)
class LoginLdapSpec extends Specification {
@Inject
@Client('/')
HttpClient client (2)
@Shared
@Inject
JwtTokenValidator tokenValidator (3)
void '/login with valid credentials returns 200 and access token and refresh token'() {
when:
HttpRequest request = HttpRequest.create(POST, '/login')
.accept(APPLICATION_JSON_TYPE)
.body(new UsernamePasswordCredentials('sherlock', 'elementary')) (4)
HttpResponse<AccessRefreshToken> rsp = client.toBlocking().exchange(request, AccessRefreshToken)
then:
rsp.status.code == 200
rsp.body.present
rsp.body.get().accessToken
}
@Ignore('TODO fix the timeout issue')
void '/login with invalid credentials returns UNAUTHORIZED'() {
when:
HttpRequest request = HttpRequest.create(POST, '/login')
.accept(APPLICATION_JSON_TYPE)
.body(new UsernamePasswordCredentials('euler', 'bogus')) (4)
client.toBlocking().exchange(request)
then:
HttpClientResponseException e = thrown()
e.status.code == 401 (5)
}
void 'access token contains expiration date'() {
when:
HttpRequest request = HttpRequest.create(POST, '/login')
.accept(APPLICATION_JSON_TYPE)
.body(new UsernamePasswordCredentials('sherlock', 'elementary')) (4)
HttpResponse<AccessRefreshToken> rsp = client.toBlocking().exchange(request, AccessRefreshToken)
then:
rsp.status.code == 200
rsp.body.present
when:
String accessToken = rsp.body.get().accessToken
then:
accessToken
when:
Publisher authentication = tokenValidator.validateToken(accessToken, request) (6)
then:
Flux.from(authentication).blockFirst()
and: 'access token contains an expiration date'
Flux.from(authentication).blockFirst().attributes.get(JwtClaims.EXPIRATION_TIME)
}
}
1 | Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info. |
2 | Inject the HttpClient bean and point it to the embedded server. |
3 | Inject the TokenValidator bean. |
4 | Creating HTTP Requests is easy thanks to the Micronaut framework fluid API. |
5 | If you attempt to access a secured endpoint without authentication, 401 is returned |
6 | Use the tokenValidator bean previously injected. |
4.7. Login Testing
Test /login
endpoint. We verify both LDAP and DB authentication providers work.
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.render.AccessRefreshToken
import io.micronaut.security.token.jwt.validator.JwtTokenValidator
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
JwtTokenValidator tokenValidator
@Inject
UserGormService 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')
}
}
5. Testing the Application
To run the tests:
./gradlew test
Then open build/reports/tests/test/index.html
in a browser to see the results.
6. Running the Application
To run the application, use the ./gradlew run
command, which starts the application on port 8080.
7. Next steps
Explore more features with Micronaut Guides.
8. Help with the Micronaut Framework
The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.