Micronaut Basic Auth

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

Authors: Sergio del Amo

Micronaut Version: 1.0.0.M4

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 Groovy Micronaut app using the Micronaut Command Line Interface.

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

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

Due to the --features groovy flag, it generates a Groovy 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 Kotlin.

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/groovy/example/micronaut/AuthenticationProviderUserPassword.groovy
package example.micronaut

import groovy.transform.CompileStatic
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 io.micronaut.security.authentication.UserDetails
import io.reactivex.Flowable
import org.reactivestreams.Publisher
import javax.inject.Singleton

@CompileStatic
@Singleton (1)
class AuthenticationProviderUserPassword implements AuthenticationProvider { (2)
    @Override
    Publisher<AuthenticationResponse> authenticate(AuthenticationRequest authenticationRequest) {
        if ( authenticationRequest.identity == "sherlock" && authenticationRequest.secret == "password" ) {
            return Flowable.just(new UserDetails((String) authenticationRequest.identity, []))  as Flowable<AuthenticationResponse>
        }
        Flowable.just(new AuthenticationFailed()) as Flowable<AuthenticationResponse>
    }
}
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/groovy/example/micronaut/HomeController.groovy
package example.micronaut

import groovy.transform.CompileStatic
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

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

    @Produces(MediaType.TEXT_PLAIN) (3)
    @Get("/") (4)
    String index(Principal principal) { (5)
        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

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

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

import io.micronaut.context.ApplicationContext
import io.micronaut.http.HttpResponse
import io.micronaut.http.HttpStatus
import io.micronaut.http.client.exceptions.HttpClientResponseException
import io.micronaut.runtime.server.EmbeddedServer
import spock.lang.AutoCleanup
import spock.lang.Shared
import spock.lang.Specification
import io.micronaut.http.client.RxHttpClient
import io.micronaut.http.HttpRequest

class BasicAuthSpec extends Specification {

    @Shared
    @AutoCleanup (1)
    EmbeddedServer embeddedServer = ApplicationContext.run(EmbeddedServer) (2)

    @Shared
    @AutoCleanup
    RxHttpClient client = embeddedServer.applicationContext.createBean(RxHttpClient, embeddedServer.getURL()) (3)

    def "Verify HTTP Basic Auth works"() {
        when: 'Accessing a secured URL without authenticating'
        client.toBlocking().exchange(HttpRequest.GET('/')) (4)

        then: 'returns unauthorized'
        HttpClientResponseException e = thrown(HttpClientResponseException) (5)
        e.status == HttpStatus.UNAUTHORIZED

        when: 'A secured URL is accessed with Basic Auth'
        HttpRequest request = HttpRequest.GET('/')
                .basicAuth("sherlock", "password") (6)
        HttpResponse<String> rsp = client.toBlocking().exchange(request, String) (7)

        then: 'the endpoint can be accessed'
        rsp.status == HttpStatus.OK
        rsp.body() == 'sherlock' (10)
    }
}
}
1 The AutoCleanup extension makes sure the close() method of an object (e.g. EmbeddedServer) is called each time a feature method is finished
2 To run the application from a unit test you can use the EmbeddedServer interface
3 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.
4 Creating HTTP Requests is easy thanks to Micronaut’s fluid API.
5 If you attempt to access a secured endpoint without authentication, 401 is returned
6 By using basicAuth method, you populate the Authorization header with user-id:password pairs, encoded using Base64.
7 Micronaut’s HttpClient simplifies parsing HTTP response payload to Java objects. In this example, we parse the response to String.
8 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/groovy/example/micronaut/AppClient.groovy
package example.micronaut

import groovy.transform.CompileStatic
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Header
import io.micronaut.http.client.Client

@CompileStatic
@Client("/")
interface AppClient {

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

Create a test which uses the previous @Client

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

import io.micronaut.context.ApplicationContext
import io.micronaut.http.HttpHeaders
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpResponse
import io.micronaut.http.HttpStatus
import io.micronaut.http.MutableHttpMessage
import io.micronaut.http.client.RxHttpClient
import io.micronaut.http.client.exceptions.HttpClientResponseException
import io.micronaut.runtime.server.EmbeddedServer
import spock.lang.AutoCleanup
import spock.lang.Shared
import spock.lang.Specification

class BasicAuthClientSpec extends Specification {

    @Shared
    @AutoCleanup (1)
    EmbeddedServer embeddedServer = ApplicationContext.run(EmbeddedServer) (2)

    def "Verify HTTP Basic Auth works"() {
        when:
        AppClient appClient = embeddedServer.applicationContext.getBean(AppClient) (3)

        then:
        noExceptionThrown() (4)

        when:
        String credsEncoded = "sherlock:password".bytes.encodeBase64().toString()
        String rsp = appClient.home("Basic ${credsEncoded}") (5)

        then:
        rsp == 'sherlock'
    }
}
1 The AutoCleanup extension makes sure the close() method of an object (e.g. EmbeddedServer) is called each time a feature method is finished
2 To run the application from a unit test you can use the EmbeddedServer interface
3 Retrieve AppClient bean from application context.
4 If the bean is found no exception is thrown
5 Generate Basic Auth header value and pass it as the parameter value.

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.