首页  >  文章  >  Java  >  如何将密钥集成到 Java Spring Boot 中

如何将密钥集成到 Java Spring Boot 中

王林
王林原创
2024-08-30 06:03:321109浏览

Java Spring Boot 中的密钥简介

密钥提供了一种现代、安全的方式来验证用户身份,而无需依赖传统密码。在本指南中,我们将引导您使用 Thymeleaf 作为模板引擎将密钥集成到 Java Spring Boot 应用程序中。

我们将利用 Corbado 的密钥优先 UI 组件连接到后端,从而简化实现过程。本教程假设您对 HTML 和 Java Spring Boot 有基本的了解,并且您已经安装了 Corbado Java SDK。

查看完整原创教程

在 Java Spring Boot 中实现密钥的先决条件

在开始之前,请确保您的项目设置包含 Corbado Java SDK。在本教程中,我们将使用版本 0.0.1 作为示例。将以下依赖项添加到您的 pom.xml 文件中:

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

或者,如果您使用 Gradle,请添加:

implementation "com.corbado:corbado-java:0.0.1"

设置您的 Corbado 帐户和项目

首先,通过开发者面板注册 Corbado 帐户。在设置过程中,您将通过选择“Corbado Complete”并为您的环境选择“Web 应用程序”来配置您的项目。请务必提供应用程序 URL 和依赖方 ID,通常分别设置为 http://localhost:8080 和 localhost。这些设置对于将密钥绑定到正确的域至关重要。

接下来,从 Corbado 开发人员面板生成 API 密钥。这对于后端通信是必要的,包括用户数据检索。

构建您的 Java Spring Boot 密钥应用程序

克隆 Spring Boot 入门存储库:

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

在此项目中,将 HelloController.java 重命名为 FrontendController.java。该控制器将根据用户请求提供 HTML 文件。在您的 application.properties 文件中,将 projectID 和 apiSecret 存储为环境变量(两者都可以从 Corbado 开发人员面板获取)。

创建密钥登录页面

在 /complete/src/main/resources/templates 目录中创建一个 index.html 文件。该文件将用作登录页面,嵌入 Corbado 密码优先 UI 组件。这是基本结构:

<!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>

定义密钥集成的控制器端点

在 FrontendController.java 中,定义端点来处理登录和个人资料页面的请求。 index() 方法应呈现登录页面,而 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";
  }
  ...

添加密钥配置文件页面

身份验证成功后,Corbado UI 组件将重定向用户。此页面显示有关用户的信息并提供注销按钮。在 templates 文件夹中,添加文件 profile.html,其中包含以下内容:

<!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>

接下来,在 FrontendController.java 中创建一个带有注释的 profile() 方法:

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

验证 Corbado 会话

在我们可以使用会话中嵌入的信息之前,我们需要验证会话是否有效。因此,我们获取 cbo_short_session cookie(会话)并使用 Corbado Java SDK 中的会话服务验证其签名。这可以通过以下方式完成:

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

从 Corbado 会话获取数据

它采用 cbo_short_session cookie,对其进行验证并返回用户 ID 和用户全名。

配置文件映射的最终代码如下所示:

  @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";
  }

启动您的应用程序

要启动 Spring Boot 应用程序,请导航到 /complete 目录并运行:

./mvnw spring-boot:run

在浏览器中访问 http://localhost:8080 以查看正在运行的登录页面。

How to Integrate Passkeys into Java Spring Boot

结论

本指南演示了如何使用 Corbado 将密钥集成到 Java Spring Boot 应用程序中。通过以下步骤,您可以高效、安全地实现无密码身份验证。有关会话管理以及将 Corbado 集成到现有应用程序中的更多详细文档,请参阅官方 Corbado 文档。

以上是如何将密钥集成到 Java Spring Boot 中的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn