操作指南:使用支持 PKCE 的单页应用进行身份验证

本指南展示了如何配置 Spring 授权服务器 以支持使用代码交换证明密钥 (PKCE) 的单页应用 (SPA)。本指南的目的是演示如何支持公共客户端并要求使用 PKCE 进行客户端身份验证。

Spring 授权服务器不会为公共客户端颁发刷新令牌。我们建议将 BFF (backend for frontend) 模式作为暴露公共客户端的替代方案。有关更多信息,请参阅 gh-297

启用 CORS

SPA 由静态资源组成,可以通过多种方式部署。它可以与后端分开部署,例如使用 CDN 或独立的 Web 服务器;也可以使用 Spring Boot 与后端一起部署。

当 SPA 托管在不同的域下时,可以使用跨域资源共享 (CORS) 允许应用程序与后端通信。

例如,如果你在本地端口 4200 上运行 Angular 开发服务器,你可以定义一个 CorsConfigurationSource @Bean,并配置 Spring Security 以使用 cors() DSL 允许预检请求,示例如下:

启用 CORS
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

	@Bean
	@Order(1)
	public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http)
			throws Exception {
		OAuth2AuthorizationServerConfigurer authorizationServerConfigurer =
				OAuth2AuthorizationServerConfigurer.authorizationServer();

		http
			.securityMatcher(authorizationServerConfigurer.getEndpointsMatcher())
			.with(authorizationServerConfigurer, (authorizationServer) ->
				authorizationServer
					.oidc(Customizer.withDefaults())	// Enable OpenID Connect 1.0
			)
			.authorizeHttpRequests((authorize) ->
				authorize
					.anyRequest().authenticated()
			)
			// Redirect to the login page when not authenticated from the
			// authorization endpoint
			.exceptionHandling((exceptions) -> exceptions
				.defaultAuthenticationEntryPointFor(
					new LoginUrlAuthenticationEntryPoint("/login"),
					new MediaTypeRequestMatcher(MediaType.TEXT_HTML)
				)
			);

		return http.cors(Customizer.withDefaults()).build();
	}

	@Bean
	@Order(2)
	public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http)
			throws Exception {
		http
			.authorizeHttpRequests((authorize) -> authorize
				.anyRequest().authenticated()
			)
			// Form login handles the redirect to the login page from the
			// authorization server filter chain
			.formLogin(Customizer.withDefaults());

		return http.cors(Customizer.withDefaults()).build();
	}

	@Bean
	public CorsConfigurationSource corsConfigurationSource() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		CorsConfiguration config = new CorsConfiguration();
		config.addAllowedHeader("*");
		config.addAllowedMethod("*");
		config.addAllowedOrigin("http://127.0.0.1:4200");
		config.setAllowCredentials(true);
		source.registerCorsConfiguration("/**", config);
		return source;
	}

}
点击上方代码示例中的“展开折叠文本”图标以显示完整示例。

配置公共客户端

SPA 无法安全地存储凭据,因此必须被视为公共客户端。公共客户端应被要求使用代码交换证明密钥 (PKCE)。

延续前面的示例,你可以配置 Spring 授权服务器以支持使用客户端身份验证方法 none 并要求使用 PKCE 的公共客户端,示例如下:

  • Yaml

  • Java

spring:
  security:
    oauth2:
      authorizationserver:
        client:
          public-client:
            registration:
              client-id: "public-client"
              client-authentication-methods:
                - "none"
              authorization-grant-types:
                - "authorization_code"
              redirect-uris:
                - "http://127.0.0.1:4200"
              scopes:
                - "openid"
                - "profile"
            require-authorization-consent: true
            require-proof-key: true
@Bean
public RegisteredClientRepository registeredClientRepository() {
	RegisteredClient publicClient = RegisteredClient.withId(UUID.randomUUID().toString())
		.clientId("public-client")
		.clientAuthenticationMethod(ClientAuthenticationMethod.NONE)
		.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
		.redirectUri("http://127.0.0.1:4200")
		.scope(OidcScopes.OPENID)
		.scope(OidcScopes.PROFILE)
		.clientSettings(ClientSettings.builder()
			.requireAuthorizationConsent(true)
			.requireProofKey(true)
			.build()
		)
		.build();

	return new InMemoryRegisteredClientRepository(publicClient);
}
requireProofKey 设置对于防止PKCE 降级攻击非常重要。

与客户端进行身份验证

服务器配置为支持公共客户端后,一个常见问题是:如何对客户端进行身份验证并获取访问令牌?简短的回答是:与对任何其他客户端进行身份验证的方式相同。

SPA 是基于浏览器的应用程序,因此使用与其他任何客户端相同的基于重定向的流程。这个问题通常与期望通过 REST API 执行身份验证有关,但这不适用于 OAuth2。

更详细的回答需要理解 OAuth2 和 OpenID Connect 中涉及的流程,在这里是授权码流程。授权码流程的步骤如下:

  1. 客户端通过重定向到授权端点发起 OAuth2 请求。对于公共客户端,此步骤包括生成 code_verifier 并计算 code_challenge,然后将其作为查询参数发送。

  2. 如果用户未进行身份验证,授权服务器将重定向到登录页面。身份验证后,用户再次重定向回授权端点。

  3. 如果用户未同意请求的范围且需要同意,则会显示同意页面。

  4. 用户同意后,授权服务器会生成 authorization_code 并通过 redirect_uri 重定向回客户端。

  5. 客户端通过查询参数获取 authorization_code 并向令牌端点发起请求。对于公共客户端,此步骤包括发送 code_verifier 参数而不是凭据进行身份验证。

如你所见,这个流程相当复杂,本概述仅触及皮毛。

建议你使用单页应用框架支持的强大客户端库来处理授权码流程。