Merge pull request #11298 from azhwani/BAEL-5100

BAEL-5100: Update Manual Logout With Spring Security
This commit is contained in:
davidmartinezbarua 2021-10-12 19:52:30 -03:00 committed by GitHub
commit d00d394011
2 changed files with 89 additions and 53 deletions

View File

@ -1,8 +1,17 @@
package com.baeldung.manuallogout; package com.baeldung.manuallogout;
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.EXECUTION_CONTEXTS;
import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.STORAGE;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; 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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@ -10,25 +19,40 @@ import org.springframework.security.web.authentication.logout.HeaderWriterLogout
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter; import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter;
import javax.servlet.http.Cookie;
import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.*;
@Configuration @Configuration
@EnableWebSecurity @EnableWebSecurity
public class SimpleSecurityConfiguration { public class SimpleSecurityConfiguration {
private static Logger logger = LoggerFactory.getLogger(SimpleSecurityConfiguration.class);
@Order(4)
@Configuration
public static class LogoutOnRequestConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/request/**")
.authorizeRequests(authz -> authz.anyRequest()
.permitAll())
.logout(logout -> logout.logoutUrl("/request/logout")
.addLogoutHandler((request, response, auth) -> {
try {
request.logout();
} catch (ServletException e) {
logger.error(e.getMessage());
}
}));
}
}
@Order(3) @Order(3)
@Configuration @Configuration
public static class DefaultLogoutConfiguration extends WebSecurityConfigurerAdapter { public static class DefaultLogoutConfiguration extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http.antMatcher("/basic/**")
.antMatcher("/basic/**") .authorizeRequests(authz -> authz.anyRequest()
.authorizeRequests(authz -> authz.anyRequest().permitAll()) .permitAll())
.logout(logout -> logout .logout(logout -> logout.logoutUrl("/basic/basiclogout"));
.logoutUrl("/basic/basiclogout")
);
} }
} }
@ -37,11 +61,10 @@ public class SimpleSecurityConfiguration {
public static class AllCookieClearingLogoutConfiguration extends WebSecurityConfigurerAdapter { public static class AllCookieClearingLogoutConfiguration extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http.antMatcher("/cookies/**")
.antMatcher("/cookies/**") .authorizeRequests(authz -> authz.anyRequest()
.authorizeRequests(authz -> authz.anyRequest().permitAll()) .permitAll())
.logout(logout -> logout .logout(logout -> logout.logoutUrl("/cookies/cookielogout")
.logoutUrl("/cookies/cookielogout")
.addLogoutHandler(new SecurityContextLogoutHandler()) .addLogoutHandler(new SecurityContextLogoutHandler())
.addLogoutHandler((request, response, auth) -> { .addLogoutHandler((request, response, auth) -> {
for (Cookie cookie : request.getCookies()) { for (Cookie cookie : request.getCookies()) {
@ -50,8 +73,7 @@ public class SimpleSecurityConfiguration {
cookieToDelete.setMaxAge(0); cookieToDelete.setMaxAge(0);
response.addCookie(cookieToDelete); response.addCookie(cookieToDelete);
} }
}) }));
);
} }
} }
@ -59,18 +81,15 @@ public class SimpleSecurityConfiguration {
@Configuration @Configuration
public static class ClearSiteDataHeaderLogoutConfiguration extends WebSecurityConfigurerAdapter { public static class ClearSiteDataHeaderLogoutConfiguration extends WebSecurityConfigurerAdapter {
private static final ClearSiteDataHeaderWriter.Directive[] SOURCE = private static final ClearSiteDataHeaderWriter.Directive[] SOURCE = { CACHE, COOKIES, STORAGE, EXECUTION_CONTEXTS };
{CACHE, COOKIES, STORAGE, EXECUTION_CONTEXTS};
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http http.antMatcher("/csd/**")
.antMatcher("/csd/**") .authorizeRequests(authz -> authz.anyRequest()
.authorizeRequests(authz -> authz.anyRequest().permitAll()) .permitAll())
.logout(logout -> logout .logout(logout -> logout.logoutUrl("/csd/csdlogout")
.logoutUrl("/csd/csdlogout") .addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(SOURCE))));
.addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(SOURCE)))
);
} }
} }
} }

View File

@ -1,5 +1,17 @@
package com.baeldung.manuallogout; package com.baeldung.manuallogout;
import static org.junit.Assert.assertNull;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.cookie;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -7,20 +19,9 @@ import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession; import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.test.context.support.WithMockUser; import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import static org.junit.Assert.assertNull;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@WebMvcTest() @WebMvcTest()
public class ManualLogoutIntegrationTest { public class ManualLogoutIntegrationTest {
@ -39,7 +40,8 @@ public class ManualLogoutIntegrationTest {
@Test @Test
public void givenLoggedUserWhenUserLogoutThenSessionClearedAndNecessaryCookieCleared() throws Exception { public void givenLoggedUserWhenUserLogoutThenSessionClearedAndNecessaryCookieCleared() throws Exception {
this.mockMvc.perform(post("/basic/basiclogout").secure(true).with(csrf())) this.mockMvc.perform(post("/basic/basiclogout").secure(true)
.with(csrf()))
.andExpect(status().is3xxRedirection()) .andExpect(status().is3xxRedirection())
.andExpect(unauthenticated()) .andExpect(unauthenticated())
.andReturn(); .andReturn();
@ -55,7 +57,10 @@ public class ManualLogoutIntegrationTest {
Cookie randomCookie = new Cookie(COOKIE_NAME, COOKIE_VALUE); Cookie randomCookie = new Cookie(COOKIE_NAME, COOKIE_VALUE);
randomCookie.setMaxAge(EXPIRY); // 10 minutes randomCookie.setMaxAge(EXPIRY); // 10 minutes
MockHttpServletRequest requestStateAfterLogout = this.mockMvc.perform(post("/cookies/cookielogout").secure(true).with(csrf()).session(session).cookie(randomCookie)) MockHttpServletRequest requestStateAfterLogout = this.mockMvc.perform(post("/cookies/cookielogout").secure(true)
.with(csrf())
.session(session)
.cookie(randomCookie))
.andExpect(status().is3xxRedirection()) .andExpect(status().is3xxRedirection())
.andExpect(unauthenticated()) .andExpect(unauthenticated())
.andExpect(cookie().maxAge(COOKIE_NAME, 0)) .andExpect(cookie().maxAge(COOKIE_NAME, 0))
@ -70,10 +75,22 @@ public class ManualLogoutIntegrationTest {
@Test @Test
public void givenLoggedUserWhenUserLogoutThenClearDataSiteHeaderPresent() throws Exception { public void givenLoggedUserWhenUserLogoutThenClearDataSiteHeaderPresent() throws Exception {
this.mockMvc.perform(post("/csd/csdlogout").secure(true).with(csrf())) this.mockMvc.perform(post("/csd/csdlogout").secure(true)
.with(csrf()))
.andDo(print()) .andDo(print())
.andExpect(status().is3xxRedirection()) .andExpect(status().is3xxRedirection())
.andExpect(header().exists(CLEAR_SITE_DATA_HEADER)) .andExpect(header().exists(CLEAR_SITE_DATA_HEADER))
.andReturn(); .andReturn();
} }
@WithMockUser(value = "spring")
@Test
public void givenLoggedUserWhenUserLogoutOnRequestThenSessionCleared() throws Exception {
this.mockMvc.perform(post("/request/logout").secure(true)
.with(csrf()))
.andExpect(status().is3xxRedirection())
.andExpect(unauthenticated())
.andReturn();
}
} }