ビジネス・シナリオ:クライアントはjsonデータを暗号化し、Base64文字列にエンコードしてサーバーに送信します。サーバはそれを復号化します。RequestBodyAdviceを使用すると、Controllerのコードを変更することなく簡単にこれを行うことができます。
RequestBodyAdvice
HttpMessageConverterこのインターフェイスは、.NET Framework によってリクエストボディデータが変換される前後に使用できる一連のメソッドを定義します。何らかのロジックコードを実行します。通常は復号を行うために使われます。
import java.io.IOException;
import java.lang.reflect.Type;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.lang.Nullable;
public interface RequestBodyAdvice {
/**
* このメソッドは、現在のリクエストと、beforeBodyReadメソッドを実行するかどうかを決定するために使われる。
* @param handlerメソッドのパラメータ・オブジェクト
* @param handlerメソッドのパラメータ・タイプ
* @param 使用されるHttpメッセージコンバータクラスのタイプ。
* @return trueを返すと、beforeBodyReadが実行される。
*/
boolean supports(MethodParameter methodParameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType);
/**
* Httpメッセージコンバーターが変換を実行する。
* @param クライアントのリクエストデータ
* @param handlerメソッドのパラメータ・オブジェクト
* @param handlerメソッドのパラメータ・タイプ
* @param 使用されるHttpメッセージコンバータクラスのタイプ。
* @return カスタム HttpInputMessage を返す。
*/
HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException;
/**
* 変換はHttpメッセージコンバータで実行され、その後に
* @param 変換されたオブジェクト
* @param クライアントのリクエストデータ
* @param handlerメソッドのパラメータ・タイプ
* @param handlerメソッドのパラメータ・タイプ
* @param 使用されるHttpメッセージコンバータクラスタイプ
* @return 新しいオブジェクトを返す
*/
Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType);
/**
* 上記と同じだが、このメソッドはボディが空の場合を処理する。
*/
@Nullable
Object handleEmptyBody(@Nullable Object body, HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType);
}
中心となるメソッドは supports で、beforeBodyRead メソッドを実行するかどうかを決定する boolean 値を返します。主なロジックは、beforeBodyRead メソッドでクライアントのリクエストボディを復号化することです。
RequestBodyAdviceAdapter
RequestBodyAdvice インターフェイスを実装したアダプタ抽象クラスです。
import java.io.IOException;
import java.lang.reflect.Type;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.lang.Nullable;
public abstract class RequestBodyAdviceAdapter implements RequestBodyAdvice {
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType)
throws IOException {
return inputMessage;
}
@Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
return body;
}
@Override
@Nullable
public Object handleEmptyBody(@Nullable Object body, HttpInputMessage inputMessage,
MethodParameter parameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) {
return body;
}
}
デモ: クライアントの AES 暗号化されたリクエストボディの復号化
クライアントは AES アルゴリズムで json データを暗号化し、リクエストボディとして Base64 文字列にエンコードしてサーバにリクエストします。サーバはRequestBodyAdviceで復号化を行います。
RequestBodyDecodeAdvice
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;
@RestControllerAdvice
public class RequestBodyDecodeAdvice extends RequestBodyAdviceAdapter {
/**
* 128ビットのAESキー
*/
private static final byte[] AES_KEY = "1111111111111111".getBytes(StandardCharsets.US_ASCII);
@Override
public boolean supports(MethodParameter methodParameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) {
/**
* このシステムでは、jsonデータのHttpメッセージ・コンバータとしてGsonを使用している。
*/
return GsonHttpMessageConverter.class.isAssignableFrom(converterType);
}
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
// 暗号化されたリクエスト・ボディを読む
byte[] body = new byte[inputMessage.getBody().available()];
inputMessage.getBody().read(body);
try {
// AESを使って復号化した
body = this.decrypt(Base64.getDecoder().decode(body), AES_KEY);
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException
| BadPaddingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
// 復号化されたデータを使って新しい読み取りストリームを構築する。
InputStream rawInputStream = new ByteArrayInputStream(body);
return new HttpInputMessage() {
@Override
public HttpHeaders getHeaders() {
return inputMessage.getHeaders();
}
@Override
public InputStream getBody() throws IOException {
return rawInputStream;
}
};
}
/**
* AES
*
* @param data
* @param key
* @return
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public byte[] decrypt(byte[] data, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException,
NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = getCipher(key, Cipher.DECRYPT_MODE);
return cipher.doFinal(data);
}
private Cipher getCipher(byte[] key, int model)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(model, secretKeySpec);
return cipher;
}
}
TestController
ほとんど何も変更せず、クライアントのリクエスト本文を出力するだけのシンプルなものです。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.google.gson.JsonObject;
@RestController
@RequestMapping("/test")
public class TestController {
private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class);
@PostMapping
public Object test (@RequestBody JsonObject requestBody) {
LOGGER.info("requestBody={}", requestBody);
return requestBody;
}
}
クライアント
元のデータを同じAESキーで暗号化
Gg/hLfWllxXF7KkzeNTPELCZ3jjxgHL24tJWPhO+O7KS5vAS1ag9xmtjP94L8p8BY+HMggCL1mvVEHEL8+FwSSjWYLln8SZk4CuWil2x4sI=
Postmanを使ったリクエスト
サーバは復号化されたリクエストボディで応答します。
サーバログ
2020-07-22 13:39:31.870 INFO 2684 --- [ XNIO-1 task-1] TestController : requestBody={"name":"SpringBoot ,"site":"https://.io"}
データの復号化に成功し、json オブジェクトのエンコードを終了しました。




