Spring Security对接Authentik启动连接失败求助
解决Spring Security与Docker Compose部署的Authentik连接问题
核心问题分析
- 容器网络访问逻辑错误:浏览器用
localhost访问的是宿主机端口,但Docker Compose中容器间通信需要使用服务名称而非localhost,且要对应容器内部的端口(而非宿主机映射端口,除非你显式配置了端口映射的内部端口一致)。 - 自签名证书信任问题:Authentik使用默认自签名证书,Spring Boot的JVM默认不信任这类证书,导致TLS握手失败。
分步解决方案
1. 配置正确的Issuer URI
在application.yaml中,将OIDC的issuer-uri设置为Docker Compose内部可访问的地址:
假设你的Authentik服务在docker-compose.yml中定义的服务名为authentik,容器内部HTTP端口为80(默认配置),则正确的URI应为:
spring: security: oauth2: client: provider: authentik: issuer-uri: http://authentik:80/application/o/{name}
注意:不要加
localhost或宿主机IP,容器间通过服务名直接通信,Docker Compose会自动解析服务名到对应容器的IP。
2. 处理自签名证书信任问题
如果使用HTTPS(端口443),必须让Spring Boot信任Authentik的自签名证书,有两种方式:
方式一:将证书导入JVM信任存储(推荐生产环境)
- 从Authentik容器导出证书:
docker exec -it {authentik-container-name} cat /etc/authentik/certs/localhost.crt > authentik.crt
- 将证书导入Spring Boot使用的JVM信任存储(替换
$JAVA_HOME为你的JDK路径):
keytool -import -alias authentik -file authentik.crt -keystore $JAVA_HOME/jre/lib/security/cacerts -storepass changeit
- 重启Spring Boot服务,此时JVM会信任该证书。
方式二:禁用证书验证(仅开发环境)
在application.yaml中添加基础配置,再通过代码跳过SSL验证(不建议生产使用):
spring: security: oauth2: client: provider: authentik: issuer-uri: https://authentik:443/application/o/{name} jwk-set-uri: https://authentik:443/application/o/{name}/.well-known/jwks.json
@Configuration public class SSLConfig { @Bean public RestTemplate restTemplate() throws KeyManagementException, NoSuchAlgorithmException { TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) {} public void checkServerTrusted(X509Certificate[] certs, String authType) {} }}; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustAllCerts, new SecureRandom()); HttpClient httpClient = HttpClientBuilder.create().setSSLContext(sslContext).build(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); return new RestTemplate(factory); } }
3. 验证容器网络连通性
在Spring Boot容器内测试是否能访问Authentik:
docker exec -it {spring-boot-container-name} curl http://authentik:80/application/o/{name}/.well-known/openid-configuration
如果能返回JSON,说明网络没问题,问题出在证书或Spring配置。
4. 检查Spring Security OIDC配置完整性
确保你的客户端ID和客户端密钥配置正确,对应Authentik中创建的应用:
spring: security: oauth2: client: registration: authentik: client-id: {your-client-id} client-secret: {your-client-secret} authorization-grant-type: authorization_code redirect-uri: "{baseUrl}/login/oauth2/code/authentik" provider: authentik: issuer-uri: http://authentik:80/application/o/{name}
内容的提问来源于stack exchange,提问作者Robert Anderson
相关产品推荐
相关产品推荐

