Micronaut JWT authentication via Cookies

Learn how to secure a Micronaut app using JWT (JSON Web Token) based authentication where the JWT tokens are transported via Cookies.

Authors: Sergio del Amo

Micronaut Version: 1.0.0.M1

1 Getting Started

In this guide you are going to setup JWT based authentication and configure it so that JWT tokens are transported and read via Cookies.

The following sequence illustrates the authentication flow:

jwt cookie

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 How to complete the guide

To get started do the following:

or

The Micronaut guides repositories contain two folders:

  • initial Initial project. Often a simple Micronaut app with some additional code to give you a head-start.

  • complete A completed example. It is the result of working through the steps presented by the guide and applying those changes to the initial folder.

To complete the guide, go to the initial folder

  • cd into micronaut-guides/micronaut-security-jwt-cookie/initial

and follow the instructions in the next sections.

You can go right to the completed example if you cd into micronaut-guides/micronaut-security-jwt-cookie/complete

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 JWT security dependency to your build file.

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

2.2 Configuration

Create the next configuration file:

src/main/resources/application.yaml
micronaut:
  security:
    enabled: true (1)
    endpoints:
      login:
        enabled: true (2)
      logout:
        enabled: true (3)
    token:
      jwt:
        enabled: true (4)
        bearer:
          enabled: false (5)
        cookie:
          enabled: true (6)
          loginFailureTargetUrl: /login/authFailed  (7)
        signatures:
          secret:
            generator: (9)
              secret: pleaseChangeThisSecretForANewOne  (9)
1 Enable Micronaut’s security capabilities
2 Expose /login endpoint
3 Expose /logout endpoint
4 Enable JWT based authentication
5 Disable Bearer Token support.
6 Enable Cookie Token support.
7 If the login fails, redirect to /login/authFailed
8 You can create a SecretSignatureConfiguration named generator via configuration as illustrated above. The generator signature is used to sign the issued JWT claims.
9 Change this by your own secret and keep it safe.

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 Apache Velocity

By default, Micronaut’s controllers produce JSON. Usually, you consume those endpoints with a mobile phone application or a Javascript front end (Angular, React, Vue.js …​). However, to keep this guide simple we are going to produce HTML in our controllers.

In order to do that, we use Apache Velocity.

Velocity is a Java-based template engine. It permits anyone to use a simple yet powerful template language to reference objects defined in Java code.

Add a dependency to velocity:

build.gradle
dependencies {
...
..
.
    compile "org.apache.velocity:velocity-engine-core:2.0"
}

Create two velocity templates:

src/main/resources/templates/home.vm
<!DOCTYPE html>
<html>
    <head>
        <title>Home</title>
    </head>
    <body>
        #if( $loggedIn )
            <h1>username: <span>$username</span></h1>
        #else
            <h1>You are not logged in</h1>
        #end
        #if( $loggedIn )
            <form action="logout" method="POST">
                <input type="submit" value="Logout"/>
            </form>
        #else
            <p><a href="/login/auth">Login</a></p>
        #end
    </body>
</html>
src/main/resources/templates/auth.vm
<!DOCTYPE html>
<html>
    <head>
        #if( $errors )
            <title>Login Failed</title>
        #else
            <title>Login</title>
        #end
    </head>
<body>
    <form action="/login" method="POST">
        <ol>
            <li>
                <label for="username">Username</label>
                <input type="text" name="username" id="username"/>
            </li>
            <li>
                <label for="password">Password</label>
                <input type="password" name="password" id="password"/>
            </li>
            <li>
                <input type="submit" value="Login"/>
            </li>
            #if( $errors )
                <li id="errors">
                    <span style="color: red;">Login Failed</span>
                </li>
            #end
        </ol>
    </form>
</body>
</html>

To render those templates, create VelocityService.java

src/main/java/example/micronaut/services/VelocityService.java
package example.micronaut.services;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import javax.annotation.PostConstruct;
import javax.inject.Singleton;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Properties;

@Singleton (1)
public class VelocityService {

    private VelocityEngine velocityEngine;

    @PostConstruct (2)
    void initialize() {
        final Properties p = new Properties();
        p.setProperty("resource.loader", "class");
        p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        velocityEngine = new VelocityEngine(p);
    }

