Spring Boot集成Keycloak获取用户信息时触发500内部服务器错误
问题:获取登录用户信息时出现500内部服务器错误
获取access token后,将其填入Postman的Authorization→OAuth 2.0的access token字段,请求http://localhost:9000/api/v1/users/info接口时触发500 Internal Server Error,报错信息如下:
Failed to load URLs from http://localhost:8181/auth/realms/Client/.well-known/openid-configuration java.lang.Exception: Not Found Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception java.lang.NullPointerException: Cannot invoke "String.length()" because "this.input" is null
- 代码仓库:https://github.com/Rapter1990/SpringBootMicroservices
- 相关截图:

排查与解决步骤
1. 修复Keycloak配置路径问题
直接访问报错中的地址http://localhost:8181/auth/realms/Client/.well-known/openid-configuration,如果返回404,按以下情况处理:
- 领域名称错误:检查Keycloak后台的实际领域名称,确保配置中的
Client和后台创建的领域名拼写完全一致。 - 版本适配路径:若使用Keycloak 17及以上版本,官方已移除
/auth前缀,正确的OIDC配置地址应为http://localhost:8181/realms/[你的领域名]/.well-known/openid-configuration,同步修改服务端配置中的对应路径。
2. 验证服务端OIDC配置
检查Spring Boot服务的配置文件(application.yml/application.properties)中的JWT issuer配置:
spring: security: oauth2: resourceserver: jwt: issuer-uri: http://localhost:8181/auth/realms/Client # 替换为实际存在的领域地址,新版本去掉/auth
确保issuer-uri指向的Keycloak领域真实存在,且服务能正常访问该地址。
3. 解决空指针异常
空指针是因OIDC配置加载失败导致后续逻辑拿到null值,解决第一步的404问题后,该异常通常会自动消失。若仍存在:
- 用Keycloak的令牌校验接口(
/realms/[领域名]/protocol/openid-connect/token/introspect)验证Postman中使用的access token是否有效。 - 检查服务端token解析逻辑,确保配置缺失时不会触发空指针调用。
4. 确认网络连通性
确保运行Spring Boot服务的环境能正常访问Keycloak地址localhost:8181,若为容器部署,需确认容器间网络互通,避免服务端无法连接Keycloak。
内容的提问来源于stack exchange,提问作者Sercan Noyan Germiyanoğlu
相关产品推荐
相关产品推荐

