私は春のMVCのを使用しています@ControllerAdvice
し、@ExceptionHandler
REST APIをすべての例外を処理します。Web MVCコントローラーによってスローされた例外に対しては正常に機能しますが、コントローラーメソッドが呼び出される前に実行されるため、SpringSecurityカスタムフィルターによってスローされた例外に対しては機能しません。
トークンベースの認証を行うカスタムスプリングセキュリティフィルターがあります。
public class AegisAuthenticationFilter extends GenericFilterBean {
...
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
try {
...
} catch(AuthenticationException authenticationException) {
SecurityContextHolder.clearContext();
authenticationEntryPoint.commence(request, response, authenticationException);
}
}
}
このカスタムエントリポイントの場合:
@Component("restAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage());
}
}
そして、このクラスを使用して、例外をグローバルに処理します。
@ControllerAdvice
public class RestEntityResponseExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({ InvalidTokenException.class, AuthenticationException.class })
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
@ResponseBody
public RestError handleAuthenticationException(Exception ex) {
int errorCode = AegisErrorCode.GenericAuthenticationError;
if(ex instanceof AegisException) {
errorCode = ((AegisException)ex).getCode();
}
RestError re = new RestError(
HttpStatus.UNAUTHORIZED,
errorCode,
"...",
ex.getMessage());
return re;
}
}
私がする必要があるのは、春のセキュリティAuthenticationExceptionの場合でも詳細なJSON本文を返すことです。Spring SecurityAuthenticationEntryPointとSpringMVC @ExceptionHandlerを連携させる方法はありますか?
Spring Security3.1.4とSpringMVC3.2.4を使用しています。
OK、AuthenticationEntryPointから自分でjsonを書いてみましたが、うまくいきました。
テストのために、response.sendErrorを削除してAutenticationEntryPointを変更しました
@Component("restAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getOutputStream().println("{ \"error\": \"" + authenticationException.getMessage() + "\" }");
}
}
このようにして、Spring Security AuthenticationEntryPointを使用している場合でも、401と一緒にカスタムjsonデータを無許可で送信できます。
明らかに、テスト目的で行ったようにjsonをビルドすることはありませんが、いくつかのクラスインスタンスをシリアル化します。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加