我有一个授权服务器[Simple Class with an @SpringBootApplication
,
@RestController
,@Configuration
,@EnableAuthorizationServer
& oauth2安全]在端口8081
上运行,运行良好&使用POST
方法从POSTMAN请求时提供访问令牌以及键值对形式的必需参数,
http://localhost:8080/oauth/token
,但是如何在java中实现camel路由以通过在body中传递参数来获取访问令牌?
答案 0 :(得分:2)
这个问题更多的是关于使用Apache Camel发送multipart/form-data
。我前段时间正在使用它并使用自定义处理器解决它,使用multipart/form-data
将标题转换为Content-Disposition: form-data
格式。
这是我的处理器将标头转换为multipart/form-data
格式:
public class PrepareMultipartFormData implements Processor {
private String[] multipartHeaders;
public PrepareMultipartFormData(String... multipartHeaders) {
this.multipartHeaders = multipartHeaders;
}
@Override
public void process(Exchange exchange) throws Exception {
addMultipart(exchange.getIn(), multipartHeaders);
}
private static void addMultipart(Message message, String... multipartKeys){
final String boundary = "---------------------------"+RandomStringUtils.randomAlphanumeric(9);
message.setHeader(Exchange.CONTENT_TYPE, "multipart/form-data;boundary="+boundary);
StringBuilder sb = new StringBuilder("--").append(boundary);
for (String key: multipartKeys) {
sb.append("\r\n")
.append("Content-Disposition: form-data; name=\"").append(key).append("\"")
.append("\r\n\r\n")
.append(message.getHeader(key, String.class))
.append("\r\n")
.append("--").append(boundary);
}
message.setBody(sb.toString());
}
}
要向OAuth请求令牌发送,您需要发送:
authUsername
和authPassword
PrepareMultipartFormData
处理器PrepareMultipartFormData
处理器中的标头转换而来的
最终路线可以这种方式实施:
(用一些表达式替换常量,动态设置它。如果你只需要token
作为响应,添加一些解组,因为这条路由返回JSON)
from("direct:getTokenResponse")
.setHeader(Exchange.HTTP_METHOD, constant("POST"))
.setHeader(Exchange.HTTP_PATH, constant("oauth/token"))
.setHeader("grant_type", constant("password"))
.setHeader("username", constant("admin"))
.setHeader("password", constant("admin1234"))
.setHeader("client_id", constant("spring-security-oauth2-read-write-client"))
.process(new PrepareMultipartFormData("grant_type", "username", "password", "client_id"))
.to("http://localhost:8080?authMethod=Basic&authUsername=oauth-endpoint-username&authPassword=oauth-endpoint-password")
.convertBodyTo(String.class)
.to("log:response");
使用MultipartEntityBuilder更新答案以提供更短的PrepareMultipartFormData#addMultipart
实施。
private static void addMultipart(Message message, String... multipartKeys) throws Exception{
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
for (String key: multipartKeys) {
builder.addTextBody(key, message.getHeader(key, String.class));
}
HttpEntity resultEntity = builder.build();
message.setHeader(Exchange.CONTENT_TYPE, resultEntity.getContentType().getValue());
message.setBody(resultEntity.getContent());
}