Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat= Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Accessibility testing is a crucial aspect to ensure that your application is usable for everyone and meets accessibility standards that are required in many countries.

By automating these tests, teams can quickly detect issues related to screen reader compatibility, keyboard navigation, color contrast, and other aspects that could pose a barrier to using the software effectively for people with disabilities.

Learn how to automate accessibility testing with Selenium and the LambdaTest cloud-based testing platform that lets developers and testers perform accessibility automation on over 3000+ real environments:

Automated Accessibility Testing With Selenium

Course – LSS – NPI (cat=Spring Security)
announcement - icon

If you're working on a Spring Security (and especially an OAuth) implementation, definitely have a look at the Learn Spring Security course:

>> LEARN SPRING SECURITY

1. Introduction

Login forms have long been, and still are, a common feature of any web service that requires authentication to provide its services. However, as security concerns started to become mainstream, it became clear that simple text passwords are a weak spot: they can be guessed, intercepted, or leaked, leading to security incidents that can result in financial and/or reputation damage.

Previous attempts to replace passwords with alternative solutions (mTLS, security cards, etc) tried to address this issue but led to poor user experience and additional costs.

In this tutorial, we’ll explore Passkeys, also known as WebAuthn, a standard that provides a secure alternative to passwords. In particular, we’ll demonstrate how to quickly add support for this authentication mechanism to a Spring Boot application with Spring Security.

2. What Is a Passkey?

Passkeys or WebAuthn is a standard API defined by the W3C Consortium that allows applications running on a Web Browser to manage public keys and register them for use with a given service provider.

The typical registration scenario goes like this:

  1. The user creates a new account on the service. The initial credentials are usually the familiar username/password
  2. Once registered, the user goes to his profile page and selects “create passkey”
  3. The system displays a passkey registration form
  4. The user fills the form with the required information – e.g. the key label that will help the user select the right key later – and submits it
  5. The system saves the passkey in its database and associates it with the user account. At the same time, a private part of this key will be saved on the user’s device
  6. The passkey registration is complete

Once key registration is completed, the user can use the stored passkey to access the service. Depending on the security configuration of the browser and the user’s device, the login will require a fingerprint scan, unlocking a smartphone, or similar action.

A passkey consists of two parts: the public key that the browser sends to the service provider and a private part that remains on the local device.

Moreover, the client-side API’s implementation ensures that a given passkey is usable only with the same site that registered it.

3. Adding Passkeys to Spring Boot Applications

Let’s create a simple Spring Boot application to test passkeys. Our application will have just a welcome page that displays the name of the current user and a link to the passkey registration page.

The first step is to add the required dependencies to the project:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>3.4.3</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
    <version>3.4.3</version>
</dependency>
<dependency>
    <groupId>com.webauthn4j</groupId>
    <artifactId>webauthn4j-core</artifactId>
    <version>0.28.5.RELEASE</version>
</dependency>

The latest versions of these dependencies are available on Maven Central:

IMPORTANT: WebAuthn support requires Spring Boot version 3.4.0 or higher

4. Spring Security Configuration

Starting with Spring Security 6.4, which is the default version included through the spring-boot-starter-security dependency, the configuration DSL comes with native support for passkeys through the webautn() method.

@Bean
SecurityFilterChain webauthnFilterChain(HttpSecurity http, WebAuthNProperties webAuthNProperties) {
    return http.authorizeHttpRequests( ht -> ht.anyRequest().authenticated())
      .formLogin(withDefaults())
      .webAuthn(webauth ->
          webauth.allowedOrigins(webAuthNProperties.getAllowedOrigins())
            .rpId(webAuthNProperties.getRpId())
            .rpName(webAuthNProperties.getRpName())
      )
      .build();
}

This is what we get with this configuration:

  • A “login with passkey” button will be present on the login page
  • A registration page available at /webauthn/register

For proper operation, we must provide at least the following configuration attributes to the webauthn configurer:

  • allowedOrigins: external URL of the site, which MUST use HTTPS, unless it uses localhost
  • rpId: Application identifier, which MUST be a valid domain name that matches the hostname part of the allowedOrigin attribute
  • rpName: A user-friendly name that the browser may use during the registration and/or login process

This configuration, however, misses a critical aspect of passkey support: registered keys are lost upon application restart. This is because, by default, Spring Security uses a memory-based implementation credential store, which is not meant for production use.

We’ll see how to fix this later on.

5. Passkey Walk-Around

With the passkey configuration in place, it’s time for a quick walk-around through our application. Once we start it using mvn spring-boot:run or the IDE, we can open our browser and navigate to http://localhost:8080:

Login form with passkey

