此版本仍在开发中,尚未被视为稳定版本。如需最新稳定版本,请使用 Spring Security 7.0.4spring-doc.cadn.net.cn

通行密钥

Spring Security 提供对通行密钥(passkeys)的支持。 通行密钥是一种比密码更安全的身份验证方法,其基于WebAuthn构建。spring-doc.cadn.net.cn

为了使用通行密钥(passkey)进行身份验证,用户必须首先注册一个新凭据。 在凭据注册完成后,即可通过验证身份验证断言来使用该凭据进行身份验证。spring-doc.cadn.net.cn

必需的依赖项

首先,请将 spring-security-webauthn 依赖项添加到您的项目中。spring-doc.cadn.net.cn

这假设您正在使用 Spring Boot 或 Spring Security 的 BOM(物料清单)来管理 Spring Security 的版本,如 获取 Spring Security 中所述。spring-doc.cadn.net.cn

通行密钥依赖项
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-webauthn</artifactId>
</dependency>
dependencies {
    implementation "org.springframework.security:spring-security-webauthn"
}

配置

以下配置启用了通行密钥(passkey)身份验证。 它提供了一种在 #passkeys-register 路径下注册新凭据的方式,以及一个默认的登录页面,允许使用通行密钥进行身份验证spring-doc.cadn.net.cn

@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 实现持久化。 默认情况下使用内存持久化,但 JDBC 持久化也支持 JdbcPublicKeyCredentialUserEntityRepositoryJdbcUserCredentialRepository。 要配置基于 JDBC 的持久化,请将存储库暴露为 Bean:spring-doc.cadn.net.cn

@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 暴露出来(类似于上面的示例)来使用它们。spring-doc.cadn.net.cn

自定义 PublicKeyCredentialCreationOptionsRepository

PublicKeyCredentialCreationOptionsRepository 用于在请求之间持久化 PublicKeyCredentialCreationOptions。 默认情况下,它会将其持久化到 HttpSession 中,但有时用户可能需要自定义此行为。 这可以通过设置可选属性 creationOptionsRepository(如配置中所示)或通过暴露一个 PublicKeyCredentialCreationOptionsRepository Bean 来实现:spring-doc.cadn.net.cn

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

注册新凭证

为了使用通行密钥,用户必须首先注册新凭据spring-doc.cadn.net.cn

注册新凭据包含两个步骤:spring-doc.cadn.net.cn

  1. 请求注册选项spring-doc.cadn.net.cn

  2. 注册凭证spring-doc.cadn.net.cn

请求注册选项

注册新凭据的第一步是请求注册选项。 在 Spring Security 中,注册选项的请求通常使用 JavaScript 完成,如下所示:spring-doc.cadn.net.cn

Spring Security 提供了一个默认的注册页面,可用作如何注册凭据的参考。spring-doc.cadn.net.cn

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

上述请求将获取当前已认证用户的注册选项。 由于挑战值会被持久化(状态会发生变化),以便在注册时进行比对,因此该请求必须是 POST 请求,并包含 CSRF Tokens。spring-doc.cadn.net.cn

注册选项的响应
{
  "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.createspring-doc.cadn.net.cn

然后可以将返回的值作为 JSON 请求发送到服务器。 下面是一个注册请求的示例:spring-doc.cadn.net.cn

示例注册请求
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
}

验证身份断言

注册新凭据后,通行密钥即可被验证(认证)。spring-doc.cadn.net.cn

验证凭据包含两个步骤:spring-doc.cadn.net.cn

  1. 请求验证选项spring-doc.cadn.net.cn

  2. 验证凭据spring-doc.cadn.net.cn

请求验证选项

验证凭据的第一步是请求验证选项。 在 Spring Security 中,请求验证选项通常通过 JavaScript 完成,如下所示:spring-doc.cadn.net.cn

Spring Security 提供了一个默认的登录页面,可作为如何验证凭据的参考。spring-doc.cadn.net.cn

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

上述请求将获取验证选项。 由于挑战(challenge)会被持久化(状态会发生变化),以便在身份验证时进行比对,因此该请求必须是 POST 请求,并且包含 CSRF Tokens。spring-doc.cadn.net.cn

响应将包含用于获取凭证的选项,其中二进制值(例如 challenge)会以 base64url 编码形式呈现。spring-doc.cadn.net.cn

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

验证凭据

获取验证选项后,它们将被用于获取凭据。 要获取凭据,应用程序应在对二进制值(如 challenge)进行 base64url 解码后,将选项传递给 navigator.credentials.getspring-doc.cadn.net.cn

然后可以将 navigator.credentials.get 的返回值作为 JSON 请求发送到服务器。 二进制值(例如 rawIdresponse.*)必须进行 base64url 编码。 以下是一个身份验证请求的示例:spring-doc.cadn.net.cn

示例身份验证请求
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