renamed spring-security-mvc-session to simply spring-security-mvc

This commit is contained in:
Gerardo Roza
2019-07-25 12:08:47 -03:00
parent b981da41c8
commit 30f4da3dd5
26 changed files with 5 additions and 5 deletions

View File

@@ -0,0 +1,12 @@
package com.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringSessionApplication {
public static void main(String[] args) {
SpringApplication.run(SpringSessionApplication.class, args);
}
}

View File

@@ -0,0 +1,25 @@
package com.baeldung.monitoring;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Slf4jReporter;
public final class MetricRegistrySingleton {
public static final MetricRegistry metrics = new MetricRegistry();
static {
Logger logger = LoggerFactory.getLogger("org.baeldung.monitoring");
final Slf4jReporter reporter = Slf4jReporter.forRegistry(metrics).outputTo(logger).convertRatesTo(TimeUnit.SECONDS).convertDurationsTo(TimeUnit.MILLISECONDS).build();
reporter.start(5, TimeUnit.MINUTES);
}
private MetricRegistrySingleton() {
throw new AssertionError();
}
}

View File

@@ -0,0 +1,94 @@
package com.baeldung.security;
import java.io.IOException;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
protected final Log logger = LogFactory.getLog(this.getClass());
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
public MySimpleUrlAuthenticationSuccessHandler() {
super();
}
// API
@Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException {
handle(request, response, authentication);
clearAuthenticationAttributes(request);
}
// IMPL
protected void handle(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException {
final String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
logger.debug("Response has already been committed. Unable to redirect to " + targetUrl);
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String determineTargetUrl(final Authentication authentication) {
boolean isUser = false;
boolean isAdmin = false;
final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (final GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
isUser = true;
break;
} else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
isAdmin = true;
break;
}
}
if (isUser) {
return "/homepage.html";
} else if (isAdmin) {
return "/console.html";
} else {
throw new IllegalStateException();
}
}
/**
* Removes temporary authentication-related data which may have been stored in the session
* during the authentication process.
*/
protected final void clearAuthenticationAttributes(final HttpServletRequest request) {
final HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
public void setRedirectStrategy(final RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}

View File

@@ -0,0 +1,45 @@
package com.baeldung.security;
import java.io.IOException;
import java.util.Arrays;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SessionFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("init filter");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
Cookie[] allCookies = req.getCookies();
if (allCookies != null) {
Cookie session = Arrays.stream(allCookies).filter(x -> x.getName().equals("JSESSIONID")).findFirst().orElse(null);
if (session != null) {
session.setHttpOnly(true);
session.setSecure(true);
res.addCookie(session);
}
}
chain.doFilter(req, res);
}
@Override
public void destroy() {
System.out.println("destroy filter");
}
}

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

@@ -0,0 +1,78 @@
package com.baeldung.spring;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
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" })
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
public SecSecurityConfig() {
super();
}
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth.inMemoryAuthentication()
.withUser("user1").password(passwordEncoder().encode("user1Pass")).roles("USER")
.and()
.withUser("admin1").password(passwordEncoder().encode("admin1Pass")).roles("ADMIN");
// @formatter:on
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/anonymous*").anonymous()
.antMatchers("/login*","/invalidSession*", "/sessionExpired*").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/login")
.successHandler(successHandler())
.failureUrl("/login.html?error=true")
.and()
.logout().deleteCookies("JSESSIONID")
.and()
.rememberMe().key("uniqueAndSecret").tokenValiditySeconds(86400)
.and()
.sessionManagement()
.sessionFixation().migrateSession()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.invalidSessionUrl("/invalidSession.html")
.maximumSessions(2)
.expiredUrl("/sessionExpired.html");
// @formatter:on
}
private AuthenticationSuccessHandler successHandler() {
return new MySimpleUrlAuthenticationSuccessHandler();
}
@Bean
public HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@@ -0,0 +1,42 @@
package com.baeldung.web;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import com.baeldung.monitoring.MetricRegistrySingleton;
import com.codahale.metrics.Counter;
public class SessionListenerWithMetrics implements HttpSessionListener {
private final AtomicInteger activeSessions;
private final Counter counterOfActiveSessions;
public SessionListenerWithMetrics() {
super();
activeSessions = new AtomicInteger();
counterOfActiveSessions = MetricRegistrySingleton.metrics.counter("web.sessions.active.count");
}
// API
public final int getTotalActiveSession() {
return activeSessions.get();
}
@Override
public final void sessionCreated(final HttpSessionEvent event) {
activeSessions.incrementAndGet();
counterOfActiveSessions.inc();
}
@Override
public final void sessionDestroyed(final HttpSessionEvent event) {
activeSessions.decrementAndGet();
counterOfActiveSessions.dec();
}
}

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,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"
>
<http create-session="always" use-expressions="true">
<intercept-url pattern="/anonymous*" access="isAnonymous()"/>
<intercept-url pattern="/login*" access="permitAll"/>
<intercept-url pattern="/**" access="isAuthenticated()"/>
<csrf disabled="true"/>
<form-login login-page='/login.html' authentication-success-handler-ref="myAuthenticationSuccessHandler" authentication-failure-url="/login.html?error=true"/>
<logout delete-cookies="JSESSIONID"/>
<remember-me key="uniqueAndSecret" token-validity-seconds="86400"/>
<session-management invalid-session-url="/invalidSession.html">
<concurrency-control max-sessions="2" expired-url="/sessionExpired.html"/>
</session-management>
</http>
<beans:bean id="myAuthenticationSuccessHandler" class="org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler"/>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user1" password="user1Pass" authorities="ROLE_USER"/>
<user name="admin1" password="admin1Pass" authorities="ROLE_ADMIN"/>
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd" >
</beans>

