Spring Security – 403 Forbidden / Access Deniedページのカスタマイズ
1. 前書き
この記事では、customize the access denied page in a Spring Security projectを実行する方法を示します。
これは、Spring Security構成またはweb.xmlファイルのWebアプリケーション構成のいずれかを介して実現できます。
残りのセクションでは、これらの各オプションをさらに詳しく見ていきます。
2. カスタムJSP
3. Spring Securityの構成
デフォルトでは、Spring SecurityにはタイプAuthenticationExceptionおよびAccessDeniedExceptionの例外を処理するExceptionTranslationFilterが定義されています。 後者は、AccessDeniedHandlerImplクラスを使用するaccessDeniedHandler,と呼ばれるプロパティを介して行われます。
上で作成した独自のページを使用するようにこの動作をカスタマイズするには、ExceptionTranslationFilterクラスのプロパティをオーバーライドする必要があります。 これは、Java構成またはXML構成のいずれかで実行できます。
3.1. アクセス拒否ページ
Javaを使用して、HttpSecurity要素の構成中にwe can customize the 403 error handling process by using the accessDeniedPage() or accessDeniedHandler() methodsを使用します。
“/admin/**のURLをADMINロールに制限し、アクセス拒否ページをカスタムaccessDenied.jspページに設定する認証構成を作成しましょう。
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
// ...
.and()
.exceptionHandling().accessDeniedPage("/accessDenied.jsp");
}
アクセス拒否ページの同等のXML構成を見てみましょう。
3.2. アクセス拒否ハンドラー
ページの代わりにアクセス拒否ハンドラーを使用すると、403ページにリダイレクトする前に実行するカスタムロジックを定義できるという利点があります。 このため、we need to create a class that implements the AccessDeniedHandler interfaceは、handle()メソッドをオーバーライドします。
アクセスが拒否されたすべての試行に対して、試行を行ったユーザーとアクセスしようとした保護されたURLを含む警告メッセージをログに記録するカスタムAccessDeniedHandlerクラスを作成しましょう。
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
public static final Logger LOG
= Logger.getLogger(CustomAccessDeniedHandler.class);
@Override
public void handle(
HttpServletRequest request,
HttpServletResponse response,
AccessDeniedException exc) throws IOException, ServletException {
Authentication auth
= SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
LOG.warn("User: " + auth.getName()
+ " attempted to access the protected URL: "
+ request.getRequestURI());
}
response.sendRedirect(request.getContextPath() + "/accessDenied");
}
}
セキュリティ構成では、we’ll define the bean and set the custom AccessDeniedHandler:
@Bean
public AccessDeniedHandler accessDeniedHandler(){
return new CustomAccessDeniedHandler();
}
//...
.exceptionHandling().accessDeniedHandler(accessDeniedHandler());
XMLを使用して上記で定義したCustomAccessDeniedHandlerクラスを構成する場合、構成は少し異なります。
4. アプリケーション構成
Handling the access denied error can be done through the web.xml file of a web application, by defining an error-page tag.これには、インターセプトするステータスコードを指定するerror-code,と呼ばれる2つのサブタグと、エラーコードが発生した場合にユーザーがリダイレクトされるURLを示すlocation,が含まれます。
403
/accessDenied
Spring Bootの場合のように、アプリケーションにweb.xmlファイルがない場合、Springアノテーションは現在、error-pageタグの正確な代替手段を提供していません。 Springのドキュメントによると、この場合、推奨されるアプローチは、セクション3に示されているメソッドaccessDeniedPage()およびaccessDeniedHandler()を使用することです。
5. 結論
この簡単な記事では、カスタム403ページを使用してアクセス拒否エラーを処理できるさまざまな方法について詳しく説明しました。
記事の完全なソースコードはGitHub projectにあります。