spring-session

1. spring-session for browswer (token in HttpSession)

Enable Redis HttpSession,

@EnableRedisHttpSession
public class HttpSessionConfig {
}

2. spring-session for REST (token in header)

Enable Redis HttpSession, and use HTTP headers to convey session info.

@EnableRedisHttpSession
public class HttpSessionConfig {
@Bean
public HttpSessionStrategy httpSessionStrategy() {
//use HTTP headers to convey the current session information instead of cookies
return new HeaderHttpSessionStrategy();
}
}

Enable Web Security

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("pwd").roles("USER");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.requestCache()
.requestCache(new NullRequestCache())
.and()
.httpBasic();
}
}

build.gradle

compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-security")
compile("org.springframework.session:spring-session-data-redis")

operation w/o token will result in 401(UnAuth):

curl -v http://localhost:8080/

login with:

curl -v http://localhost:8080/ -u admin:pwd

resp will has header:

x-auth-token: 0dc1f6e1-c7f1-41ac-8ce2-32b6b3e57aa3

all later operations need to set “x-auth-token” in header

curl -v http://localhost:8080/ -H "x-auth-token: ${token}"

logout will invalidate the session

curl -v http://localhost:8080/logout -H "x-auth-token: ${token}"

3. class and packages

org.springframework.session

  • (C)HeaderHttpSessionStrategy
  • @EnableRedisHttpSession

org.springframework.security

  • @EnableWebSecurity
  • (C)WebSecurityConfigurerAdapter

org.springframework.web

  • @RestController
  • @RequestMapping

javax.servlet.http (inside spring-boot-starter-web)

  • (C)HttpSession

org.springframework.data.redis (needed by reflection, inside spring-boot-starter-redis or spring-session-data-redis)

  • (I) RedisSerializer

4. packages

“spring-boot-starter-redis” includes

\--- org.springframework.boot:spring-boot-starter-redis: -> 1.4.2.RELEASE
     +--- org.springframework.boot:spring-boot-starter:1.4.2.RELEASE
     +--- org.springframework.data:spring-data-redis:1.7.5.RELEASE
     \--- redis.clients:jedis:2.8.2

“spring-session” is atom package

\--- org.springframework.session:spring-session: -> 1.2.2.RELEASE

“spring-session-data-redis” includes

\--- org.springframework.session:spring-session-data-redis: -> 1.2.2.RELEASE
     +--- org.apache.commons:commons-pool2:2.4.2
     +--- org.springframework.data:spring-data-redis:1.7.1.RELEASE -> 1.7.5.RELEASE
     +--- org.springframework.session:spring-session:1.2.2.RELEASE
     \--- redis.clients:jedis:2.8.1 -> 2.8.2