The standard login page for Spring applications will now include the “Sign in with a passkey” button. Since we haven’t registered any key yet, we must log in using username/password credentials, which we’ve configured in our application.yaml file: alice/changeit

Welcome page

As expected, we’re now logged in as Alice. We can now continue to the registration page by clicking on the Register PassKey link:

Passkey registration page

Here, we’ll just provide a label – baeldung-demo – and click on Register. What happens next depends on the device type (desktop, mobile, tablet) and OS (Windows, Linux, Mac, Android), but in the end, it will result in a new key being added to the list:

Passkey registration success

For instance, in Chrome on Windows, the dialog will give a choice to create a new key and store it with the browser’s native password manager or use the Windows Hello functionality available on the OS.

Next, let’s log out of the application and try our new key. First, we navigate to http://localhost:8080/logout and confirm that want to exit. Next, on the login form, we click on “Sign in with a passkey”. The browser will show a dialog which allows you to select a passkey:

Passkey Selector

Once we select one of the available keys, the device will perform an additional authentication challenge. For the “Windows Hello” authentication, this can be a fingerprint scan, face recognition, etc.

If the authentication is successful, the user’s private key will be used to sign a challenge and send it to the server, where it will be validated using the previously stored public key. Finally, if everything checks, the login completes and the welcome page will be displayed as before.

6. Passkey Repositories

As mentioned before, the default passkey configuration created by Spring Security doesn’t provide persistence for the registered keys. To fix this, we need to provide implementations for the following interfaces:

  • PublicKeyCredentialUserEntityRepository
  • UserCredentialRepository

6.1. PublicKeyCredentialUserEntityRepository

This service manages PublicKeyCredentialUserEntity instances and maps user accounts managed by the standard UserDetailsService to user account identifiers. This entity has the following attributes:

  • name: A user-friendly name identifier for the account
  • id: An opaque identifier for the user’s account
  • displayName: An alternate version of the account name, meant to be used for display purposes

It’s important to notice that the current implementation assumes that both name and id are unique within a given authentication domain.

In general, we can assume that entries in this table have a 1:1 relationship with accounts managed by the standard UserDetailsService.

The implementation, available online, uses Spring Data JDBC repositories to store those fields in the PASSKEY_USERS table.

6.2. UserCredentialRepository

Manages CredentialRecord instances, which stores the actual public key received from the browser as part of the registration process. This entity includes all the recommended properties specified in the W3C’s documentation, along with some additional ones:

  •  userEntityUserId: Identifier of the PublicKeyCredentialUserEntity that owns this credential
  •  label: user-defined label for this credential, assigned at registration time
  •  lastUsed: Date of last usage for this credential
  •  created: Date of creation of this credential

Notice that CredentialRecord has an N:1 relationship with PublicKeyCredentialUserEntity, which reflects on the methods of the repository. For instance, the findByUserId() method returns a list of CredentialRecord instances.

Our implementation takes this into account and uses a foreign key in the PASSKEY_CREDENTIALS table to ensure referential integrity.

7. Testing

While it is possible to test passkey-based applications using mock requests, the value of those tests is somewhat limited. Most failure scenarios are related to client-side issues, thus requiring integration tests that use a real browser driven by an automation tool.

Here, we’ll use Selenium to implement a “happy path” scenario just to illustrate the technique. In particular, we’ll use the VirtualAuthenticator feature to configure the WebDriver, allowing us to simulate interactions between the registration and login page with this mechanism.

For instance, this is how we can create a new driver with a VirtualAuthenticator:

@BeforeEach
void setupTest() {
    VirtualAuthenticatorOptions options = new VirtualAuthenticatorOptions()
      .setIsUserVerified(true)
      .setIsUserConsenting(true)
      .setProtocol(VirtualAuthenticatorOptions.Protocol.CTAP2)
      .setHasUserVerification(true)
      .setHasResidentKey(true);

    driver = new ChromeDriver();
    authenticator = ((HasVirtualAuthenticator) driver).addVirtualAuthenticator(options);
}

Once we get the authenticator instance, we can use it to simulate different scenarios, such as a successful or unsuccessful login, registration, and so on. Our live test goes through a full cycle, consisting of the following steps:

  • Initial login using username/password credentials
  • Passkey registration
  • Logout
  • Login using the passkey

8. Conclusion

In this tutorial, we’ve shown how to use Passkeys in a Spring Boot Web application, including the Spring Security setup and adding key persistence support needed for real-world applications.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat = Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Partner – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Course – LSS – NPI (cat=Security/Spring Security)
announcement - icon

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security:

>> CHECK OUT THE COURSE

Partner – Microsoft – NPI (cat=Spring)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

eBook Jackson – NPI EA – 3 (cat = Jackson)