Home Java javaTutorial How to Integrate Passkeys into Java Spring Boot

How to Integrate Passkeys into Java Spring Boot

Aug 30, 2024 am 06:03 AM

Introduction to Passkeys in Java Spring Boot

Passkeys offer a modern, secure way to authenticate users without relying on traditional passwords. In this guide, we’ll walk you through integrating passkeys into a Java Spring Boot application using Thymeleaf as the template engine.

We’ll utilize Corbado’s passkey-first UI component to connect to a backend, simplifying the implementation process. This tutorial assumes you have a basic understanding of HTML and Java Spring Boot, and that you have installed the Corbado Java SDK.

See the full original tutorial

Prerequisites for Implementing Passkeys in Java Spring Boot

Before we begin, ensure your project setup includes the Corbado Java SDK. For this tutorial, we’ll use version 0.0.1 as an example. Add the following dependency to your pom.xml file:

<dependency>
  <groupId>com.corbado</groupId>
  <artifactId>corbado-java</artifactId>
  <version>0.0.1</version>
</dependency>
Copy after login

Alternatively, if you’re using Gradle, add:

implementation "com.corbado:corbado-java:0.0.1"
Copy after login

Setting Up Your Corbado Account and Project

To begin, sign up for a Corbado account through the developer panel. During the setup, you’ll configure your project by selecting “Corbado Complete” and choosing “Web app” for your environment. Be sure to provide the Application URL and Relying Party ID, typically set to http://localhost:8080 and localhost, respectively. These settings are crucial for binding passkeys to the correct domain.

Next, generate an API secret from the Corbado developer panel. This will be necessary for backend communications, including user data retrieval.

Building Your Java Spring Boot Passkey Application

Clone the Spring Boot starter repository:

git clone https://github.com/spring-guides/gs-spring-boot.git
Copy after login

Within this project, rename HelloController.java to FrontendController.java. This controller will serve HTML files based on user requests. In your application.properties file, store the projectID and apiSecret as environment variables (both can be obtained from the Corbado developer panel).

Creating the Passkeys Login Page

Create an index.html file in the /complete/src/main/resources/templates directory. This file will serve as the login page, embedding the Corbado passkey-first UI component. Here's the basic structure:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <link rel="stylesheet" href="https://unpkg.com/@corbado/web-js@2.8.0/dist/bundle/index.css"/>
  <script src="https://unpkg.com/@corbado/web-js@2.8.0/dist/bundle/index.js" defer></script>
</head>
<body>
  <div id="corbado-auth"></div>
  <script th:inline="javascript">
    document.addEventListener('DOMContentLoaded', async () => {
      await Corbado.load({
        projectId: '[PROJECT_ID]',
        darkMode: "off",
        setShortSessionCookie: "true"
      });
      Corbado.mountAuthUI(document.getElementById('corbado-auth'), {
        onLoggedIn: () => window.location.href = '/profile',
      });
    });
  </script>
</body>
</html>
Copy after login

Defining Controller Endpoints for Passkeys Integration

In FrontendController.java, define endpoints to handle requests to the login and profile pages. The index() method should render the login page, while the profile() method will validate the user session and display the user profile.

@Controller
public class FrontendController {

  @Value("${projectID}")
  private String projectID;

  @Value("${apiSecret}")
  private String apiSecret;

  private final CorbadoSdk sdk;

  @Autowired
  public FrontendController(
      @Value("${projectID}") final String projectID, @Value("${apiSecret}") final String apiSecret)
      throws StandardException {
    final Config config = new Config(projectID, apiSecret);
    this.sdk = new CorbadoSdk(config);
  }

  @RequestMapping("/")
  public String index(final Model model) {
    model.addAttribute("PROJECT_ID", projectID);
    return "index";
  }
  ...
Copy after login

Add Passkey Profile Page

After successful authentication, the Corbado UI component redirects the user. This page displays information about the user and provides a button to log out. In the templates folder, add a file profile.html with the following content:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <link
      rel="stylesheet"
      href="https://unpkg.com/@corbado/web-js@2.8.0/dist/bundle/index.css"
      />
      <script src="https://unpkg.com/@corbado/web-js@2.8.0/dist/bundle/index.js" defer></script>
    </head>
    <body>

     <!-- Define passkey-list div and logout button -->
    <h2>:/protected</h2>
    <p>User ID: [[${USER_ID}]]</p>
    <p>Name: [[${USER_NAME}]]</p>
    <p>Email: [[${USER_EMAIL}]]</p>
    <div id="passkey-list"></div>
    <button id="logoutButton">Logout</button>


    <!-- Script to load Corbado and mount PasskeyList UI -->
    <script th:inline="javascript">
        document.addEventListener('DOMContentLoaded', async () => {
            await Corbado.load({
                projectId: /*[[${PROJECT_ID}]]*/,
                darkMode: "off",
                setShortSessionCookie: "true" // set short session cookie automatically
            }); 

            // Get and mount PasskeyList UI
            const passkeyListElement = document.getElementById("passkey-list"); // Element where you want to render PasskeyList UI
            Corbado.mountPasskeyListUI(passkeyListElement);

            // Get logout button
            const logoutButton = document.getElementById('logoutButton');
            // Add event listener to logout button
            logoutButton.addEventListener('click', function() {
              Corbado.logout()
                    .then(() => {
                        window.location.replace("/");
                    })
                    .catch(err => {
                        console.error(err);
                    });
            });
        })();
    </script>


</body>
</html>
Copy after login

Next, create a profile() method with annotation inside the FrontendController.java:

@RequestMapping("/profile")
public String profile() {
  return "profile";
}
Copy after login

Verify Corbado Session

Before we can use information embedded in the session, we need to verify that the session is valid. We therefore take the cbo_short_session cookie (the session) and verify its signature using the session service from the Corbado Java SDK. This can be done with:

final SessionValidationResult validationResp =
          sdk.getSessions().getAndValidateCurrentUser(cboShortSession);
Copy after login

Get Data from Corbado Session

It takes the cbo_short_session cookie, validates it and returns the UserID and full name of the user.

The final code for the profile mapping looks as follows:

  @RequestMapping("/profile")
  public String profile(
      final Model model, @CookieValue("cbo_short_session") final String cboShortSession) {
    try {
      // Validate user from token
      final SessionValidationResult validationResp =
          sdk.getSessions().getAndValidateCurrentUser(cboShortSession);
      // get list of emails from identifier service
      List<Identifier> emails;

      emails = sdk.getIdentifiers().listAllEmailsByUserId(validationResp.getUserID());

      //
      model.addAttribute("PROJECT_ID", projectID);
      model.addAttribute("USER_ID", validationResp.getUserID());
      model.addAttribute("USER_NAME", validationResp.getFullName());
      // select email of your liking or list all emails
      model.addAttribute("USER_EMAIL", emails.get(0).getValue());

    } catch (final Exception e) {
      System.out.println(e.getMessage());
      model.addAttribute("ERROR", e.getMessage());
      return "error";
    }
    return "profile";
  }
Copy after login

Launching Your Application

To start your Spring Boot application, navigate to the /complete directory and run:

./mvnw spring-boot:run
Copy after login

Visit http://localhost:8080 in your browser to see the login page in action.

How to Integrate Passkeys into Java Spring Boot

Conclusion

This guide demonstrated how to integrate passkeys into a Java Spring Boot application using Corbado. By following these steps, you can implement passwordless authentication efficiently and securely. For more detailed documentation on session management and integrating Corbado into existing applications, refer to the official Corbado documentation.

The above is the detailed content of How to Integrate Passkeys into Java Spring Boot. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

See all articles