Micronaut Basic Auth

Learn how to secure a Micronaut app using 'Basic' HTTP Authentication Scheme.

Authors: Sergio del Amo

Micronaut Version: 1.0.0.M2

1 Getting Started

RFC7617 defines the "Basic" Hypertext Transfer Protocol (HTTP) authentication scheme, which transmits credentials as user-id/password pairs, encoded using Base64.

In this guide you are going to create a Micronaut app and secure it with HTTP Basic Auth.

1.1 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

1.2 Solution

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

or

Then, cd into the complete folder which you will find in the root project of the downloaded/cloned project.

2 Writing the Application

Create a Kotlin Micronaut app using the Micronaut Command Line Interface.

mn create-app example.micronaut.complete --features=kotlin

The previous command createas a micronaut app with the default package example.micronaut in a folder named complete.

Due to the --features kotlin flag, it generates a Kotlin Micronaut app and it uses Gradle build system. However, you could use other build tool such as Maven or other programming languages such as Java or Groovy.

If you are using Java or Kotlin and IntelliJ IDEA make sure you have enabled annotation processing.

annotationprocessorsintellij

Kotlin, Kapt and IntelliJ

As of this writing IntelliJ’s built-in compiler does not directly support Kapt and annotation processing. You must instead configure Intellij to run Gradle (or Maven) compilation as a build step before running your tests or application class.

First edit the run configuration for tests or for the application and select "Run Gradle task" as a build step:

Intellij Settings

Then add the classes task as task to execute for the application or for tests the testClasses task:

Intellij Settings

Now whenever you run tests or the application Micronaut classes will be generated at compilation time.

Read Micronaut Kotlin section to learn more.

Alternatively, you can delegate IntelliJ build/run actions to gradle completely:

delegatetogradle

2.1 Security Dependency

Add Micronaut’s security dependency to your build file.

build.gradle
dependencies {
...
..
.
    compile "io.micronaut:security"
}

2.2 Configuration

Create the a new application.yml configuration file:

src/main/resources/application.yml
micronaut:
  security:
    enabled: true (1)
    endpoints:
      login:
        enabled: true  (2)
1 Enable Micronaut’s security capabilities
2 Expose /login endpoint

2.3 Authentication Provider

To keep this guide simple, create a naive AuthenticationProvider to simulate user’s authentication.

src/main/kotlin/example/micronaut/AuthenticationProviderUserPassword.kt
package example.micronaut

import io.micronaut.security.authentication.AuthenticationProvider
import io.micronaut.security.authentication.AuthenticationRequest
import io.micronaut.security.authentication.AuthenticationResponse
import org.reactivestreams.Publisher
import io.micronaut.security.authentication.AuthenticationFailed
import io.reactivex.Flowable
import java.util.ArrayList
import io.micronaut.security.authentication.UserDetails
import javax.inject.Singleton

@Singleton (1)
class AuthenticationProviderUserPassword : AuthenticationProvider { (2)
    override fun authenticate(authenticationRequest: AuthenticationRequest<*, *>?): Publisher<AuthenticationResponse> {
        if (authenticationRequest!=null && authenticationRequest.identity != null && authenticationRequest.secret != null) {
            if ( authenticationRequest.identity == "sherlock" && authenticationRequest.secret == "password" ) {
                return Flowable.just<AuthenticationResponse>(UserDetails(authenticationRequest.identity as String, ArrayList()))
            }
        }
        return Flowable.just<AuthenticationResponse>(AuthenticationFailed())
    }
}
1 To register a Singleton in Micronaut’s application context, annotate your class with javax.inject.Singleton
2 A Micronaut’s Authentication Provider implements the interface io.micronaut.security.authentication.AuthenticationProvider

2.4 Controllers

Create a file named HomeController which resolves the base URL /:

src/main/kotlin/example/micronaut/HomeController.kt
package example.micronaut

import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Produces
import io.micronaut.security.Secured
import java.security.Principal

@Secured("isAuthenticated()") (1)
@Controller("/") (2)
class HomeController {

    @Produces(MediaType.TEXT_PLAIN) (3)
    @Get("/")  (4)
    fun index(principal: Principal) : String {  (5)
        return principal.name
    }
}
1 Annotate with io.micronaut.security.Secured to configure secured access. The isAuthenticated() expression will allow access only to authenticated users.
2 Annotate with io.micronaut.http.annotation.Controller to designate a class as a Micronaut controller.
3 By default a Micronaut’s response uses application/json as Content-Type. We are returning a String not a JSON object. Because of that, we set it to text/plain.
4 You can specify the HTTP verb that a controller’s action responds to. To respond to a GET request, use the io.micronaut.http.annotation.Get annotation.
5 If a user is authenticated, Micronaut will bind the user object to an argument of type java.security.Principal (if present).

3 Tests

Speck is a Kotlin Specification Framework for the JVM.

To use Spek modify build.gradle file as described in the Spek documentation:

