Micronaut Basic Auth

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

Authors: Sergio del Amo

Micronaut Version: 1.0.0.M1

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

mn create-app example

By default, create-app generates a Java Micronaut app and it uses Gradle build system. However, you could use other build tool such as Maven or other programming languages such as Groovy or Kotlin.

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

annotationprocessorsintellij

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/java/example/micronaut/services/AuthenticationProviderUserPassword.java
package example.micronaut.services;

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;
import java.util.ArrayList;

@Singleton (1)
public class AuthenticationProviderUserPassword implements AuthenticationProvider  { (2)

    @Override
    public Publisher<AuthenticationResponse> authenticate(AuthenticationRequest authenticationRequest) {
        if ( authenticationRequest.getIdentity().equals("sherlock") &&
                authenticationRequest.getSecret().equals("password") ) {
            return Flowable.just(new UserDetails((String) authenticationRequest.getIdentity(), new ArrayList<>()));
        }
        return Flowable.just(new 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/java/example/micronaut/controllers/HomeController.java
package example.micronaut.controllers;

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

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

    @Get("/")  (3)
    String index(Principal principal) {  (4)
        return principal.getName();
    }
}
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 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.
4 If a user is authenticated, Micronaut will bind the user object to an argument of type java.security.Principal (if present).

3 Tests

Micronaut is test framework agnostic. You can use JUnit or Spock Framework.

In this Guide, we test the app with Spock Framework.

We need to modify build.gradle to install spock.

Replace apply plugin: 'java' with apply plugin: 'groovy' and add the necessary dependencies:

build.gradle
dependencies {
...
..
    testCompile "org.codehaus.groovy:groovy-all:2.4.15"
    testCompile "org.spockframework:spock-core:1.1-groovy-2.4"
}

Edit micronaut-cli to set Spock as the test framework:

build.gradle
profile: service
defaultPackage: example
---
testFramework: spock
sourceLanguage: java

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.

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.