Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get session token for Spring boot/security in controller

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?

like image 399
Carlos Bribiescas Avatar asked Dec 03 '15 17:12

Carlos Bribiescas


People also ask

How does Spring Boot generate session ID?

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.

What is SecurityContextHolder getContext () getAuthentication ()?

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.


2 Answers

If you want to get sessionId in controllers you can use RequestContextHolder.currentRequestAttributes().getSessionId();

like image 101
Sainik Kumar Singhal Avatar answered Oct 23 '22 06:10

Sainik Kumar Singhal


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";  
}
like image 35
Borgy Manotoy Avatar answered Oct 23 '22 04:10

Borgy Manotoy