我很难思考如何让这个特定的设置发挥作用。我正在将我的身份验证服务器 (ghcr.io/navikt/mock-oauth2-server) 作为与我的 api 服务器(Spring Boot 应用程序)分开的容器运行,但它们位于同一网络上。从在本地计算机上执行的测试中,我想联系身份验证服务器并获取有效的(不记名?)令牌(没有任何提示或登录页面),api 服务器根据身份验证服务器进行验证,并最终允许客户端访问API。
首先,所描述的设置对于测试我的 api 的安全性而言是否有效?
其次,我在 api 服务器端一定缺少一些东西,因为请求总是抛出“无法获取密钥”的异常,我无法弄清楚我到底需要添加什么。我在异常的根源中看到 401,但它是针对服务器还是客户端?在 api 服务器上启用调试的完整堆栈跟踪:https://pastebin.com/e0MPaEnP
服务器:
applications.yml:
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://localhost:8080/default
jwk-set-uri: http://localhost:8080/default/jwks
安全配置:
@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
return http.authorizeExchange(exchanges -> exchanges.anyExchange().authenticated())
.csrf(csrfSpec -> csrfSpec.disable()) // Required for implicit flow
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
.build();
}
}
测试:
public class AuthorizationContainer extends GenericContainer<AuthorizationContainer> {
private static final DockerImageName AUTHORIZATION_IMAGE = DockerImageName.parse("ghcr.io/navikt/mock-oauth2-server:2.0.0");
private static final int APP_PORT = 8080;
public AuthorizationContainer() {
super(AUTHORIZATION_IMAGE);
addFixedExposedPort(APP_PORT, APP_PORT); // Easy of use for curl
waitingFor(Wait.forHttp("/isalive").forStatusCode(200));
}
}
要在没有提示的情况下获取令牌,您可以使用 client_credentials 流程。如果您想使用授权代码流程,您可能必须使用 Protractor 之类的端到端测试框架来模拟用户交互(如果在授权服务器上激活了多因素身份验证,这将变得很棘手)。
但是,我建议在单元或集成测试期间不要使用授权服务器的测试容器:它比使用 MockMvc 或 WebTestClient 的模拟
Authentication
慢得多(或者在测试 @Service 或 @Service 等组件时不使用 Web 客户端) @存储库)。
您可能会发现我写的这篇文章很有用,即使新版本已经准备好发布(应该很快)。