我试图向一个keycloak REST API端点发出一个POST请求,请求的body内容为 applicationx-www-form-urlencoded 值。
下面是一个请求的cURL。
curl -X POST \
https://auth.beyondtime-stage.io/auth/realms/master/protocol/openid-connect/token \
-H 'cache-control: no-cache' \
-H 'content-type: application/x-www-form-urlencoded' \
-d 'username=admin&password=pass123&client_id=admin-cli&grant_type=password'
让我失望的是,我还没有找到用佯装来实现的方法
下面是我试过的一个例子。
@FeignClient(name = "beyondtime-io-kc-client", url = "${btio.keycloakUrl}", path = "/")
public interface KeycloakAdminClient {
@PostMapping(name="realms/master/protocol/openid-connect/token", consumes = "application/x-www-form-urlencoded")
String getAuthToken(@RequestParam("username") String username,
@RequestParam("password") String password,
@RequestParam("client_id") String clientId,
@RequestParam("grant_type") String grantType);
}
在我的pom.xml中,我使用的是:
spring-cloud-starter-openfeign 2.1.1.RELEASE。
我也试过加入 装模作样 依赖性和 @Param 而不是 @RequestParam但没有成功。
我在这里找到了解决方案 如何使用Spring Cloud Feign POST表单url编码的数据?
伪装客户。
import com.beyondtime.recruitmentservice.seafarer.entity.AuthTokenRequest;
import com.beyondtime.recruitmentservice.seafarer.entity.KeycloakAccessToken;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@FeignClient(name = "beyondtime-io-kc-client", url = "${btio.keycloakUrl}", path = "/", configuration = KeycloakAdminClient.Configuration.class)
public interface KeycloakAdminClient {
@PostMapping(value="realms/master/protocol/openid-connect/token", consumes = "application/x-www-form-urlencoded")
KeycloakAccessToken getAuthToken(@RequestBody AuthTokenRequest authTokenRequest);
class Configuration {
@Bean
Encoder feignFormEncoder(ObjectFactory<HttpMessageConverters> converters) {
return new SpringFormEncoder(new SpringEncoder(converters));
}
}
}
请求对象:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class AuthTokenRequest {
private String username;
private String password;
private String client_id;
private String grant_type;
}
响应对象:
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class KeycloakAccessToken {
@JsonProperty("access_token")
private String accessToken;
}