Thursday, December 6, 2018

Session Handling in Spring Boot Application

There  are several ways to  handle session in  spring boot application.

One way  that we can  use  is  handling session  through Spring Security .


1.Handling Session  Through using  Redis



Spring Session has the simple goal of free up session management from the limitations of the HTTP session stored in the server.

The solution makes it easy to share session data between services in the cloud without being tied to a single container (i.e. Tomcat).
 Additionally, it supports multiple sessions in the same browser and sending sessions in a header.


2.Handling Session  Through Spring Security


When Is The Session Created?

We can control exactly when our session gets created and how Spring Security will interact with it:

    always           – a session will always be created if one doesn’t already exist
    ifRequired     – a session will be created only if required (default)
    never             – the framework will never create a session itself but it will use one if it already exists
    stateless        – no session will be created or used by Spring Security

<http create-session="ifRequired">...</http>

Java configuration:

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)

}

It’s very important to understand that this configuration only controls what Spring Security does –
not the entire application. Spring Security may not create the session if we instruct it not to, but our app may!
By default, Spring Security will create a session when it needs one – this is “ifRequired“.For a more stateless
application, the “never” option will ensure that Spring Security itself will not create any session; however, if
the application creates one, then Spring Security will make use of it.

Finally, the strictest session creation option – “stateless” – is a guarantee that the application will not create
any session at all.

This was introduced in Spring 3.1 and will effectively skip parts of the Spring Security filter chain – mainly the
session related parts such as

 HttpSessionSecurityContextRepository, SessionManagementFilter, RequestCacheFilter.

These more strict control mechanisms have the direct implication that cookies are not used and so each and every
request needs to be re-authenticated.

This stateless architecture plays well with REST APIs and their Statelessness constraint. They also work well with
authentication mechanisms such as Basic and Digest Authentication


References Used :-   spring-security-session
                                  spring-session

No comments:

Post a Comment

The AI Driven Software Developer, Optimize Innovate Transform

  The AI-Driven Software Developer: Optimize, Innovate, Transform": AI Transformation in Software Development : Understand how AI is re...