一种解决方案是使用WireMock 对keycloak 授权服务器进行存根。因此,您可以使用库spring-cloud-contract-wiremock(参见https://cloud.spring.io/spring-cloud-contract/1.1.x/multi/multi__spring_cloud_contract_wiremock.html),它提供了一个简单的spring boot 集成。您可以按照说明简单地添加依赖项。此外,我使用jose4j 创建模拟访问令牌,就像 Keycloak 和 JWT 一样。您所要做的就是为 Keycloak OpenId Configuration 和 JSON Web Key Storage 的端点存根,因为Keycloak 适配器 只请求那些验证授权标头中的访问令牌。
一个最小的独立工作示例,但需要在一个地方进行自定义(请参阅重要说明),下面列出了一些解释:
KeycloakTest.java:
@ExtendWith(SpringExtension.class)
@WebMvcTest(KeycloakTest.TestController.class)
@EnableConfigurationProperties(KeycloakSpringBootProperties.class)
@ContextConfiguration(classes= {KeycloakTest.TestController.class, SecurityConfig.class, CustomKeycloakSpringBootConfigResolver.class})
@AutoConfigureMockMvc
@AutoConfigureWireMock(port = 0) //random port, that is wired into properties with key wiremock.server.port
@TestPropertySource(locations = "classpath:wiremock.properties")
public class KeycloakTest {
private static RsaJsonWebKey rsaJsonWebKey;
private static boolean testSetupIsCompleted = false;
@Value("${wiremock.server.baseUrl}")
private String keycloakBaseUrl;
@Value("${keycloak.realm}")
private String keycloakRealm;
@Autowired
private MockMvc mockMvc;
@BeforeEach
public void setUp() throws IOException, JoseException {
if(!testSetupIsCompleted) {
// Generate an RSA key pair, which will be used for signing and verification of the JWT, wrapped in a JWK
rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
rsaJsonWebKey.setKeyId("k1");
rsaJsonWebKey.setAlgorithm(AlgorithmIdentifiers.RSA_USING_SHA256);
rsaJsonWebKey.setUse("sig");
String openidConfig = "{\n" +
" \"issuer\": \"" + keycloakBaseUrl + "/auth/realms/" + keycloakRealm + "\",\n" +
" \"authorization_endpoint\": \"" + keycloakBaseUrl + "/auth/realms/" + keycloakRealm + "/protocol/openid-connect/auth\",\n" +
" \"token_endpoint\": \"" + keycloakBaseUrl + "/auth/realms/" + keycloakRealm + "/protocol/openid-connect/token\",\n" +
" \"token_introspection_endpoint\": \"" + keycloakBaseUrl + "/auth/realms/" + keycloakRealm + "/protocol/openid-connect/token/introspect\",\n" +
" \"userinfo_endpoint\": \"" + keycloakBaseUrl + "/auth/realms/" + keycloakRealm + "/protocol/openid-connect/userinfo\",\n" +
" \"end_session_endpoint\": \"" + keycloakBaseUrl + "/auth/realms/" + keycloakRealm + "/protocol/openid-connect/logout\",\n" +
" \"jwks_uri\": \"" + keycloakBaseUrl + "/auth/realms/" + keycloakRealm + "/protocol/openid-connect/certs\",\n" +
" \"check_session_iframe\": \"" + keycloakBaseUrl + "/auth/realms/" + keycloakRealm + "/protocol/openid-connect/login-status-iframe.html\",\n" +
" \"registration_endpoint\": \"" + keycloakBaseUrl + "/auth/realms/" + keycloakRealm + "/clients-registrations/openid-connect\",\n" +
" \"introspection_endpoint\": \"" + keycloakBaseUrl + "/auth/realms/" + keycloakRealm + "/protocol/openid-connect/token/introspect\"\n" +
"}";
stubFor(WireMock.get(urlEqualTo(String.format("/auth/realms/%s/.well-known/openid-configuration", keycloakRealm)))
.willReturn(aResponse()
.withHeader("Content-Type", "application/json")
.withBody(openidConfig)
)
);
stubFor(WireMock.get(urlEqualTo(String.format("/auth/realms/%s/protocol/openid-connect/certs", keycloakRealm)))
.willReturn(aResponse()
.withHeader("Content-Type", "application/json")
.withBody(new JsonWebKeySet(rsaJsonWebKey).toJson())
)
);
testSetupIsCompleted = true;
}
}
@Test
public void When_access_token_is_in_header_Then_process_request_with_Ok() throws Exception {
ResultActions resultActions = this.mockMvc
.perform(get("/test")
.header("Authorization",String.format("Bearer %s", generateJWT(true)))
);
resultActions
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string("hello"));
}
@Test
public void When_access_token_is_missing_Then_redirect_to_login() throws Exception {
ResultActions resultActions = this.mockMvc
.perform(get("/test"));
resultActions
.andDo(print())
.andExpect(status().isFound())
.andExpect(redirectedUrl("/sso/login"));
}
private String generateJWT(boolean withTenantClaim) throws JoseException {
// Create the Claims, which will be the content of the JWT
JwtClaims claims = new JwtClaims();
claims.setJwtId(UUID.randomUUID().toString()); // a unique identifier for the token
claims.setExpirationTimeMinutesInTheFuture(10); // time when the token will expire (10 minutes from now)
claims.setNotBeforeMinutesInThePast(0); // time before which the token is not yet valid (2 minutes ago)
claims.setIssuedAtToNow(); // when the token was issued/created (now)
claims.setAudience("account"); // to whom this token is intended to be sent
claims.setIssuer(String.format("%s/auth/realms/%s",keycloakBaseUrl,keycloakRealm)); // who creates the token and signs it
claims.setSubject(UUID.randomUUID().toString()); // the subject/principal is whom the token is about
claims.setClaim("typ","Bearer"); // set type of token
claims.setClaim("azp","example-client-id"); // Authorized party (the party to which this token was issued)
claims.setClaim("auth_time", NumericDate.fromMilliseconds(Instant.now().minus(11, ChronoUnit.SECONDS).toEpochMilli()).getValue()); // time when authentication occured
claims.setClaim("session_state", UUID.randomUUID().toString()); // keycloak specific ???
claims.setClaim("acr", "0"); //Authentication context class
claims.setClaim("realm_access", Map.of("roles",List.of("offline_access","uma_authorization","user"))); //keycloak roles
claims.setClaim("resource_access", Map.of("account",
Map.of("roles", List.of("manage-account","manage-account-links","view-profile"))
)
); //keycloak roles
claims.setClaim("scope","profile email");
claims.setClaim("name", "John Doe"); // additional claims/attributes about the subject can be added
claims.setClaim("email_verified",true);
claims.setClaim("preferred_username", "doe.john");
claims.setClaim("given_name", "John");
claims.setClaim("family_name", "Doe");
// A JWT is a JWS and/or a JWE with JSON claims as the payload.
// In this example it is a JWS so we create a JsonWebSignature object.
JsonWebSignature jws = new JsonWebSignature();
// The payload of the JWS is JSON content of the JWT Claims
jws.setPayload(claims.toJson());
// The JWT is signed using the private key
jws.setKey(rsaJsonWebKey.getPrivateKey());
// Set the Key ID (kid) header because it's just the polite thing to do.
// We only have one key in this example but a using a Key ID helps
// facilitate a smooth key rollover process
jws.setKeyIdHeaderValue(rsaJsonWebKey.getKeyId());
// Set the signature algorithm on the JWT/JWS that will integrity protect the claims
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
// set the type header
jws.setHeader("typ","JWT");
// Sign the JWS and produce the compact serialization or the complete JWT/JWS
// representation, which is a string consisting of three dot ('.') separated
// base64url-encoded parts in the form Header.Payload.Signature
return jws.getCompactSerialization();
}
@RestController
public static class TestController {
@GetMapping("/test")
public String test() {
return "hello";
}
}
}
wiremock.properties:
wiremock.server.baseUrl=http://localhost:${wiremock.server.port}
keycloak.auth-server-url=${wiremock.server.baseUrl}/auth
测试设置
注解@AutoConfigureWireMock(port = 0) 将在随机端口启动一个WireMock 服务器,该端口自动设置为wiremock.server.port 属性,因此它可用于相应地覆盖Spring Boot Keycloak Adapter 的keycloak.auth-server-url 属性(请参阅wiremock.properties)
为了生成 JWT,用作 Access Token,我使用 jose4j 创建了一个 RSA 密钥对,声明为作为测试类属性,因为我确实需要在测试设置期间与 WireMock 服务器一起初始化它。
private static RsaJsonWebKey rsaJsonWebKey;
然后在测试设置期间初始化如下:
rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
rsaJsonWebKey.setKeyId("k1");
rsaJsonWebKey.setAlgorithm(AlgorithmIdentifiers.RSA_USING_SHA256);
rsaJsonWebKey.setUse("sig");
keyId 的选择无关紧要。你可以选择任何你想要的,只要它被设置好了。选择的算法和使用确实很重要,并且必须完全按照示例中的方式进行调整。
这样,Keycloak Stub 的 JSON Web Key Storage 端点可以相应地设置如下:
stubFor(WireMock.get(urlEqualTo(String.format("/auth/realms/%s/protocol/openid-connect/certs", keycloakRealm)))
.willReturn(aResponse()
.withHeader("Content-Type", "application/json")
.withBody(new JsonWebKeySet(rsaJsonWebKey).toJson())
)
);
除此之外,需要为 keycloak 存根另一个端点,如前所述。如果没有缓存,keycloak 适配器需要请求 openid 配置。对于一个最小的工作示例,所有端点都需要在配置中定义,即从 OpenId 配置端点返回:
String openidConfig = "{\n" +
" \"issuer\": \"" + keycloakBaseUrl + "/auth/realms/" + keycloakRealm + "\",\n" +
" \"authorization_endpoint\": \"" + keycloakBaseUrl + "/auth/realms/" + keycloakRealm + "/protocol/openid-connect/auth\",\n" +
" \"token_endpoint\": \"" + keycloakBaseUrl + "/auth/realms/" + keycloakRealm + "/protocol/openid-connect/token\",\n" +
" \"token_introspection_endpoint\": \"" + keycloakBaseUrl + "/auth/realms/" + keycloakRealm + "/protocol/openid-connect/token/introspect\",\n" +
" \"userinfo_endpoint\": \"" + keycloakBaseUrl + "/auth/realms/" + keycloakRealm + "/protocol/openid-connect/userinfo\",\n" +
" \"end_session_endpoint\": \"" + keycloakBaseUrl + "/auth/realms/" + keycloakRealm + "/protocol/openid-connect/logout\",\n" +
" \"jwks_uri\": \"" + keycloakBaseUrl + "/auth/realms/" + keycloakRealm + "/protocol/openid-connect/certs\",\n" +
" \"check_session_iframe\": \"" + keycloakBaseUrl + "/auth/realms/" + keycloakRealm + "/protocol/openid-connect/login-status-iframe.html\",\n" +
" \"registration_endpoint\": \"" + keycloakBaseUrl + "/auth/realms/" + keycloakRealm + "/clients-registrations/openid-connect\",\n" +
" \"introspection_endpoint\": \"" + keycloakBaseUrl + "/auth/realms/" + keycloakRealm + "/protocol/openid-connect/token/introspect\"\n" +
"}";
stubFor(WireMock.get(urlEqualTo(String.format("/auth/realms/%s/.well-known/openid-configuration", keycloakRealm)))
.willReturn(aResponse()
.withHeader("Content-Type", "application/json")
.withBody(openidConfig)
)
);
令牌生成
令牌的生成是在generateJWT() 中实现的,大量使用了 jose4j 。这里要注意的最重要的一点是,必须使用与在测试设置期间为wiremock 初始化的相同生成的JWK 的私钥。
jws.setKey(rsaJsonWebKey.getPrivateKey());
除此之外,代码主要改编自https://bitbucket.org/b_c/jose4j/wiki/JWT%20Examples的示例。
现在可以根据自己的特定测试设置调整或扩展声明。
发布的 sn-p 中的最小示例代表了 Keycloak 生成的 JWT 的典型示例。
测试执行
生成的 JWT 可以像往常一样在 Authorization Header 中用于向 REST 端点发送请求:
ResultActions resultActions = this.mockMvc
.perform(get("/test")
.header("Authorization",String.format("Bearer %s", generateJWT(true)))
);
为了表示一个独立的示例,测试类确实有一个简单的 Restcontroller 定义为内部类,用于测试。
@RestController
public static class TestController {
@GetMapping("/test")
public String test() {
return "hello";
}
}
重要提示
出于测试目的,我确实引入了自定义 TestController,因此有必要定义自定义 ContextConfiguration 以将其加载到 WebMvcTest 中,如下所示:
@ContextConfiguration(classes= {KeycloakTest.TestController.class, SecurityConfig.class, CustomKeycloakSpringBootConfigResolver.class})
除了 TestController 本身之外,还包括一堆关于 Spring Security 和 Keycloak Adapter 的配置 Bean,例如 SecurityConfig.class 和 CustomKeycloakSpringBootConfigResolver.class 以使其正常工作。当然,这些需要由您自己的配置替换。为了完整起见,这些类也将在下面列出:
SecurityConfig.java:
@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
SimpleAuthorityMapper grantedAuthorityMapper = new SimpleAuthorityMapper();
grantedAuthorityMapper.setPrefix("ROLE_");
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(grantedAuthorityMapper);
auth.authenticationProvider(keycloakAuthenticationProvider);
}
/*
* Workaround for reading the properties for the keycloak adapter (see https://stackoverflow.com/questions/57787768/issues-running-example-keycloak-spring-boot-app)
*/
@Bean
@Primary
public KeycloakConfigResolver keycloakConfigResolver(KeycloakSpringBootProperties properties) {
return new CustomKeycloakSpringBootConfigResolver(properties);
}
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
@Bean
@Override
@ConditionalOnMissingBean(HttpSessionManager.class)
protected HttpSessionManager httpSessionManager() {
return new HttpSessionManager();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http
.authorizeRequests()
.antMatchers("/**").hasRole("user")
.anyRequest().authenticated()
.and().csrf().disable();
}
}
CustomKeycloakSpringBootConfigResolver.java:
/*
* Workaround for reading the properties for the keycloak adapter (see https://stackoverflow.com/questions/57787768/issues-running-example-keycloak-spring-boot-app)
*/
@Configuration
public class CustomKeycloakSpringBootConfigResolver extends KeycloakSpringBootConfigResolver {
private final KeycloakDeployment keycloakDeployment;
public CustomKeycloakSpringBootConfigResolver(KeycloakSpringBootProperties properties) {
keycloakDeployment = KeycloakDeploymentBuilder.build(properties);
}
@Override
public KeycloakDeployment resolve(HttpFacade.Request facade) {
return keycloakDeployment;
}
}