Groovy / Maven

Micronaut JWT authentication via Cookies

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

Sergio del Amo
On this guide
In this section

Getting Started

In this guide, you will set up 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

What you will need

To complete this guide, you will need the following:

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.

Writing the Application

Create an application using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app --features=security-jwt,views-velocity,reactor,graalvm example.micronaut.micronautguide --build=maven --lang=groovy --test=spock
Note
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.
If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.

If you use Micronaut Launch, select Micronaut Application as application type and add the security-jwt, views-velocity, reactor, and graalvm features.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

Note
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.

Configuration

Add the following configuration:

src/main/resources/application.properties

Authentication Provider

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

groovy/src/main/groovy/example/micronaut/AuthenticationProviderUserPassword.groovy

Apache Velocity

By default, Micronaut controllers produce JSON. Usually, you consume those endpoints with a mobile phone application, or a JavaScript front end (Angular, React, Vue.js, etc.). However, to keep this guide simple, we will produce HTML in our controllers.

In order to do that, we use Apache Velocity and the Micronaut Server Side View Rendering Module.

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.

Create two Velocity templates in src/main/resources/views:

src/main/resources/views/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/views/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>

Controllers

Create HomeController which resolves the base URL /:

groovy/src/main/groovy/example/micronaut/HomeController.groovy

Login Form

Next, create LoginAuthController which renders the login form.

groovy/src/main/groovy/example/micronaut/LoginAuthController.groovy

Tests

We also use Geb, a browser automation solution.

To use Geb, add these dependencies:

pom.xml
<dependency>
    <groupId>org.apache.groovy.geb</groupId>
    <artifactId>geb-spock</artifactId>
    <version>@geb-spockVersion@</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>htmlunit-driver</artifactId>
    <version>@htmlunit-driverVersion@</version>
    <scope>test</scope>
</dependency>

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 tests to verify the user authentication flow.

src/test/groovy/example/micronaut/AuthenticationSpec.groovy

Testing the Application

To run the tests:

./mvnw test

Running the Application

To run the application, use the ./mvnw mn:run command, which starts the application on port 8080.

Next Steps

Explore more features with Micronaut Guides.

Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.

License

Note
All guides are released with an Apache License 2.0 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images).