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.
Authors: Sergio del Amo
Micronaut Version: 4.6.3
1. 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:
2. What you will need
To complete this guide, you will need the following:
-
Some time on your hands
-
A decent text editor or IDE (e.g. IntelliJ IDEA)
-
JDK 21 or greater installed with
JAVA_HOME
configured appropriately
3. 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.
-
Download and unzip the source
4. 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=java --test=spock
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
.
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. |
4.1. Configuration
Add the following configuration:
micronaut:
security:
authentication: cookie (1)
redirect:
login-failure: /login/authFailed (2)
token:
jwt:
signatures:
secret:
generator: (3)
secret: '"${JWT_GENERATOR_SIGNATURE_SECRET:pleaseChangeThisSecretForANewOne}"' (4)
1 | Enable Cookie authentication. |
2 | If the login fails, redirect to /login/authFailed |
3 | You can create a SecretSignatureConfiguration named generator via configuration as illustrated above. The generator signature is used to sign the issued JWT claims. |
4 | Change this to your own secret and keep it safe. |
4.2. Authentication Provider
To keep this guide simple, create a naive AuthenticationProvider
to simulate user’s authentication.
package example.micronaut;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.http.HttpRequest;
import io.micronaut.security.authentication.AuthenticationFailureReason;
import io.micronaut.security.authentication.AuthenticationRequest;
import io.micronaut.security.authentication.AuthenticationResponse;
import io.micronaut.security.authentication.provider.HttpRequestAuthenticationProvider;
import jakarta.inject.Singleton;
@Singleton (1)
public class AuthenticationProviderUserPassword<B> implements HttpRequestAuthenticationProvider<B> { (2)
@Override
public @NonNull AuthenticationResponse authenticate(
@Nullable HttpRequest<B> requestContext,
@NonNull AuthenticationRequest<String, String> authenticationRequest
) {
return authenticationRequest.getIdentity().equals("sherlock") && authenticationRequest.getSecret().equals("password")
? AuthenticationResponse.success(authenticationRequest.getIdentity())
: AuthenticationResponse.failure(AuthenticationFailureReason.CREDENTIALS_DO_NOT_MATCH);
}
}
1 | Use jakarta.inject.Singleton to designate a class as a singleton. |
2 | A Micronaut Authentication Provider implements the interface io.micronaut.security.authentication.provider.HttpRequestAuthenticationProvider . |
4.3. 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
:
<!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>
<!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>
4.4. Controllers
Create HomeController
which resolves the base URL /
:
package example.micronaut;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.security.annotation.Secured;
import io.micronaut.security.rules.SecurityRule;
import io.micronaut.views.View;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
@Secured(SecurityRule.IS_ANONYMOUS) (1)
@Controller (2)
public class HomeController {
@Get (3)
@View("home") (4)
Map<String, Object> index(@Nullable Principal principal) { (5)
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 the class as a Micronaut controller. |
3 | You can specify the HTTP verb that a controller action responds to. To respond to a GET request, use io.micronaut.http.annotation.Get |
4 | You can specify the HTTP verb that a controller action responds to. To respond to a GET request, use io.micronaut.http.annotation.Get . |
5 | If you are authenticated, you can use the java.security.Principal as a parameter type. For parameters which may be null, use io.micronaut.core.annotation.Nullable . |
4.5. Login Form
Next, create LoginAuthController
which renders the login form.
package example.micronaut;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.security.annotation.Secured;
import io.micronaut.security.rules.SecurityRule;
import io.micronaut.views.View;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@Secured(SecurityRule.IS_ANONYMOUS) (1)
@Controller("/login") (2)
public class LoginAuthController {
@Get("/auth") (3)
@View("auth") (4)
public Map<String, Object> auth() {
return new HashMap<>();
}
@Get("/authFailed") (5)
@View("auth") (4)
public Map<String, Object> authFailed() {
return Collections.singletonMap("errors", true);
}
}
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 the class as a Micronaut controller. |
3 | responds to GET requests at /login/auth |
4 | Use View annotation to specify which template to use to render the response. |
5 | responds to GET requests at /login/authFailed |
5. Tests
We also use Geb, a browser automation solution.
To use Geb, add these dependencies:
<dependency>
<groupId>org.gebish</groupId>
<artifactId>geb-spock</artifactId>
<version>7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>htmlunit-driver</artifactId>
<version>3.62.0</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:
/*
* Copyright 2017-2024 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
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()
}
}
/*
* Copyright 2017-2024 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
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.
/*
* Copyright 2017-2024 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.micronaut
import geb.spock.GebSpec
import io.micronaut.runtime.server.EmbeddedServer
import io.micronaut.test.extensions.spock.annotation.MicronautTest
import jakarta.inject.Inject
@MicronautTest (1)
class AuthenticationSpec extends GebSpec {
@Inject
EmbeddedServer embeddedServer (2)
void "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
}
}
1 | Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info. |
2 | Inject the EmbeddedServer bean. |
6. Testing the Application
To run the tests:
./mvnw test
7. Running the Application
To run the application, use the ./mvnw mn:run
command, which starts the application on port 8080.
8. Generate a Micronaut Application Native Executable with GraalVM
We will use GraalVM, the polyglot embeddable virtual machine, to generate a native executable of our Micronaut application.
Compiling native executables ahead of time with GraalVM improves startup time and reduces the memory footprint of JVM-based applications.
Only Java and Kotlin projects support using GraalVM’s native-image tool. Groovy relies heavily on reflection, which is only partially supported by GraalVM.
|
8.1. GraalVM installation
sdk install java 21.0.5-graal
For installation on Windows, or for manual installation on Linux or Mac, see the GraalVM Getting Started documentation.
The previous command installs Oracle GraalVM, which is free to use in production and free to redistribute, at no cost, under the GraalVM Free Terms and Conditions.
Alternatively, you can use the GraalVM Community Edition:
sdk install java 21.0.2-graalce
8.2. Native executable generation
To generate a native executable using Maven, run:
./mvnw package -Dpackaging=native-image
The native executable is created in the target
directory and can be run with target/micronautguide
.
9. Next steps
Explore more features with Micronaut Guides.
10. Help with the Micronaut Framework
The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.
11. License
All guides are released with an Apache license 2.0 license for the code and a Creative Commons Attribution 4.0 license for the writing and media (images…). |