Passkeys

Spring Security 为通行密钥提供支持。通行密钥是一种比密码更安全的认证方法,并基于WebAuthn构建。

为了使用通行密钥进行身份验证,用户必须首先注册新凭据。凭据注册后,可以通过验证身份验证断言来使用它进行身份验证。

所需依赖项

首先,将 webauthn4j-core 依赖项添加到您的项目中。

这假设您正在使用 Spring Boot 或 Spring Security 的 BOM 管理 Spring Security 的版本,如获取 Spring Security 中所述。

通行密钥依赖项
  • Maven

  • Gradle

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
    <groupId>com.webauthn4j</groupId>
    <artifactId>webauthn4j-core</artifactId>
    <version>0.29.7.RELEASE</version>
</dependency>
depenendencies {
    implementation "org.springframework.security:spring-security-web"
    implementation "com.webauthn4j:webauthn4j-core:0.29.7.RELEASE"
}

配置

以下配置启用通行密钥身份验证。它提供了一种在 /webauthn/register 注册新凭据的方式,以及一个允许使用通行密钥进行身份验证的默认登录页面。

  • Java

  • Kotlin

@Bean
SecurityFilterChain filterChain(HttpSecurity http) {
	// ...
	http
		// ...
		.formLogin(withDefaults())
		.webAuthn((webAuthn) -> webAuthn
			.rpId("example.com")
			.allowedOrigins("https://example.com")
			// optional properties
			.creationOptionsRepository(new CustomPublicKeyCredentialCreationOptionsRepository())
			.messageConverter(new CustomHttpMessageConverter())
		);
	return http.build();
}

@Bean
UserDetailsService userDetailsService() {
	UserDetails userDetails = User.withDefaultPasswordEncoder()
		.username("user")
		.password("password")
		.roles("USER")
		.build();

	return new InMemoryUserDetailsManager(userDetails);
}
@Bean
open fun filterChain(http: HttpSecurity): SecurityFilterChain {
	// ...
	http {
		webAuthn {
			rpId = "example.com"
			allowedOrigins = setOf("https://example.com")
			// optional properties
			creationOptionsRepository = CustomPublicKeyCredentialCreationOptionsRepository()
			messageConverter = CustomHttpMessageConverter()
		}
	}
}

@Bean
open fun userDetailsService(): UserDetailsService {
	val userDetails = User.withDefaultPasswordEncoder()
		.username("user")
		.password("password")
		.roles("USER")
		.build()
	return InMemoryUserDetailsManager(userDetails)
}

JDBC & 自定义持久化

WebAuthn 使用 PublicKeyCredentialUserEntityRepositoryUserCredentialRepository 执行持久化。默认使用内存持久化,但通过 JdbcPublicKeyCredentialUserEntityRepositoryJdbcUserCredentialRepository 支持 JDBC 持久化。要配置基于 JDBC 的持久化,请将存储库公开为 Bean。

  • Java

  • Kotlin

@Bean
JdbcPublicKeyCredentialUserEntityRepository jdbcPublicKeyCredentialRepository(JdbcOperations jdbc) {
	return new JdbcPublicKeyCredentialUserEntityRepository(jdbc);
}

@Bean
JdbcUserCredentialRepository jdbcUserCredentialRepository(JdbcOperations jdbc) {
	return new JdbcUserCredentialRepository(jdbc);
}
@Bean
fun jdbcPublicKeyCredentialRepository(jdbc: JdbcOperations): JdbcPublicKeyCredentialUserEntityRepository {
    return JdbcPublicKeyCredentialUserEntityRepository(jdbc)
}

@Bean
fun jdbcUserCredentialRepository(jdbc: JdbcOperations): JdbcUserCredentialRepository {
    return JdbcUserCredentialRepository(jdbc)
}

如果 JDBC 不能满足您的需求,您可以创建自己的接口实现,并通过将其公开为 Bean 来使用它们,类似于上面的示例。

