【问题标题】:POST request to get access token from keycloak gives 404 bad credentials - Spring boot从 keycloak 获取访问令牌的 POST 请求提供 404 错误凭据 - 春季启动
【发布时间】:2021-09-08 15:58:48
【问题描述】:

我正在尝试连接使用 SpringBoot 创建的 RestApi 以从 Keycloak 获取访问令牌。

这是我的代码:

Application.yml

keycloak:
  realm: ${CLIENT_RELM_NAME:registerApiRealm}
  auth-server-url: ${KEYCLOAK_URL_WITH_PATH:http://localhost:8080/auth}
  ssl-required: external
  #keycloak resource is the client ID
  resource: ${KEYCLOAK_CLIENT_NAME:registerApiClienty}
  #replace secret with your key
  credentials:
    secret: ${CLIENT_RELM_SECRET:12a658ea-b728-4f53-9948-492ef470363f}
  #The line below will prevent redirect to login page
  bearer-only: true

KeycloakServiceImpl.java

    @Component
    public class KeyCloakServiceImpl implements KeyCloakService {
    
        private static final Logger log = LoggerFactory.getLogger(RegistrationController.class);
    
        @Value("${keycloak.credentials.secret}")
        private String SECRETKEY;
    
        @Value("${keycloak.resource}")
        private String CLIENTID;
    
        @Value("${keycloak.auth-server-url}")
        private String AUTHURL;
    
        @Value("${keycloak.realm}")
        private String REALM;
    
        @Value("${admin.username}")
        private String ADMIN_USERNAME;
    
        @Value("${admin.password}")
        private String ADMIN_PASSWORD;
    
        @Autowired
        RestTemplate restTemplate;
    
    
        @Override
        public TokenDto getToken(UserCredentials userCredentials) {
    
            TokenDto responseToken = null;
            try {
    
                MultiValueMap<String, String> urlParameters = new LinkedMultiValueMap<>();
                urlParameters.add("grant_type", "password");
                urlParameters.add("client_id", CLIENTID);
                urlParameters.add("username", userCredentials.getUsername());
                urlParameters.add("password", userCredentials.getPassword());
                urlParameters.add("client_secret", SECRETKEY);
    
                responseToken = authenticate(urlParameters);
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return responseToken;
    
        }

 private TokenDto authenticate( MultiValueMap<String, String> urlParameters ) throws Exception {

        TokenDto tokenDto = new TokenDto();

        String uri = AUTHURL + "/realms/" + REALM + "/protocol/openid-connect/token";

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(urlParameters, httpHeaders);

        ResponseEntity<Object> result = restTemplate.exchange(uri, HttpMethod.POST, request, Object.class);
        log.info("{}", result);
        log.info("{}", result.getBody());

        LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) result.getBody();

        if (map != null) {
            tokenDto.setAccess_token(map.get("access_token").toString());
            tokenDto.setToken_type(map.get("token_type").toString());
            tokenDto.setRefresh_token(map.get("refresh_token").toString());
            tokenDto.setExpires_in(map.get("expires_in").toString());
            tokenDto.setScope(map.get("scope").toString());
        } else {
            return null;
        }

        return tokenDto;

    }

当我通过发送username 和`password` 使用Postaman 测试它时

{
    "username": "user",
    "password": "useruser35"
  
}

我收到以下错误:

org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request: [{"error":"invalid_client","error_description":"Invalid client credentials"}]

我不确定为什么要仔细检查我的用户是否已创建,我检查了 clientId 和 secret,一切似乎都很好。

我在这里缺少什么,任何建议表示赞赏。

【问题讨论】:

    标签: java spring-boot postman keycloak


    【解决方案1】:

    您的代码似乎有效。

    您可能需要查看this 手册以查看是否已正确配置 keycloak。

    您示例中的密码授予流程通常不是进行登录的首选方法。 您还可以通过 spring security 检索令牌,请参阅this link。网上有很多关于如何用spring security做oAuth2的例子。

    【讨论】:

      猜你喜欢
      • 2021-03-21
      • 2019-06-19
      • 2018-10-05
      • 2014-12-28
      • 1970-01-01
      • 2017-01-21
      • 2016-04-19
      • 2019-05-07
      • 2022-01-05
      相关资源
      最近更新 更多