    public String render(final String name, Map<String, Object> data) {
        final StringWriter writer = new StringWriter();
        final VelocityContext velocityContext = new VelocityContext(data);
        velocityEngine.mergeTemplate(templateName(name), StandardCharsets.UTF_8.name(), velocityContext, writer);
        return writer.toString();
    }

    String templateName(final String name) {
        final StringBuilder sb = new StringBuilder();
        sb.append("templates/");
        sb.append(name);
        return sb.toString();
    }
}
1 To create a Sigleton bean use the javax.inject.Singleton annotation.
2 Use the javax.annotation.PostConstruct annotation to trigger the method execution after dependency injection is done. Typically to perform any initialization.

2.5 Controllers

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

src/main/java/example/micronaut/controllers/HomeController.java
package example.micronaut.controllers;

import example.micronaut.services.VelocityService;
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 javax.annotation.Nullable;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

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

    protected final VelocityService velocityService;

    public HomeController(VelocityService velocityService) { (3)
        this.velocityService = velocityService;
    }

    @Produces(MediaType.TEXT_HTML) (4)
    @Get("/")  (5)
    String index(@Nullable Principal principal) {  (6)
        return velocityService.render("home.vm", homeModel(principal));
    }

    private Map homeModel(@Nullable Principal principal) {
        Map<String, Object> data = new HashMap<>();
        data.put("loggedIn", principal!=null);
        if (principal!=null) {
            data.put("username", principal.getName());
        }
        return data;
    }
}
1 Annotate with io.micronaut.security.Secured to configure security access. Use isAnonymous() expression for anonymous access.
2 Annotate with io.micronaut.http.annotation.Controller to designate a class as a Micronaut’s controller.
3 VelocityService is injected via constructor injection.
4 By default a controller’s action produces JSON, however you can define its produces HTML with io.micronaut.http.annotation.Produces annotation.
5 You can specify the HTTP verb for which a controller’s action responds to. To respond to a GET request, use io.micronaut.http.annotation.Get.
6 If you are authenticated, you can use the java.security.Principal as a parameter type. For parameters which maybe null, use javax.annotation.Nullable.

Login Form

Next, create LoginAuthController which renders the login form.

src/main/java/example/micronaut/controllers/LoginAuthController.java
package example.micronaut.controllers;

import example.micronaut.services.VelocityService;
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.util.HashMap;
import java.util.Map;

@Secured("isAnonymous()") (1)
@Controller("/login")  (2)
public class LoginAuthController {

    protected final VelocityService velocityService;

    public LoginAuthController(VelocityService velocityService) {  (3)
        this.velocityService = velocityService;
    }

    @Produces(MediaType.TEXT_HTML) (4)
    @Get("/auth") (5)
    public String auth() {
        return velocityService.render("auth.vm", new HashMap<>()); (6)
    }

    @Produces(MediaType.TEXT_HTML) (4)
    @Get("/authFailed") (7)
    public String authFailed() {
        return velocityService.render("auth.vm", authFailedModel()); (6)
    }

