Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serve static resources (JS, CSS) from dedicated filter #15723

Merged
merged 7 commits into from
Sep 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
import org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter;
import org.springframework.security.web.authentication.ui.DefaultOneTimeTokenSubmitPageGeneratingFilter;
import org.springframework.security.web.authentication.ui.DefaultResourcesFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.authentication.www.DigestAuthenticationFilter;
import org.springframework.security.web.context.SecurityContextHolderFilter;
Expand Down Expand Up @@ -101,6 +102,7 @@ final class FilterOrderRegistration {
order.next());
put(UsernamePasswordAuthenticationFilter.class, order.next());
order.next(); // gh-8105
put(DefaultResourcesFilter.class, order.next());
put(DefaultLoginPageGeneratingFilter.class, order.next());
put(DefaultLogoutPageGeneratingFilter.class, order.next());
put(DefaultOneTimeTokenSubmitPageGeneratingFilter.class, order.next());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
import org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter;
import org.springframework.security.web.authentication.ui.DefaultResourcesFilter;
import org.springframework.security.web.csrf.CsrfToken;

/**
Expand Down Expand Up @@ -98,6 +99,7 @@ public void configure(H http) {
if (this.loginPageGeneratingFilter.isEnabled() && authenticationEntryPoint == null) {
this.loginPageGeneratingFilter = postProcess(this.loginPageGeneratingFilter);
http.addFilter(this.loginPageGeneratingFilter);
http.addFilter(DefaultResourcesFilter.css());
LogoutConfigurer<H> logoutConfigurer = http.getConfigurer(LogoutConfigurer.class);
if (logoutConfigurer != null) {
http.addFilter(this.logoutPageGeneratingFilter);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
import org.springframework.security.web.authentication.ott.OneTimeTokenAuthenticationConverter;
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
import org.springframework.security.web.authentication.ui.DefaultOneTimeTokenSubmitPageGeneratingFilter;
import org.springframework.security.web.authentication.ui.DefaultResourcesFilter;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.security.web.csrf.CsrfToken;
Expand Down Expand Up @@ -136,6 +137,7 @@ private void configureOttGenerateFilter(H http) {
generateFilter.setGeneratedOneTimeTokenHandler(getGeneratedOneTimeTokenHandler(http));
generateFilter.setRequestMatcher(antMatcher(HttpMethod.POST, this.generateTokenUrl));
http.addFilter(postProcess(generateFilter));
http.addFilter(DefaultResourcesFilter.css());
}

private GeneratedOneTimeTokenHandler getGeneratedOneTimeTokenHandler(H http) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@
import org.springframework.security.web.server.savedrequest.ServerRequestCacheWebFilter;
import org.springframework.security.web.server.savedrequest.WebSessionServerRequestCache;
import org.springframework.security.web.server.transport.HttpsRedirectWebFilter;
import org.springframework.security.web.server.ui.DefaultResourcesWebFilter;
import org.springframework.security.web.server.ui.LoginPageGeneratingWebFilter;
import org.springframework.security.web.server.ui.LogoutPageGeneratingWebFilter;
import org.springframework.security.web.server.util.matcher.AndServerWebExchangeMatcher;
Expand Down Expand Up @@ -2974,6 +2975,7 @@ protected void configure(ServerHttpSecurity http) {
}
if (loginPage != null) {
http.addFilterAt(loginPage, SecurityWebFiltersOrder.LOGIN_PAGE_GENERATING);
http.addFilterBefore(DefaultResourcesWebFilter.css(), SecurityWebFiltersOrder.LOGIN_PAGE_GENERATING);
if (http.logout != null) {
http.addFilterAt(new LogoutPageGeneratingWebFilter(),
SecurityWebFiltersOrder.LOGOUT_PAGE_GENERATING);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
import org.springframework.security.web.authentication.ui.DefaultResourcesFilter;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.DefaultCsrfToken;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
Expand All @@ -46,6 +47,7 @@
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
Expand All @@ -55,6 +57,7 @@
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

Expand All @@ -67,143 +70,6 @@
@ExtendWith(SpringTestContextExtension.class)
public class DefaultLoginPageConfigurerTests {

public static final String EXPECTED_HTML_HEAD = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Please sign in</title>
<style>
/* General layout */
body {
font-family: system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
background-color: #eee;
padding: 40px 0;
margin: 0;
line-height: 1.5;
}
\s\s\s\s
h2 {
margin-top: 0;
margin-bottom: 0.5rem;
font-size: 2rem;
font-weight: 500;
line-height: 2rem;
}
\s\s\s\s
.content {
margin-right: auto;
margin-left: auto;
padding-right: 15px;
padding-left: 15px;
width: 100%;
box-sizing: border-box;
}
\s\s\s\s
@media (min-width: 800px) {
.content {
max-width: 760px;
}
}
\s\s\s\s
/* Components */
a,
a:visited {
text-decoration: none;
color: #06f;
}
\s\s\s\s
a:hover {
text-decoration: underline;
color: #003c97;
}
\s\s\s\s
input[type="text"],
input[type="password"] {
height: auto;
width: 100%;
font-size: 1rem;
padding: 0.5rem;
box-sizing: border-box;
}
\s\s\s\s
button {
padding: 0.5rem 1rem;
font-size: 1.25rem;
line-height: 1.5;
border: none;
border-radius: 0.1rem;
width: 100%;
}
\s\s\s\s
button.primary {
color: #fff;
background-color: #06f;
}
\s\s\s\s
.alert {
padding: 0.75rem 1rem;
margin-bottom: 1rem;
line-height: 1.5;
border-radius: 0.1rem;
width: 100%;
box-sizing: border-box;
border-width: 1px;
border-style: solid;
}
\s\s\s\s
.alert.alert-danger {
color: #6b1922;
background-color: #f7d5d7;
border-color: #eab6bb;
}
\s\s\s\s
.alert.alert-success {
color: #145222;
background-color: #d1f0d9;
border-color: #c2ebcb;
}
\s\s\s\s
.screenreader {
position: absolute;
clip: rect(0 0 0 0);
height: 1px;
width: 1px;
padding: 0;
border: 0;
overflow: hidden;
}
\s\s\s\s
table {
width: 100%;
max-width: 100%;
margin-bottom: 2rem;
}
\s\s\s\s
.table-striped tr:nth-of-type(2n + 1) {
background-color: #e1e1e1;
}
\s\s\s\s
td {
padding: 0.75rem;
vertical-align: top;
}
\s\s\s\s
/* Login / logout layouts */
.login-form,
.logout-form {
max-width: 340px;
padding: 0 15px 15px 15px;
margin: 0 auto 2rem auto;
box-sizing: border-box;
}
</style>
</head>
""";

public final SpringTestContext spring = new SpringTestContext(this);

@Autowired
Expand All @@ -224,9 +90,17 @@ public void loginPageThenDefaultLoginPageIsRendered() throws Exception {
this.mvc.perform(get("/login").sessionAttr(csrfAttributeName, csrfToken))
.andExpect((result) -> {
CsrfToken token = (CsrfToken) result.getRequest().getAttribute(CsrfToken.class.getName());
assertThat(result.getResponse().getContentAsString()).isEqualTo(
EXPECTED_HTML_HEAD +
"""
assertThat(result.getResponse().getContentAsString()).isEqualTo("""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Please sign in</title>
<link href="/default-ui.css" rel="stylesheet" />
</head>
<body>
<div class="content">
<form class="login-form" method="post" action="/login">
Expand Down Expand Up @@ -271,9 +145,17 @@ public void loginPageWhenErrorThenDefaultLoginPageWithError() throws Exception {
.sessionAttr(csrfAttributeName, csrfToken))
.andExpect((result) -> {
CsrfToken token = (CsrfToken) result.getRequest().getAttribute(CsrfToken.class.getName());
assertThat(result.getResponse().getContentAsString()).isEqualTo(
EXPECTED_HTML_HEAD +
"""
assertThat(result.getResponse().getContentAsString()).isEqualTo("""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Please sign in</title>
<link href="/default-ui.css" rel="stylesheet" />
</head>
<body>
<div class="content">
<form class="login-form" method="post" action="/login">
Expand Down Expand Up @@ -322,9 +204,17 @@ public void loginPageWhenLoggedOutThenDefaultLoginPageWithLogoutMessage() throws
this.mvc.perform(get("/login?logout").sessionAttr(csrfAttributeName, csrfToken))
.andExpect((result) -> {
CsrfToken token = (CsrfToken) result.getRequest().getAttribute(CsrfToken.class.getName());
assertThat(result.getResponse().getContentAsString()).isEqualTo(
EXPECTED_HTML_HEAD +
"""
assertThat(result.getResponse().getContentAsString()).isEqualTo("""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Please sign in</title>
<link href="/default-ui.css" rel="stylesheet" />
</head>
<body>
<div class="content">
<form class="login-form" method="post" action="/login">
Expand All @@ -349,7 +239,15 @@ public void loginPageWhenLoggedOutThenDefaultLoginPageWithLogoutMessage() throws
</body>
</html>""".formatted(token.getToken()));
});
// @formatter:on
}