自定义 PublicKeyCredentialCreationOptionsRepository

PublicKeyCredentialCreationOptionsRepository 用于在请求之间持久化 PublicKeyCredentialCreationOptions。默认是将其持久化到 HttpSession 中,但有时用户可能需要自定义此行为。这可以通过在配置中演示的 creationOptionsRepository 可选属性来完成,或者通过公开一个 PublicKeyCredentialCreationOptionsRepository Bean 来完成。

  • Java

  • Kotlin

@Bean
CustomPublicKeyCredentialCreationOptionsRepository creationOptionsRepository() {
	return new CustomPublicKeyCredentialCreationOptionsRepository();
}
@Bean
open fun creationOptionsRepository(): CustomPublicKeyCredentialCreationOptionsRepository {
	return CustomPublicKeyCredentialCreationOptionsRepository()
}

注册新凭据

为了使用通行密钥,用户必须首先注册新凭据

注册新凭据包括两个步骤

  1. 请求注册选项

  2. 注册凭据

请求注册选项

注册新凭据的第一步是请求注册选项。在 Spring Security 中,请求注册选项通常使用 JavaScript 完成,如下所示

Spring Security 提供了一个默认注册页面,可以用作注册凭据的参考。

请求注册选项
POST /webauthn/register/options
X-CSRF-TOKEN: 4bfd1575-3ad1-4d21-96c7-4ef2d9f86721

上述请求将获取当前已认证用户的注册选项。由于质询已持久化(状态已更改),以便在注册时进行比较,因此请求必须是 POST 并包含 CSRF 令牌。

注册选项响应
{
  "rp": {
    "name": "SimpleWebAuthn Example",
    "id": "example.localhost"
  },
  "user": {
    "name": "[email protected]",
    "id": "oWJtkJ6vJ_m5b84LB4_K7QKTCTEwLIjCh4tFMCGHO4w",
    "displayName": "[email protected]"
  },
  "challenge": "q7lCdd3SVQxdC-v8pnRAGEn1B2M-t7ZECWPwCAmhWvc",
  "pubKeyCredParams": [
    {
      "type": "public-key",
      "alg": -8
    },
    {
      "type": "public-key",
      "alg": -7
    },
    {
      "type": "public-key",
      "alg": -257
    }
  ],
  "timeout": 300000,
  "excludeCredentials": [],
  "authenticatorSelection": {
    "residentKey": "required",
    "userVerification": "preferred"
  },
  "attestation": "none",
  "extensions": {
    "credProps": true
  }
}

注册凭据

获取注册选项后,它们用于创建要注册的凭据。要注册新凭据,应用程序应在对 user.idchallengeexcludeCredentials[].id 等二进制值进行 base64url 解码后,将选项传递给 navigator.credentials.create

然后可以将返回的值作为 JSON 请求发送到服务器。示例如下所示

注册请求示例
POST /webauthn/register
X-CSRF-TOKEN: 4bfd1575-3ad1-4d21-96c7-4ef2d9f86721

{
  "publicKey": { (1)
    "credential": {
      "id": "dYF7EGnRFFIXkpXi9XU2wg",
      "rawId": "dYF7EGnRFFIXkpXi9XU2wg",
      "response": {
        "attestationObject": "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YViUy9GqwTRaMpzVDbXq1dyEAXVOxrou08k22ggRC45MKNhdAAAAALraVWanqkAfvZZFYZpVEg0AEHWBexBp0RRSF5KV4vV1NsKlAQIDJiABIVggQjmrekPGzyqtoKK9HPUH-8Z2FLpoqkklFpFPQVICQ3IiWCD6I9Jvmor685fOZOyGXqUd87tXfvJk8rxj9OhuZvUALA",
        "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoiSl9RTi10SFJYRWVKYjlNcUNrWmFPLUdOVmlibXpGVGVWMk43Z0ptQUdrQSIsIm9yaWdpbiI6Imh0dHBzOi8vZXhhbXBsZS5sb2NhbGhvc3Q6ODQ0MyIsImNyb3NzT3JpZ2luIjpmYWxzZX0",
        "transports": [
          "internal",
          "hybrid"
        ]
      },
      "type": "public-key",
      "clientExtensionResults": {},
      "authenticatorAttachment": "platform"
    },
    "label": "1password" (2)
  }
}
1 调用 navigator.credentials.create 并对二进制值进行 base64url 编码的结果。
2 用户选择的与此凭据关联的标签,以帮助用户区分凭据。
注册成功响应示例
HTTP/1.1 200 OK

