JAVA-67: renamed spring-security-mvc to spring-security-web-mvc
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.clearsitedata;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
|
||||
@Controller
|
||||
public class LogoutClearSiteDataController {
|
||||
|
||||
@GetMapping(value = "/baeldung/logout")
|
||||
public ResponseEntity<String> logout(@PathVariable String name) {
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.clearsitedata;
|
||||
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
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.web.authentication.logout.HeaderWriterLogoutHandler;
|
||||
import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter;
|
||||
|
||||
import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.CACHE;
|
||||
import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.COOKIES;
|
||||
import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.STORAGE;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
||||
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
|
||||
http.csrf()
|
||||
.disable()
|
||||
.formLogin()
|
||||
.loginPage("/login.html")
|
||||
.loginProcessingUrl("/perform_login")
|
||||
.defaultSuccessUrl("/homepage.html", true)
|
||||
.and()
|
||||
.logout().logoutUrl("/baeldung/logout")
|
||||
.addLogoutHandler(new HeaderWriterLogoutHandler(
|
||||
new ClearSiteDataHeaderWriter(CACHE, COOKIES, STORAGE)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.clearsitedata;
|
||||
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import org.springframework.web.servlet.mvc.WebContentInterceptor;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@EnableWebMvc
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = {"com.baeldung.clearsitedata"})
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
}
|
||||
@@ -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("com.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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.session;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.session.bean;
|
||||
|
||||
public class Constants {
|
||||
public static final String FOO = "foo";
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.session.bean;
|
||||
|
||||
import static org.springframework.context.annotation.ScopedProxyMode.TARGET_CLASS;
|
||||
import static org.springframework.web.context.WebApplicationContext.SCOPE_SESSION;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@Scope(value = SCOPE_SESSION, proxyMode = TARGET_CLASS)
|
||||
public class Foo {
|
||||
private final String created;
|
||||
|
||||
public Foo() {
|
||||
this.created = LocalDateTime.now()
|
||||
.format(DateTimeFormatter.ISO_DATE_TIME);
|
||||
}
|
||||
|
||||
public Foo(Foo theFoo) {
|
||||
this.created = theFoo.created;
|
||||
}
|
||||
|
||||
public String getCreated() {
|
||||
return created;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.session.filter;
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.baeldung.session.security.config;
|
||||
|
||||
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*", "/foo/**").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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.session.web;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import com.baeldung.session.bean.Constants;
|
||||
import com.baeldung.session.bean.Foo;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(path = "/foo")
|
||||
public class FooController {
|
||||
|
||||
@Autowired
|
||||
private Foo theFoo;
|
||||
|
||||
@GetMapping(path = "set")
|
||||
public void fooSet(HttpSession session) {
|
||||
session.setAttribute(Constants.FOO, new Foo());
|
||||
}
|
||||
|
||||
@GetMapping(path = "autowired")
|
||||
public Foo getAutowired() {
|
||||
return new Foo(theFoo);
|
||||
}
|
||||
|
||||
@GetMapping(path = "inject")
|
||||
public Foo fooInject(HttpSession session) {
|
||||
return (Foo) session.getAttribute(Constants.FOO);
|
||||
}
|
||||
|
||||
@GetMapping(path = "raw")
|
||||
public Foo fromRaw() {
|
||||
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
|
||||
HttpSession session = attr.getRequest()
|
||||
.getSession(true);
|
||||
return (Foo) session.getAttribute(Constants.FOO);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.session.web;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class SessionRestController {
|
||||
|
||||
@GetMapping("/session-max-interval")
|
||||
public String retrieveMaxSessionInactiveInterval(HttpSession session) {
|
||||
return "Max Inactive Interval before Session expires: " + session.getMaxInactiveInterval();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.session.web.config;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
|
||||
import org.springframework.web.WebApplicationInitializer;
|
||||
|
||||
public class MainWebAppInitializer implements WebApplicationInitializer {
|
||||
|
||||
@Override
|
||||
public void onStartup(ServletContext sc) throws ServletException {
|
||||
sc.getSessionCookieConfig().setHttpOnly(true);
|
||||
sc.getSessionCookieConfig().setSecure(true);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.session.web.config;
|
||||
|
||||
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");
|
||||
// }
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
spring.jackson.serialization.fail-on-empty-beans=false
|
||||
|
||||
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
|
||||
@@ -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>
|
||||
@@ -0,0 +1,38 @@
|
||||
<?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" disable-url-rewriting="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="com.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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -0,0 +1,74 @@
|
||||
<?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>
|
||||
<tracking-mode>COOKIE</tracking-mode>
|
||||
<!-- <cookie-config>
|
||||
<http-only>true</http-only>
|
||||
<secure>true</secure>
|
||||
</cookie-config> -->
|
||||
</session-config>
|
||||
<listener>
|
||||
<listener-class>com.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>com.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>com.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>
|
||||
@@ -0,0 +1,17 @@
|
||||
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;
|
||||
|
||||
import com.baeldung.session.SpringSessionApplication;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = SpringSessionApplication.class)
|
||||
public class SpringContextTest {
|
||||
|
||||
@Test
|
||||
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.clearsitedata;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
|
||||
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
import javax.servlet.Filter;
|
||||
|
||||
@ExtendWith(SpringExtension.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = {SpringSecurityConfig.class, WebConfig.class})
|
||||
public class LogoutClearSiteDataControllerUnitTest {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext wac;
|
||||
|
||||
@Autowired
|
||||
private Filter springSecurityFilterChain;
|
||||
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@BeforeEach
|
||||
void setup() throws Exception {
|
||||
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).addFilters(springSecurityFilterChain).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenResponseBody_thenReturnCacheHeader() throws Exception {
|
||||
this.mockMvc
|
||||
.perform(MockMvcRequestBuilders
|
||||
.get("/baeldung/logout").secure(true))
|
||||
.andDo(MockMvcResultHandlers.print())
|
||||
.andExpect(MockMvcResultMatchers.status().is(302))
|
||||
.andExpect(MockMvcResultMatchers.header()
|
||||
.string("Clear-Site-Data", "\"cache\", \"cookies\", \"storage\""));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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 SessionConfigurationLiveTest {
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
13
spring-security-modules/spring-security-web-mvc/src/test/resources/.gitignore
vendored
Normal file
13
spring-security-modules/spring-security-web-mvc/src/test/resources/.gitignore
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
Reference in New Issue
Block a user