Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I best handle sessions in my RestController within Spring?

I'm looking for suggestions on how to handle sessions more elegantly than my implementation below.

Basically I've written a BaseController that has a handleSession() routine that does the initial creation and subsequent reads from session data. This session data is required to store various security information that I don't want to be reading on every hit for obvious performance reasons. I also don't want to store this on the client, or I would just create a new request to pull the information back to Angular.

CustomerController implements this handleSession() call within each request. This means I have to put it everywhere.

Is there a more graceful way to handle this?

BaseController.java

public abstract class BaseController {

    public Logger log = LoggerFactory.getLogger(getClass());

    public void handleSession(HttpSession session) {
        if (session.isNew()) {
            log.info("New session: " + session.getId());
            // TODO: write all session data here?
            session.setAttribute("Parm", "Value");
        } else {
            // TODO: read all session data here?
            log.info("Reused session: " + session.getId() + " Parm is set to: "
                    + session.getAttribute("Parm"));

        }
    }
}

CustomerController.java

@RestController
@RequestMapping("/data/customer")
public class CustomerController extends BaseController {
    @Autowired
    private CustomerRepository customerRepository;

    @RequestMapping("")
    List<Customer> customers(HttpSession session) {
        handleSession(session);
        return customerRepository.getCustomers();
    }

    @RequestMapping("/{company}/{customer}/{division}")
    Customer customer(@PathVariable String company,
            @PathVariable String customer, @PathVariable String division,
            HttpSession session) {
        handleSession(session);
        return customerRepository.getCustomer(company, customer, division);
    }
}
like image 207
ehiggins Avatar asked Oct 24 '25 00:10

ehiggins


1 Answers

Maybe you can get HttpSession information with @Autowired in you Controller. If you pass session information as parameter, there will be chance that you will get security vulnerability finding for your application.

For this, use the approach below:

@RestController
@RequestMapping("/data/customer")
public class CustomerController extends BaseController {
    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private HttpSession httpSession;

You can remove HttpSession parameter from all your request mapping methods.

like image 108
Channa Mallaiah Avatar answered Oct 25 '25 15:10

Channa Mallaiah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!