I am developing a Spring application and I am authenticating user in HandlerInterceptorAdapter's prehandle() method and if user authenticated I am setting request attribute like this:
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
request.setAttribute("isAuthenticated",true);
request.setAttribute("user",user);
}
if user not authenticated I am setting like this
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
request.setAttribute("isAuthenticated",false);
request.setAttribute("user",null);
}
and then later in controller method I am retrieving user with HttpServletRequest like this:
@GetMapping(value = "/user", produces = "application/json")
public Object getUserByToken(HttpServletRequest request) {
if((Boolean) request.getAttribute("isAuthenticated")) {
return request.getAttribute("user");
}
return ResponseEntity.status(UNAUTHORIZED).body("unauthorized");
}
The problem is I need to receive HttpServletRequest in each controller method to check if user authenticated.
What I want is that a method that is called before controller method and inside the controller class, so that I can set user in one place and get from all other controller methods