{
  "success": true
}

验证身份验证断言

注册新凭据后,通行密钥可以被验证(认证)。

验证凭据包括两个步骤

  1. 请求验证选项

  2. 验证凭据

请求验证选项

验证凭据的第一步是请求验证选项。在 Spring Security 中,请求验证选项通常使用 JavaScript 完成,如下所示

Spring Security 提供了一个默认的登录页面,可以用作验证凭据的参考。

请求验证选项
POST /webauthn/authenticate/options
X-CSRF-TOKEN: 4bfd1575-3ad1-4d21-96c7-4ef2d9f86721

上述请求将获取验证选项。由于质询已持久化(状态已更改),以便在身份验证时进行比较,因此请求必须是 POST 并包含 CSRF 令牌。

响应将包含用于获取凭据的选项,其中包含诸如 challenge 等 base64url 编码的二进制值。

验证选项响应示例
{
  "challenge": "cQfdGrj9zDg3zNBkOH3WPL954FTOShVy0-CoNgSewNM",
  "timeout": 300000,
  "rpId": "example.localhost",
  "allowCredentials": [],
  "userVerification": "preferred",
  "extensions": {}
}

验证凭据

获取验证选项后,它们将用于获取凭据。要获取凭据,应用程序应在对 challenge 等二进制值进行 base64url 解码后,将选项传递给 navigator.credentials.get

然后可以将 navigator.credentials.get 的返回值作为 JSON 请求发送到服务器。rawIdresponse.* 等二进制值必须进行 base64url 编码。示例如下所示

身份验证请求示例
POST /login/webauthn
X-CSRF-TOKEN: 4bfd1575-3ad1-4d21-96c7-4ef2d9f86721

{
  "id": "dYF7EGnRFFIXkpXi9XU2wg",
  "rawId": "dYF7EGnRFFIXkpXi9XU2wg",
  "response": {
    "authenticatorData": "y9GqwTRaMpzVDbXq1dyEAXVOxrou08k22ggRC45MKNgdAAAAAA",
    "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiRFVsRzRDbU9naWhKMG1vdXZFcE9HdUk0ZVJ6MGRRWmxUQmFtbjdHQ1FTNCIsIm9yaWdpbiI6Imh0dHBzOi8vZXhhbXBsZS5sb2NhbGhvc3Q6ODQ0MyIsImNyb3NzT3JpZ2luIjpmYWxzZX0",
    "signature": "MEYCIQCW2BcUkRCAXDmGxwMi78jknenZ7_amWrUJEYoTkweldAIhAMD0EMp1rw2GfwhdrsFIeDsL7tfOXVPwOtfqJntjAo4z",
    "userHandle": "Q3_0Xd64_HW0BlKRAJnVagJTpLKLgARCj8zjugpRnVo"
  },
  "clientExtensionResults": {},
  "authenticatorAttachment": "platform"
}
身份验证成功响应示例
HTTP/1.1 200 OK

{
  "redirectUrl": "/", (1)
  "authenticated": true (2)
}
1 要重定向到的 URL
2 指示用户已通过身份验证
身份验证失败响应示例
HTTP/1.1 401 OK
© . This site is unofficial and not affiliated with VMware.