From 317a82b74fb62c491731e02bfc3fd664ef1bea1b Mon Sep 17 00:00:00 2001 From: Pekka Helenius Date: Sat, 3 Oct 2020 01:24:17 +0300 Subject: [PATCH] Implement BookStoreAccessDeniedHandler Signed-off-by: Pekka Helenius --- .../session/BookStoreAccessDeniedHandler.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 bookstore/src/main/java/com/fjordtek/bookstore/service/session/BookStoreAccessDeniedHandler.java diff --git a/bookstore/src/main/java/com/fjordtek/bookstore/service/session/BookStoreAccessDeniedHandler.java b/bookstore/src/main/java/com/fjordtek/bookstore/service/session/BookStoreAccessDeniedHandler.java new file mode 100644 index 0000000..c4d5e64 --- /dev/null +++ b/bookstore/src/main/java/com/fjordtek/bookstore/service/session/BookStoreAccessDeniedHandler.java @@ -0,0 +1,40 @@ +package com.fjordtek.bookstore.service.session; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.stereotype.Component; + +import com.fjordtek.bookstore.service.HttpServerLogger; + +@Component +public class BookStoreAccessDeniedHandler implements AccessDeniedHandler { + + private HttpServerLogger httpServerLogger = new HttpServerLogger(); + + @Override + public void handle( + HttpServletRequest requestData, + HttpServletResponse responseData, + AccessDeniedException accessDeniedException + ) throws IOException, ServletException { + + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + + if (auth != null) { + responseData.setStatus(HttpServletResponse.SC_FORBIDDEN); + httpServerLogger.log(requestData, responseData); + } + + responseData.setHeader("Location", "/"); + responseData.setStatus(302); + } + +} \ No newline at end of file