概要
Spring Bootアプリケーションでリバースプロキシサーバー(例:Nginx)を介して通信している場合、本来は HTTPS でアクセスされているにも関わらず、アプリケーション側では HTTP として認識されてしまい、リダイレクト時にHTTPで返ってしまう ことがあります。
このような場合の 応急処置 として、HandlerInterceptor
の postHandle
メソッドで 強制的にHTTPSに書き換える方法 を実装したので、備忘録として残しておきます。
応急処置として記述したコード
応急処置コード
public class HandlerInterceptorImpl implements HandlerInterceptor {
@Override
public void postHandle(
@NonNull HttpServletRequest request,
@NonNull HttpServletResponse response,
@NonNull Object handler,
@Nullable ModelAndView modelAndView) throws Exception {
if (modelAndView != null) {
String viewName = modelAndView.getViewName();
if (StringUtils.hasLength(viewName) && viewName.startsWith("redirect:")) {
// 「redirect:」を除いた元のリダイレクト先URLを取得(例: "redirect:/login" → "/login")
String originUrl = viewName.replace("redirect:", "");
// 元のリダイレクト先URLをURIとして分解(パス、クエリを取り出せるようにする)
UriComponents originComponents = UriComponentsBuilder.fromUriString(originUrl).build();
// HTTPS用にリダイレクトURLを再構築
String secureRedirectUrl = "redirect:" + UriComponentsBuilder.newInstance()
.scheme("https")
.host(request.getServerName())
.port(request.getServerPort())
.path(request.getContextPath() + "/" + originComponents.getPath())
.query(originComponents.getQuery())
.build()
.toUriString();
// 再構築したURLをmodelAndViewにセット
modelAndView.setViewName(secureRedirectUrl);
}
}
}
}