Advanced Handler Interceptors (#672)

* Expression-Based Access Control

PermitAll, hasRole, hasAnyRole etc.
I modified classes regards to Security

* Added test cases for Spring Security Expressions

* Handler Interceptor - logging example

* Test for logger interceptor

* Removed conflicted part

* UserInterceptor (adding user information to model)

* Spring Handler Interceptor - session timers
This commit is contained in:
maibin 2016-09-07 08:14:26 +02:00 committed by Grzegorz Piwowarek
parent 9c1b87d3e5
commit 113afd40d4
4 changed files with 133 additions and 1 deletions

View File

@ -0,0 +1,16 @@
package org.baeldung.spring;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.request.RequestContextListener;
public class ListenerConfig implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext sc) throws ServletException {
// Manages the lifecycle of the root application context
sc.addListener(new RequestContextListener());
}
}

View File

@ -1,6 +1,7 @@
package org.baeldung.spring; package org.baeldung.spring;
import org.baeldung.web.interceptor.LoggerInterceptor; import org.baeldung.web.interceptor.LoggerInterceptor;
import org.baeldung.web.interceptor.SessionTimerInterceptor;
import org.baeldung.web.interceptor.UserInterceptor; import org.baeldung.web.interceptor.UserInterceptor;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
@ -15,7 +16,7 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration @Configuration
@ComponentScan("org.baeldung.web") @ComponentScan("org.baeldung.web")
@EnableWebMvc @EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter { public class WebConfig extends WebMvcConfigurerAdapter{
public WebConfig() { public WebConfig() {
super(); super();
@ -42,5 +43,7 @@ public class WebConfig extends WebMvcConfigurerAdapter {
public void addInterceptors(final InterceptorRegistry registry) { public void addInterceptors(final InterceptorRegistry registry) {
registry.addInterceptor(new LoggerInterceptor()); registry.addInterceptor(new LoggerInterceptor());
registry.addInterceptor(new UserInterceptor()); registry.addInterceptor(new UserInterceptor());
registry.addInterceptor(new SessionTimerInterceptor());
} }
} }

View File

@ -0,0 +1,57 @@
package org.baeldung.web.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class SessionTimerInterceptor extends HandlerInterceptorAdapter {
private static Logger log = LoggerFactory.getLogger(SessionTimerInterceptor.class);
private static final long MAX_INACTIVE_SESSION_TIME = 5 * 10000;
@Autowired
private HttpSession session;
/**
* Executed before actual handler is executed
**/
@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler)
throws Exception {
log.info("Pre handle method - check handling start time");
long startTime = System.currentTimeMillis();
request.setAttribute("executionTime", startTime);
if (UserInterceptor.isUserLogged()) {
session = request.getSession();
log.info("Who is logged in: " + SecurityContextHolder.getContext().getAuthentication().getName());
log.info("Time since last request in this session: "
+ (System.currentTimeMillis() - request.getSession().getLastAccessedTime()) + " ms");
if (System.currentTimeMillis() - session.getLastAccessedTime() > MAX_INACTIVE_SESSION_TIME) {
log.warn("Logging out, due to inactive session");
SecurityContextHolder.clearContext();
request.logout();
response.sendRedirect("/spring-security-rest-full/logout");
}
}
return true;
}
/**
* Executed before after handler is executed
**/
@Override
public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
final ModelAndView model) throws Exception {
log.info("Post handle method - check execution time of handling");
long startTime = (Long) request.getAttribute("executionTime");
log.info("Execution time for handling the request was: " + (System.currentTimeMillis() - startTime) + " ms");
}
}

View File

@ -0,0 +1,56 @@
package org.baeldung.web.interceptor;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import javax.servlet.http.HttpSession;
import org.baeldung.spring.PersistenceConfig;
import org.baeldung.spring.SecurityWithoutCsrfConfig;
import org.baeldung.spring.WebConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@Transactional
@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class })
@WithMockUser(username = "admin", roles = { "USER", "ADMIN" })
public class SessionTimerInterceptorTest {
@Autowired
WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
/**
* After execution of HTTP GET logs from interceptor will be displayed in
* the console
*/
@Test
public void testInterceptors() throws Exception {
HttpSession session = mockMvc.perform(get("/auth/admin")).andExpect(status().is2xxSuccessful()).andReturn()
.getRequest().getSession();
Thread.sleep(51000);
mockMvc.perform(get("/auth/admin").session((MockHttpSession) session)).andExpect(status().is2xxSuccessful());
}
}