@Test
public void cssWhenFormLoginConfiguredThenServesCss() throws Exception {
this.spring.register(DefaultLoginPageConfig.class).autowire();
this.mvc.perform(get("/default-ui.css"))
.andExpect(status().isOk())
.andExpect(header().string("content-type", "text/css;charset=UTF-8"))
.andExpect(content().string(containsString("body {")));
}

@Test
Expand All @@ -373,9 +271,17 @@ public void loginPageWhenRememberConfigureThenDefaultLoginPageWithRememberMeChec
this.mvc.perform(get("/login").sessionAttr(csrfAttributeName, csrfToken))
.andExpect((result) -> {
CsrfToken token = (CsrfToken) result.getRequest().getAttribute(CsrfToken.class.getName());
assertThat(result.getResponse().getContentAsString()).isEqualTo(
EXPECTED_HTML_HEAD +
"""
assertThat(result.getResponse().getContentAsString()).isEqualTo("""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Please sign in</title>
<link href="/default-ui.css" rel="stylesheet" />
</head>
<body>
<div class="content">
<form class="login-form" method="post" action="/login">
Expand Down Expand Up @@ -444,6 +350,22 @@ public void configureWhenAuthenticationEntryPointThenNoDefaultLoginPageGeneratin
.count()).isZero();
}

@Test
public void configureWhenAuthenticationEntryPointThenDoesNotServeCss() throws Exception {
this.spring.register(DefaultLoginWithCustomAuthenticationEntryPointConfig.class).autowire();
FilterChainProxy filterChain = this.spring.getContext().getBean(FilterChainProxy.class);
assertThat(filterChain.getFilterChains()
.get(0)
.getFilters()
.stream()
.filter((filter) -> filter.getClass().isAssignableFrom(DefaultResourcesFilter.class))
.count()).isZero();
//@formatter:off
this.mvc.perform(get("/default-ui.css"))
.andExpect(status().is3xxRedirection());
//@formatter:on
}

@Test
public void formLoginWhenLogoutEnabledThenCreatesDefaultLogoutPage() throws Exception {
this.spring.register(DefaultLogoutPageConfig.class).autowire();
Expand Down
Loading