We are using spring boot with spring security to implement a querying interface. What I want to do is to only allow a fixed number of queries per user to run at a time. Queries may take a long time and users may send repeated requests faster than we can respond. I want the controller to only ever be calculating a subset request at a time and I'll have to implement some logic as to which requests to respond to.
To do this, I need to know the session token for the given user. Is there an easy way to get this in the controller's methods?
getSessionId(); This relies on Spring's RequestContextHolder , so it should be used with Spring MVC's DispatcherServlet or you should have a RequestContextListener declared. Also session will be created if not exists.
The HttpServletRequest.getUserPrincipal() will return the result of SecurityContextHolder.getContext().getAuthentication() . This means it is an Authentication which is typically an instance of UsernamePasswordAuthenticationToken when using username and password based authentication.
If you want to get sessionId in controllers you can use
RequestContextHolder.currentRequestAttributes().getSessionId();
I find it easier to add the parameter 'HttpSession session' in your request mapping:
@GetMapping(value = "/hello")
public String home(HttpSession session) {
String sessionId = session.getId();
System.out.println("[session-id]: " + sessionId);
...
return "anyPage";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With