跳转至

Java Spring Boot

本指南将介绍如何使用 OAuth2,以 Authany 作为身份提供方(IdP),为您的 Java Spring Boot 应用添加身份验证。

学习目标

您将学到以下内容:

  • 如何在 Authany 上创建应用。
  • 如何启用基于邮箱的登录。
  • 为 Spring Boot 应用添加注册和登录功能。

前提条件

开始之前,您需要准备以下内容:

  • Java 17 或更高版本。
  • 一个免费的 Authany 账号。如果您还没有账号,请注册。

为您的 Spring Web 应用添加登录

第 1 部分:配置 Authany

要使用 Authany 服务,您需要先在 Authany 管理台 中设置一个应用。该应用是您为所开发项目配置身份验证方式的地方。

步骤 1:配置应用

使用交互式选择器创建一个新的 Authany OIDC 客户端应用,或选择一个已有的、代表您想要接入的项目的应用。

Authany 中的每个应用都会被分配一个由字母数字组成的唯一客户端 ID,您的应用代码会通过 Spring Boot 的 OAuth 2 Client 使用该 ID 调用 Authany API。请从输出结果中记下 Authany 颁发方(issuer,例如 https://example-auth.authanyid.com/)、CLIENT ID、CLIENT SECRET 和 OpenID 端点。您将在下一步的客户端应用配置中用到这些值。

步骤 2:配置重定向 URI

重定向 URI 是您应用中的一个 URL,用于指定用户完成身份验证后 Authany 应将其重定向到的位置。在本例中,它将是我们 Spring Boot 应用的主页。如果未设置,用户登录后将不会被带回您的应用。

要跟随本文的示例操作,请添加以下 URL 作为重定向 URI:

http://localhost:8080/login/oauth2/code/authgear

步骤 3:选择登录方式

创建 Authany 应用后,您需要选择用户在登录页面上进行身份验证的方式。从「身份验证」标签页进入「登录方式」,您可以从多种选项中选择一种登录方式,包括邮箱、手机、社交登录、仅用户名,或您自定义的方式。在本示例中,我们选择 邮箱+无密码 方式,用户需要注册账号并使用邮箱登录,登录时会收到发送到邮箱的一次性密码(OTP),验证该验证码后即可使用应用。

第 2 部分:配置 Spring Boot 应用

步骤 1:添加 Spring 依赖

要创建新的 Spring Boot 应用,可以使用 Spring Initializr。然后在 pom.xml 文件中添加依赖,例如 spring-boot-starter-oauth2-client starter 提供了为 Web 应用添加身份验证所需的全部 Spring Security 依赖,而 Thymeleaf 仅用于构建单页面 UI。

  <dependencies>
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-oauth2-client</artifactId>
      </dependency>
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>
      <dependency>
          <groupId>org.thymeleaf.extras</groupId>
          <artifactId>thymeleaf-extras-springsecurity6</artifactId>
          <version>3.1.1.RELEASE</version>
      </dependency>
  </dependencies>

步骤 2:配置使用 Authany 的 OIDC 身份验证

Spring Security 让您可以轻松地为应用配置与 Authany 等 OIDC 提供方的身份验证。我们需要在 application.properties 文件中添加客户端凭证以及您的 Authany 提供方配置。您可以参考下面的示例,并将其中的属性替换为您 Authany 应用中的值:

spring.security.oauth2.client.registration.authgear.client-id={your-client-id}
spring.security.oauth2.client.registration.authgear.client-secret={your-client-secret}
spring.security.oauth2.client.registration.authgear.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.authgear.scope=openid,offline_access
spring.security.oauth2.client.registration.authgear.redirect-uri=http://localhost:8080/login/oauth2/code/authgear/
spring.security.oauth2.client.provider.authgear.token-uri=https://{DOMAIN}/oauth2/token
spring.security.oauth2.client.provider.authgear.authorization-uri=https://{DOMAIN}/oauth2/authorize

# To logout from the app
authgear.oauth2.end-session-endpoint=https://{DOMAIN}/oauth2/end_session

步骤 3:为您的应用添加登录

要启用通过 Authany 进行用户登录,请创建一个提供 SecurityFilterChain 实例的类,添加 @EnableMethodSecurity 注解,并重写必要的方法:

@Configuration
@EnableMethodSecurity(securedEnabled = true)
public class SecurityConfig {

    @Value("${authgear.oauth2.end-session-endpoint}")
    private String endSessionEndpoint;

    @Bean
    public SecurityFilterChain configure(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((requests) -> requests
                // allow anonymous access to the root page
                .requestMatchers("/").permitAll()
                // authenticate all other requests
                .anyRequest().authenticated())
            // enable OAuth2/OIDC
            .oauth2Login(withDefaults())
            // configure logout handler
            .logout(logout -> logout.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/")
                .addLogoutHandler(oidcLogoutHandler()));
        return http.build();
    }

    LogoutHandler oidcLogoutHandler() {
        return (request, response, authentication) -> {
            try {
                response.sendRedirect(endSessionEndpoint);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        };
    }
}

步骤 4:添加首页

我们使用 Thymeleaf 模板创建一个简单的 home.html 页面。当用户打开运行在 http://localhost:8080/ 上的页面时,会看到带有登录或登出按钮的页面:

步骤 5:添加控制器

接下来,我们创建一个控制器类来处理传入的请求。该控制器负责渲染 home.html 页面。当用户完成身份验证后,应用会获取用户的资料信息属性并用于渲染页面。

@Controller
public class HomeController {
    @GetMapping("/")
    String home() {
        return "home";
    }
}

步骤 6:运行应用

要运行应用,您可以执行 mvn spring-boot:run 目标,或者在编辑器中直接运行主文件 ExampleApplication.java。示例应用将运行在 http://localhost:8080/。

点击 登录 按钮,即可跳转到 Authany 登录页面。

您也可以在 Authany 管理台中自定义登录页面的 UI 外观。注册后,您会收到发送到邮箱的 OTP 验证码,用于验证身份。

登录新账号后,您将被重定向回主页:

您已经成功配置了 Spring Boot 应用,使其使用 Authany 进行身份验证。现在用户可以注册新账号、登录和登出。完整示例源码可以在 GitHub 上找到。

后续步骤

Authany 还能做更多的事。您可以探索其他登录方式,例如通过邮件发送魔法链接、社交登录,或 WhatsApp OTP。对于当前应用,您也可以在 Authany 管理台中添加更多用户。