    private Map<String, Object> authFailedModel() {
        Map<String, Object> data = new HashMap<>();
        data.put("errors", true);
        return data;
    }
}
1 Annotate with io.micronaut.security.Secured to configure security access. Use isAnonymous() expression for anonymous access.
2 Annotate with io.micronaut.http.annotation.Controller to designate a class as a Micronaut’s controller.
3 VelocityService is injected via constructor injection.
4 By default a controller’s action produces JSON, however you can define its produces HTML with io.micronaut.http.annotation.Produces annotation.
5 responds to GET requests at /login/auth
6 Render velocity template auth.vm
7 responds to GET requests at /login/authFailed

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 {
...
..
    compile "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

We use also, Geb; a browser automation solution.

To use Geb, add dependencies:

build.gradle
dependencies {
...
..
.
    testCompile "org.gebish:geb-spock:2.1"
    testRuntime "org.seleniumhq.selenium:selenium-chrome-driver:3.6.0"
    testRuntime "org.seleniumhq.selenium:selenium-firefox-driver:3.6.0"
    testCompile "org.seleniumhq.selenium:selenium-support:3.6.0"
    testCompile "org.seleniumhq.selenium:selenium-api:3.6.0"
}

Create a Geb Configuration file to setup different environments:

import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions
import org.openqa.selenium.firefox.FirefoxDriver
import org.openqa.selenium.firefox.FirefoxOptions

environments {

    // run via “./gradlew -Dgeb.env=chrome test”
    chrome {
        driver = { new ChromeDriver() }
    }

    // run via “./gradlew -Dgeb.env=chromeHeadless test”
    chromeHeadless {
        driver = {
            ChromeOptions o = new ChromeOptions()
            o.addArguments('headless')
            new ChromeDriver(o)
        }
    }

    firefoxHeadless {
        driver = {
            FirefoxOptions o = new FirefoxOptions()
            o.addArguments('-headless')
            new FirefoxDriver(o)
        }
    }

    // run via “./gradlew -Dgeb.env=firefox test”
    firefox {
        driver = { new FirefoxDriver() }
    }
}

Geb uses the Page concept pattern - The Page Object Pattern gives us a common sense way to model content in a reusable and maintainable way.

Create two pages:

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

import geb.Page

class HomePage extends Page {

    static url = '/'

    static at = { title == 'Home' }

    static content = {
        loginLink { $('a', text: 'Login') }
        logoutButton { $('input', type: 'submit', value: 'Logout') }
        usernameElement(required: false) { $('h1 span', 0) }
    }

    String username() {
        if ( usernameElement.empty ) {
            return null
        }
        usernameElement.text()
    }

    void login() {
        loginLink.click()
    }

    void logout() {
        logoutButton.click()
    }
}
src/test/groovy/example/micronaut/LoginPage.groovy
package example.micronaut

import geb.Page

class LoginPage extends Page {

    static url = '/login/auth'

    static at = { title.contains 'Login' }

    static content = {
        usernameInput { $('#username') }
        passwordInput { $('#password') }
        submitInput { $('input', type: 'submit') }
        errorsLi(required: false) { $('li#errors') }
    }

    boolean hasErrors() {
        !errorsLi.empty
    }

    void login(String username, String password) {
        usernameInput = username
        passwordInput = password
        submitInput.click()
    }
}

Create a tests which verifies the user authentication flow.

src/test/groovy/example/micronaut/AuthenticationSpec.groovy
class AuthenticationSpec extends GebSpec {

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

    @IgnoreIf({ !sys['geb.env'] })
    def "verify session based authentication works"() {
        given:
        browser.baseUrl = "http://localhost:${embeddedServer.port}"

        when:
        to HomePage

        then:
        at HomePage

        when:
        HomePage homePage = browser.page HomePage

        then: 'As we are not logged in, there is no username'
        homePage.username() == null

        when: 'click the login link'
        homePage.login()

        then:
        at LoginPage

        when: 'fill the login form, with invalid credentials'
        LoginPage loginPage = browser.page LoginPage
        loginPage.login('foo', 'foo')

        then: 'the user is still in the login form'
        at LoginPage

        and: 'and error is displayed'
        loginPage.hasErrors()

        when: 'fill the form with valid credentials'
        loginPage.login('sherlock', 'password')

        then: 'we get redirected to the home page'
        at HomePage

        when:
        homePage = browser.page HomePage

        then: 'the username is populated'
        homePage.username() == 'sherlock'

        when: 'click the logout button'
        homePage.logout()

        then: 'we are in the home page'
        at HomePage

        when:
        homePage = browser.page HomePage

        then: 'but we are no longer logged in'
        homePage.username() == null
    }
}

3.1 WebDriver Binaries

Install webdriver-binaries Gradle plugin; a plugin that downloads and caches WebDriver binaries specific to the OS the build runs on.

build.gradle
buildscript {
    repositories {
...
..
    }
    dependencies {
        classpath "gradle.plugin.com.energizedwork.webdriver-binaries:webdriver-binaries-gradle-plugin:1.4"
    }
}

dependencies {
...
..
.
}

webdriverBinaries {
    chromedriver '2.38'
    geckodriver '0.20.1'
}

tasks.withType(Test) {
    systemProperty "geb.env", System.getProperty('geb.env')
    systemProperty "webdriver.chrome.driver", System.getProperty('webdriver.chrome.driver')
    systemProperty "webdriver.gecko.driver", System.getProperty('webdriver.gecko.driver')
}

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.