Issue
I Have cookies working in httponly on my frontend app.
I want to be able to refresh the page and still be logged in. I can do this, the cookie stays present. But the data from the login request where it provides the userProfile in the body wont be present.
I have the following class which filters requests:
public class AuthTokenFilter extends OncePerRequestFilter {
@Autowired
private JwtUtils jwtUtils;
@Autowired
private MyUserDetailsService userDetailsService;
private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
String jwt = parseJwt(request);
if (jwt != null && jwtUtils.validateJwtToken(jwt)) {
String email = jwtUtils.getEmailFromJwtToken(jwt);
UserDetails userDetails = userDetailsService.loadUserByUsername(email);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
catch (Exception e) { logger.error("Cannot set user authentication: {}", e);
System.out.println(e);
}
filterChain.doFilter(request, response);
}
private String parseJwt(HttpServletRequest request) { return jwtUtils.getJwtFromCookies(request); }
}
But idealy i want to be handling the whoAmI
from the auth controller.
@GetMapping("/whoAmI")
public ResponseEntity<?> whoAmI() {
...
...
...
Cookie[] cookies = request.getCookies();
if (cookies != null) {
var temp = Arrays.stream(cookies)
.map(c -> c.getName() + "=" + c.getValue()).collect(Collectors.joining(", "));
}
...
...
...
return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, jwtCookie.toString())
.body(userService.findUserProfileUserByEmail(userDetails.getEmail()));
}
It makes more sense for me to deal with this in controller instead of the filter. But how can I pass the request into the controller from the filter?
Solution
You can define a controller method with an argument of type ServletRequest
and Spring will do the magic for you.
@GetMapping("/whoAmI")
public ResponseEntity<?> whoAmI(HttpServletRequest httpRequest) {
}
Take a look at reference docs here for possible handler method arguments.
Also spring-mvc is a thread-per-request model, so (if you don't use async spring-mvc features) you can get your servlet request anywhere in your code by using:
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();
Answered By - AndrewThomas
Answer Checked By - Terry (JavaFixing Volunteer)