View File

@@ -0,0 +1,10 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head></head>
<body>
<h1>Anonymous page</h1>
<a href="<c:url value="/login.html" />">To Login</a>
</body>
</html>

View File

@@ -0,0 +1,22 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<html>
<head></head>
<body>
<h1>This is the landing page for the admin</h1>
<security:authorize access="hasRole('ROLE_USER')">
This text is only visible to a user
<br/>
</security:authorize>
<security:authorize access="hasRole('ROLE_ADMIN')">
This text is only visible to an admin
<br/>
</security:authorize>
<a href="<c:url value="/logout" />">Logout</a>
</body>
</html>

View File

@@ -0,0 +1,22 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags"%>
<html>
<head></head>
<body>
<h1>This is the homepage for the user</h1>
<security:authorize access="hasRole('ROLE_USER')">
This text is only visible to a user
<br />
</security:authorize>
<security:authorize access="hasRole('ROLE_ADMIN')">
This text is only visible to an admin
<br />
</security:authorize>
<a href="<c:url value="/logout" />">Logout</a>
</body>
</html>

View File

@@ -0,0 +1,10 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head></head>
<body>
<h1>Invalid Session Page</h1>
<a href="<c:url value="/login.html" />">To Login</a>
</body>
</html>

View File

@@ -0,0 +1,30 @@
<html>
<head></head>
<body>
<h1>Login</h1>
<form name='f' action="login" method='POST'>
<table>
<tr>
<td>User:</td>
<td><input type='text' name='username' value=''></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password' /></td>
</tr>
<tr>
<td>Remember Me:</td>
<td><input type="checkbox" name="remember-me" /></td>
</tr>
<tr>
<td><input name="submit" type="submit" value="submit" /></td>
</tr>
</table>
</form>
</body>
</html>

View File

@@ -0,0 +1,10 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head></head>
<body>
<h1>Session Expired Page</h1>
<a href="<c:url value="/login.html" />">To Login</a>
</body>
</html>

View File

@@ -0,0 +1,73 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Spring MVC Session Application</display-name>
<session-config>
<session-timeout>1</session-timeout>
<!-- <cookie-config>
<http-only>true</http-only>
<secure>true</secure>
</cookie-config> -->
</session-config>
<listener>
<listener-class>org.baeldung.web.SessionListenerWithMetrics</listener-class>
</listener>
<!-- <listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener> -->
<!-- Spring root -->
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>org.baeldung.spring</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring child -->
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- <filter>
<filter-name>SessionFilter</filter-name>
<filter-class>org.baeldung.security.SessionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SessionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> -->
<!-- <welcome-file-list> -->
<!-- <welcome-file>index.html</welcome-file> -->
<!-- </welcome-file-list> -->
</web-app>

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);
}
}

View File

@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear