In the following example we are going to show how to implement authentication using HandlerInterceptor. If the clients want to access a page without logged in, the request is redirected to the login page.
Note that for production-grade authentication, authorization, or CSRF protection, you should use Spring Security — not interceptors. Interceptors are best kept for cross-cutting technical concerns such as request logging, performance monitoring, setting common model attributes, or measuring execution time. They are not a security layer.
Example
package com.logicbig.example;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
RequestMapping rm = ((HandlerMethod) handler).getMethodAnnotation(
RequestMapping.class);
boolean alreadyLoggedIn = request.getSession()
.getAttribute("user") != null;
boolean loginPageRequested = rm != null &&
rm.value().length > 0 &&
"login".equals(rm.value()[0]);
if (alreadyLoggedIn && loginPageRequested) {
response.sendRedirect(request.getContextPath() + "/app/main-page");
return false;
} else if (!alreadyLoggedIn && !loginPageRequested) {
response.sendRedirect(request.getContextPath() + "/login");
return false;
}
return true;
}
}
package com.logicbig.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
@Controller
public class AppController {
@Autowired
private UserService userService;
@RequestMapping(value = "login", method = RequestMethod.GET)
public String handleLoginGetRequest () {
return "user-login";
}
@RequestMapping(value = "login", method = RequestMethod.POST)
public String handleLoginPostRequest (User user, Model model,
HttpServletRequest request) {
User loggedUser = userService.loginUser(user);
if (loggedUser != null) {
request.getSession(true)
.setAttribute("user", loggedUser);
return "redirect:/app/main-page";
} else {
model.addAttribute("error", "Not a valid user");
return "user-login";
}
}
@RequestMapping(value = "app/**", method = RequestMethod.GET)
public String handleAppRequest (Model model, HttpServletRequest request) {
model.addAttribute("uri", request.getRequestURI());
model.addAttribute("user", request.getAttribute("user"));
return "app-page";
}
}
Running example
To try examples, run embedded Jetty (configured in pom.xml of example project below):
mvn jetty:run
Enter 'admin@example.com' for email address and 'password' for password:
Example ProjectDependencies and Technologies Used: - spring-webmvc 4.2.4.RELEASE (Spring Web MVC)
- spring-test 4.2.4.RELEASE (Spring TestContext Framework)
- javax.servlet-api 3.0.1 (Java Servlet API)
- junit 4.12 (JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck)
- JDK 1.8
- Maven 3.9.11
|