0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Spring BootでHTTPSリダイレクトがHTTPになってしまう場合の応急処置

Posted at

概要

Spring Bootアプリケーションでリバースプロキシサーバー(例:Nginx)を介して通信している場合、本来は HTTPS でアクセスされているにも関わらず、アプリケーション側では HTTP として認識されてしまい、リダイレクト時にHTTPで返ってしまう ことがあります。

このような場合の 応急処置 として、HandlerInterceptorpostHandle メソッドで 強制的に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);
            }
        }
    }
}

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?