Spring Boot+RestTemplate获取用户信息问题:仅Admin账号可成功
问题原因与解决方案
你的问题出在**硬编码使用了Admin客户端的凭证(admin_Client和secret_key)**来请求用户信息接口。普通用户的access token是关联到自身客户端的,和Admin客户端的凭证不匹配,导致接口身份校验失败,拒绝返回数据。
解决方案
用户信息接口(比如OpenID Connect标准的UserInfo端点)仅需当前登录用户的access token即可验证身份,无需携带Admin客户端的凭证。你需要调整请求逻辑:
- 移除请求体中的
CLIENT_ID和CLIENT_SECRET参数 - 将access token放入
Authorization请求头,格式为Bearer {accessToken} - 根据接口文档调整请求方法(多数UserInfo接口支持GET请求,无需表单提交)
修改后的代码示例
public UserDto getInfo() throws APIErrorException { UserInfoResponse userInfoResponse = null; HttpHeaders headers = new HttpHeaders(); // 使用Bearer Token传递用户身份 headers.setBearerAuth(accessToken); // 若接口要求特定Content-Type,按需设置;GET请求通常无需表单类型 HttpEntity<Void> request = new HttpEntity<>(headers); try { // 多数UserInfo接口为GET请求,若你的接口是POST,可改为HttpMethod.POST userInfoResponse = restTemplate.exchange( userInfoUrl, HttpMethod.GET, request, UserInfoResponse.class ).getBody(); } catch (Exception e) { throw new APIErrorException(ErrorCode.E444); } UserKeycloak userKeycloak = userMapperService.fromUserInfoResponse(userInfoResponse); return userMapperService.convertKeycloakToDto(userKeycloak); }
额外注意事项
- 如果你的用户信息接口确实要求POST请求,只需保留access token的正确传递(按接口文档要求放在头或表单中),不要混入Admin客户端凭证。
- 确保普通用户的access token已被授予访问该用户信息接口的权限(比如包含
profile、email等必要的scope)。
内容的提问来源于stack exchange,提问作者Guost
相关产品推荐
相关产品推荐

