Merge pull request #7415 from rozagerardo/rozagerardo/BAEL-10220_Update-Spring-Session-article

[BAEL-10220] Update Spring Session article
This commit is contained in:
Loredana Crusoveanu 2019-07-27 14:30:09 +03:00 committed by GitHub
commit 71af0f793c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
30 changed files with 263 additions and 223 deletions

View File

@ -743,7 +743,7 @@
<module>spring-security-mvc-ldap</module>
<module>spring-security-mvc-login</module>
<module>spring-security-mvc-persisted-remember-me</module>
<module>spring-security-mvc-session</module>
<module>spring-security-mvc</module>
<module>spring-security-mvc-socket</module>
<module>spring-security-openid</module>
<!--<module>spring-security-react</module> --> <!-- fails on Travis, fails intermittently on the new Jenkins (01.12.2018) BAEL-10834 -->
@ -919,7 +919,7 @@
<module>spring-security-mvc-digest-auth</module>
<module>spring-security-mvc-ldap</module>
<module>spring-security-mvc-persisted-remember-me</module>
<module>spring-security-mvc-session</module>
<module>spring-security-mvc</module>
<module>spring-security-mvc-socket</module>
<module>spring-security-rest</module>
<module>spring-security-sso</module>
@ -1412,7 +1412,7 @@
<module>spring-security-mvc-ldap</module>
<module>spring-security-mvc-login</module>
<module>spring-security-mvc-persisted-remember-me</module>
<module>spring-security-mvc-session</module>
<module>spring-security-mvc</module>
<module>spring-security-mvc-socket</module>
<module>spring-security-openid</module>
<!--<module>spring-security-react</module> --> <!-- fails on Travis, fails intermittently on the new Jenkins (01.12.2018) BAEL-10834 -->

View File

@ -1,125 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-security-mvc-session</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-security-mvc-session</name>
<packaging>war</packaging>
<parent>
<artifactId>parent-boot-2</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencies>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<!-- web -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<scope>runtime</scope>
</dependency>
<!-- ops -->
<dependency>
<groupId>com.codahale.metrics</groupId>
<artifactId>metrics-core</artifactId>
<version>${codahale.metrics.version}</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-security-mvc-session</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<wait>true</wait>
<container>
<containerId>jetty8x</containerId>
<type>embedded</type>
<systemProperties>
<!-- <provPersistenceTarget>cargo</provPersistenceTarget> -->
</systemProperties>
</container>
<configuration>
<properties>
<cargo.servlet.port>8082</cargo.servlet.port>
</properties>
</configuration>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<!-- various -->
<codahale.metrics.version>3.0.2</codahale.metrics.version>
<!-- Maven plugins -->
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
</properties>
</project>

View File

@ -1,44 +0,0 @@
package org.baeldung.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@EnableWebMvc
@Configuration
public class MvcConfig implements WebMvcConfigurer {
public MvcConfig() {
super();
}
// API
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController("/anonymous.html");
registry.addViewController("/login.html");
registry.addViewController("/homepage.html");
registry.addViewController("/sessionExpired.html");
registry.addViewController("/invalidExpired.html");
registry.addViewController("/console.html");
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
}

View File

@ -1,19 +0,0 @@
package org.baeldung;
import org.baeldung.spring.MvcConfig;
import org.baeldung.spring.SecSecurityConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class })
@WebAppConfiguration
public class SpringContextIntegrationTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -1,19 +0,0 @@
package org.baeldung;
import org.baeldung.spring.MvcConfig;
import org.baeldung.spring.SecSecurityConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { MvcConfig.class, SecSecurityConfig.class })
@WebAppConfiguration
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -0,0 +1,84 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-security-mvc</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-security-mvc</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencies>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<scope>runtime</scope>
</dependency>
<!-- ops -->
<dependency>
<groupId>io.dropwizard.metrics</groupId>
<artifactId>metrics-core</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.baeldung.SpringSessionApplication</mainClass>
<layout>JAR</layout>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,4 +1,4 @@
package org.baeldung;
package com.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

View File

@ -1,4 +1,4 @@
package org.baeldung.monitoring;
package com.baeldung.monitoring;
import java.util.concurrent.TimeUnit;

View File

@ -1,4 +1,4 @@
package org.baeldung.security;
package com.baeldung.security;
import java.io.IOException;
import java.util.Collection;

View File

@ -1,4 +1,4 @@
package org.baeldung.security;
package com.baeldung.security;
import java.io.IOException;
import java.util.Arrays;

View File

@ -0,0 +1,33 @@
package com.baeldung.spring;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController("/anonymous.html");
registry.addViewController("/login.html");
registry.addViewController("/homepage.html");
registry.addViewController("/sessionExpired.html");
registry.addViewController("/invalidSession.html");
registry.addViewController("/console.html");
}
/*
* Spring Boot supports configuring a ViewResolver with properties
*/
// @Bean
// public ViewResolver viewResolver() {
// final InternalResourceViewResolver bean = new InternalResourceViewResolver();
//
// bean.setViewClass(JstlView.class);
// bean.setPrefix("/WEB-INF/view/");
// bean.setSuffix(".jsp");
// }
}