build.gradle
buildscript {
    repositories {
      ...
      ..
    }
    dependencies {
      ...
      ..
        classpath 'org.junit.platform:junit-platform-gradle-plugin:1.2.0'
    }
}
...
..
.
apply plugin: 'org.junit.platform.gradle.plugin'

junitPlatform {
    filters {
        engines {
            include 'spek'
        }
    }
}

repositories {
  ...
  ..
    maven { url "https://jcenter.bintray.com" }
}

dependencies {
...
..
    testCompile "org.jetbrains.spek:spek-api:1.1.5"
    testRuntime "org.jetbrains.spek:spek-junit-platform-engine:1.1.5"
    testCompile 'org.jetbrains.kotlin:kotlin-test:1.1.0'
}
...
..

test {
    useJUnitPlatform()
}

Create a test which verifies the user authentication flow via Basic Auth.

src/test/kotlin/example/micronaut/BasicAuthSpec.kt
package example.micronaut

import io.micronaut.context.ApplicationContext
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpResponse
import io.micronaut.http.HttpStatus
import io.micronaut.http.client.RxHttpClient
import io.micronaut.http.client.exceptions.HttpClientResponseException
import io.micronaut.runtime.server.EmbeddedServer
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.on
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class BasicAuthSpec: Spek({
    describe("Verify HTTP Basic Auth works") {

        var embeddedServer : EmbeddedServer = ApplicationContext.run(EmbeddedServer::class.java) (1)
        var client : RxHttpClient = RxHttpClient.create(embeddedServer.url) (2)
        on("Accessing a secured URL without authenticating") {
            var exceptionThrown = false
            try {
                val request = HttpRequest.GET<Any>("/")
                client.toBlocking().exchange(request, String::class.java) (3)
            } catch(e: HttpClientResponseException) {  (4)
                exceptionThrown = true
            }
            assertTrue(exceptionThrown)
        }
        on("If a secured URL is accessed with Basic Auth, it can be accessed") {
                val request = HttpRequest.GET<Any>("/").basicAuth("sherlock", "password")  (5)
                val rsp : HttpResponse<String> = client.toBlocking().exchange(request, String::class.java)  (6)

                assertEquals(rsp.status()!!, HttpStatus.OK)
                assertEquals(rsp.body()!!, "sherlock") (7)
        }
        afterGroup {
            client.close()
            embeddedServer.close()
        }

    }
})
}
1 To run the application from a unit test you can use the EmbeddedServer interface
2 Register a RxClient bean in the application context and point it to the embedded server URL. The EmbeddedServer interface provides the URL of the server under test which runs on a random port.
3 Creating HTTP Requests is easy thanks to Micronaut’s fluid API.
4 If you attempt to access a secured endpoint without authentication, 401 is returned
5 By using basicAuth method, you populate the Authorization header with user-id:password pairs, encoded using Base64.
6 Micronaut’s HttpClient simplifies parsing HTTP response payload to Java objects. In this example, we parse the response to String.
7 Use .body() to retrieve the parsed payload.

3.1 Use Micronaut's HTTP Client and Basic Auth

If you want to access a secured endpoint, you can also use Micronaut’s HTTP Client and supply the Basic Auth as the Authorization header value.

First create a @Client with a method home which accepts an Authorization HTTP Header.

src/test/kotlin/example/micronaut/AppClient.kt
package example.micronaut

import io.micronaut.http.client.Client
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Header

@Client("/")
interface AppClient {

    @Get("/")
    fun home(@Header authorization: String): String
}

Create a test which uses the previous @Client

src/test/kotlin/example/micronaut/BasicAuthClientSpec.kt
package example.micronaut

import io.micronaut.context.ApplicationContext
import io.micronaut.http.client.exceptions.HttpClientResponseException
import io.micronaut.runtime.server.EmbeddedServer
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.on
import java.util.Base64
import kotlin.test.assertEquals
import kotlin.test.assertFalse

class BasicAuthClientSpec: Spek({
    describe("Verify HTTP Basic Auth works") {

        val embeddedServer : EmbeddedServer = ApplicationContext.run(EmbeddedServer::class.java) (1)
        on("Accessing a secured URL using a @Client which supplies basic auth in Authorization header") {
            val credsEncoded: String = Base64.getEncoder().encodeToString("sherlock:password".byteInputStream().readBytes())

            var exceptionThrown = false
            try {
                val appClient: AppClient = embeddedServer.applicationContext.getBean(AppClient::class.java) (2)
                val rsp : String = appClient.home("Basic $credsEncoded") (3)
                assertEquals(rsp, "sherlock")
            } catch(e: HttpClientResponseException) {  (4)
                exceptionThrown = true
            }
            assertFalse(exceptionThrown)
        }
        afterGroup {
            embeddedServer.close()
        }
    }
})
1 To run the application from a unit test you can use the EmbeddedServer interface
2 Retrieve AppClient bean from application context.
3 Generate Basic Auth header value and pass it as the parameter value.
4 If the bean is found no exception is thrown

4 Testing the Application

To run the tests:

$ ./gradlew test
$ open build/reports/tests/test/index.html

5 Running the Application

To run the application use the ./gradlew run command which will start the application on a random port.