Skip to content

Commit 113afd4

Browse files
maibinpivovarit
authored andcommitted
Advanced Handler Interceptors (eugenp#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
1 parent 9c1b87d commit 113afd4

4 files changed

Lines changed: 133 additions & 1 deletion

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package org.baeldung.spring;
2+
3+
import javax.servlet.ServletContext;
4+
import javax.servlet.ServletException;
5+
6+
import org.springframework.web.WebApplicationInitializer;
7+
import org.springframework.web.context.request.RequestContextListener;
8+
9+
public class ListenerConfig implements WebApplicationInitializer {
10+
11+
@Override
12+
public void onStartup(ServletContext sc) throws ServletException {
13+
// Manages the lifecycle of the root application context
14+
sc.addListener(new RequestContextListener());
15+
}
16+
}

‎spring-security-rest-full/src/main/java/org/baeldung/spring/WebConfig.java‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package org.baeldung.spring;
22

33
import org.baeldung.web.interceptor.LoggerInterceptor;
4+
import org.baeldung.web.interceptor.SessionTimerInterceptor;
45
import org.baeldung.web.interceptor.UserInterceptor;
56
import org.springframework.context.annotation.Bean;
67
import org.springframework.context.annotation.ComponentScan;
@@ -15,7 +16,7 @@
1516
@Configuration
1617
@ComponentScan("org.baeldung.web")
1718
@EnableWebMvc
18-
public class WebConfig extends WebMvcConfigurerAdapter {
19+
public class WebConfig extends WebMvcConfigurerAdapter{
1920

2021
public WebConfig() {
2122
super();
@@ -42,5 +43,7 @@ public void addViewControllers(final ViewControllerRegistry registry) {
4243
public void addInterceptors(final InterceptorRegistry registry) {
4344
registry.addInterceptor(new LoggerInterceptor());
4445
registry.addInterceptor(new UserInterceptor());
46+
registry.addInterceptor(new SessionTimerInterceptor());
4547
}
48+
4649
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package org.baeldung.web.interceptor;
2+
3+
import javax.servlet.http.HttpServletRequest;
4+
import javax.servlet.http.HttpServletResponse;
5+
import javax.servlet.http.HttpSession;
6+
7+
import org.slf4j.Logger;
8+
import org.slf4j.LoggerFactory;
9+
import org.springframework.beans.factory.annotation.Autowired;
10+
import org.springframework.security.core.context.SecurityContextHolder;
11+
import org.springframework.web.servlet.ModelAndView;
12+
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
13+
14+
public class SessionTimerInterceptor extends HandlerInterceptorAdapter {
15+
16+
private static Logger log = LoggerFactory.getLogger(SessionTimerInterceptor.class);
17+
18+
private static final long MAX_INACTIVE_SESSION_TIME = 5 * 10000;
19+
20+
@Autowired
21+
private HttpSession session;
22+
23+
/**
24+
* Executed before actual handler is executed
25+
**/
26+
@Override
27+
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler)
28+
throws Exception {
29+
log.info("Pre handle method - check handling start time");
30+
long startTime = System.currentTimeMillis();
31+
request.setAttribute("executionTime", startTime);
32+
if (UserInterceptor.isUserLogged()) {
33+
session = request.getSession();
34+
log.info("Who is logged in: " + SecurityContextHolder.getContext().getAuthentication().getName());
35+
log.info("Time since last request in this session: "
36+
+ (System.currentTimeMillis() - request.getSession().getLastAccessedTime()) + " ms");
37+
if (System.currentTimeMillis() - session.getLastAccessedTime() > MAX_INACTIVE_SESSION_TIME) {
38+
log.warn("Logging out, due to inactive session");
39+
SecurityContextHolder.clearContext();
40+
request.logout();
41+
response.sendRedirect("/spring-security-rest-full/logout");
42+
}
43+
}
44+
return true;
45+
}
46+
47+
/**
48+
* Executed before after handler is executed
49+
**/
50+
@Override
51+
public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
52+
final ModelAndView model) throws Exception {
53+
log.info("Post handle method - check execution time of handling");
54+
long startTime = (Long) request.getAttribute("executionTime");
55+
log.info("Execution time for handling the request was: " + (System.currentTimeMillis() - startTime) + " ms");
56+
}
57+
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package org.baeldung.web.interceptor;
2+
3+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
4+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
5+
6+
import javax.servlet.http.HttpSession;
7+
8+
import org.baeldung.spring.PersistenceConfig;
9+
import org.baeldung.spring.SecurityWithoutCsrfConfig;
10+
import org.baeldung.spring.WebConfig;
11+
import org.junit.Before;
12+
import org.junit.Test;
13+
import org.junit.runner.RunWith;
14+
import org.mockito.MockitoAnnotations;
15+
import org.springframework.beans.factory.annotation.Autowired;
16+
import org.springframework.mock.web.MockHttpSession;
17+
import org.springframework.security.test.context.support.WithMockUser;
18+
import org.springframework.test.context.ContextConfiguration;
19+
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
20+
import org.springframework.test.context.web.WebAppConfiguration;
21+
import org.springframework.test.web.servlet.MockMvc;
22+
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
23+
import org.springframework.transaction.annotation.Transactional;
24+
import org.springframework.web.context.WebApplicationContext;
25+
26+
@RunWith(SpringJUnit4ClassRunner.class)
27+
@WebAppConfiguration
28+
@Transactional
29+
@ContextConfiguration(classes = { SecurityWithoutCsrfConfig.class, PersistenceConfig.class, WebConfig.class })
30+
@WithMockUser(username = "admin", roles = { "USER", "ADMIN" })
31+
public class SessionTimerInterceptorTest {
32+
33+
@Autowired
34+
WebApplicationContext wac;
35+
36+
private MockMvc mockMvc;
37+
38+
@Before
39+
public void setup() {
40+
MockitoAnnotations.initMocks(this);
41+
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
42+
}
43+
44+
/**
45+
* After execution of HTTP GET logs from interceptor will be displayed in
46+
* the console
47+
*/
48+
@Test
49+
public void testInterceptors() throws Exception {
50+
HttpSession session = mockMvc.perform(get("/auth/admin")).andExpect(status().is2xxSuccessful()).andReturn()
51+
.getRequest().getSession();
52+
Thread.sleep(51000);
53+
mockMvc.perform(get("/auth/admin").session((MockHttpSession) session)).andExpect(status().is2xxSuccessful());
54+
}
55+
56+
}

0 commit comments

Comments
 (0)