View File

@ -1,11 +1,9 @@
package org.baeldung.spring;
package com.baeldung.spring;
import org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@ -13,9 +11,10 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.session.HttpSessionEventPublisher;
import com.baeldung.security.MySimpleUrlAuthenticationSuccessHandler;
@Configuration
// @ImportResource({ "classpath:webSecurityConfig.xml" })
@EnableWebSecurity
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
public SecSecurityConfig() {
@ -39,7 +38,7 @@ public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
.csrf().disable()
.authorizeRequests()
.antMatchers("/anonymous*").anonymous()
.antMatchers("/login*").permitAll()
.antMatchers("/login*","/invalidSession*", "/sessionExpired*").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()

View File

@ -1,12 +1,11 @@
package org.baeldung.web;
package com.baeldung.web;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.baeldung.monitoring.MetricRegistrySingleton;
import com.baeldung.monitoring.MetricRegistrySingleton;
import com.codahale.metrics.Counter;
public class SessionListenerWithMetrics implements HttpSessionListener {

View File

@ -0,0 +1,17 @@
package com.baeldung.web;
import javax.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SessionRestController {
@GetMapping("/session-max-interval")
@ResponseBody
public String retrieveMaxSessionIncativeInterval(HttpSession session) {
return "Max Inactive Interval before Session expires: " + session.getMaxInactiveInterval();
}
}

View File

@ -0,0 +1,8 @@
server.servlet.session.timeout=65s
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp
## Secure Session Cookie configurations
#server.servlet.session.cookie.http-only=true
#server.servlet.session.cookie.secure=true

View File

@ -0,0 +1,15 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringContextIntegrationTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -0,0 +1,92 @@
package com.baeldung.session;
import static io.restassured.RestAssured.given;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Optional;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import io.restassured.filter.session.SessionFilter;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
/**
* This Live Test requires the service to be up and running.
*/
public class SessionConfigurationIntegrationTest {
private static final String USER = "user1";
private static final String PASSWORD = "user1Pass";
private static final String SESSION_SVC_URL = "http://localhost:8080/session-max-interval";
@Test
public void givenValidUser_whenRequestResourceAfterSessionExpiration_thenRedirectedToInvalidSessionUri() throws Exception {
SessionFilter sessionFilter = new SessionFilter();
simpleSvcRequestLoggingIn(sessionFilter);
Response resp2 = simpleResponseRequestUsingSessionNotFollowingRedirects(sessionFilter);
assertThat(resp2.getStatusCode()).isEqualTo(HttpStatus.OK.value());
assertThat(resp2.getBody()
.asString()).isEqualTo("Max Inactive Interval before Session expires: 60");
// session will be expired in 60 seconds...
Thread.sleep(62000);
Response resp3 = simpleResponseRequestUsingSessionNotFollowingRedirects(sessionFilter);
assertThat(resp3.getStatusCode()).isEqualTo(HttpStatus.FOUND.value());
assertThat(resp3.getHeader("Location")).isEqualTo("http://localhost:8080/invalidSession.html");
}
@Test
public void givenValidUser_whenLoginMoreThanMaxValidSession_thenRedirectedToExpiredSessionUri() throws Exception {
SessionFilter sessionFilter = new SessionFilter();
simpleSvcRequestLoggingIn(sessionFilter);
simpleSvcRequestLoggingIn();
// this login will expire the first session
simpleSvcRequestLoggingIn();
// now try to access a resource using expired session
Response resp4 = given().filter(sessionFilter)
.and()
.redirects()
.follow(false)
.when()
.get(SESSION_SVC_URL);
assertThat(resp4.getStatusCode()).isEqualTo(HttpStatus.FOUND.value());
assertThat(resp4.getHeader("Location")).isEqualTo("http://localhost:8080/sessionExpired.html");
}
private static void simpleSvcRequestLoggingIn() {
simpleSvcRequestLoggingIn(null);
}
private static void simpleSvcRequestLoggingIn(SessionFilter sessionFilter) {
Response response = simpleResponseSvcRequestLoggingIn(Optional.ofNullable(sessionFilter));
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getBody()
.asString()).isEqualTo("Max Inactive Interval before Session expires: 60");
}
private static Response simpleResponseSvcRequestLoggingIn(Optional<SessionFilter> sessionFilter) {
RequestSpecification spec = given().auth()
.form(USER, PASSWORD);
sessionFilter.ifPresent(filter -> spec.and()
.filter(filter));
return spec.when()
.get(SESSION_SVC_URL);
}
private static Response simpleResponseRequestUsingSessionNotFollowingRedirects(SessionFilter sessionFilter) {
return given().filter(sessionFilter)
.and()
.redirects()
.follow(false)
.when()
.get(SESSION_SVC_URL);
}
}