diff --git a/web/src/main/java/org/springframework/security/web/server/ui/HtmlTemplates.java b/web/src/main/java/org/springframework/security/web/server/ui/HtmlTemplates.java new file mode 100644 index 0000000000..432b1b65a5 --- /dev/null +++ b/web/src/main/java/org/springframework/security/web/server/ui/HtmlTemplates.java @@ -0,0 +1,108 @@ +/* + * Copyright 2002-2024 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.web.server.ui; + +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import org.springframework.util.StringUtils; +import org.springframework.web.util.HtmlUtils; + +/** + * Render HTML templates using string substitution. Intended for internal use. Variables + * can be templated using double curly-braces: {@code {{name}}}. + * + * @author Daniel Garnier-Moiroux + * @since 6.4 + * @see org.springframework.security.web.authentication.ui.HtmlTemplates + */ +final class HtmlTemplates { + + private HtmlTemplates() { + } + + static Builder fromTemplate(String template) { + return new Builder(template); + } + + static final class Builder { + + private final String template; + + private final Map values = new HashMap<>(); + + private Builder(String template) { + this.template = template; + } + + /** + * HTML-escape, and inject value {@code value} in every {@code {{key}}} + * placeholder. + * @param key the placeholder name + * @param value the value to inject + * @return this instance for further templating + */ + Builder withValue(String key, String value) { + this.values.put(key, HtmlUtils.htmlEscape(value)); + return this; + } + + /** + * Inject value {@code value} in every {@code {{key}}} placeholder without + * HTML-escaping. Useful for injecting "sub-templates". + * @param key the placeholder name + * @param value the value to inject + * @return this instance for further templating + */ + Builder withRawHtml(String key, String value) { + if (!value.isEmpty() && value.charAt(value.length() - 1) == '\n') { + value = value.substring(0, value.length() - 1); + } + this.values.put(key, value); + return this; + } + + /** + * Render the template. All placeholders MUST have a corresponding value. If a + * placeholder does not have a corresponding value, throws + * {@link IllegalStateException}. + * @return the rendered template + */ + String render() { + String template = this.template; + for (String key : this.values.keySet()) { + String pattern = Pattern.quote("{{" + key + "}}"); + template = template.replaceAll(pattern, this.values.get(key)); + } + + String unusedPlaceholders = Pattern.compile("\\{\\{([a-zA-Z0-9]+)}}") + .matcher(template) + .results() + .map((result) -> result.group(1)) + .collect(Collectors.joining(", ")); + if (StringUtils.hasLength(unusedPlaceholders)) { + throw new IllegalStateException("Unused placeholders in template: [%s]".formatted(unusedPlaceholders)); + } + + return template; + } + + } + +} diff --git a/web/src/main/java/org/springframework/security/web/server/ui/LoginPageGeneratingWebFilter.java b/web/src/main/java/org/springframework/security/web/server/ui/LoginPageGeneratingWebFilter.java index 3065796ea4..3a18738448 100644 --- a/web/src/main/java/org/springframework/security/web/server/ui/LoginPageGeneratingWebFilter.java +++ b/web/src/main/java/org/springframework/security/web/server/ui/LoginPageGeneratingWebFilter.java @@ -19,6 +19,7 @@ package org.springframework.security.web.server.ui; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; +import java.util.stream.Collectors; import reactor.core.publisher.Mono; @@ -37,7 +38,6 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; -import org.springframework.web.util.HtmlUtils; /** * Generates a default log in page used for authenticating users. @@ -89,80 +89,61 @@ public class LoginPageGeneratingWebFilter implements WebFilter { private byte[] createPage(ServerWebExchange exchange, String csrfTokenHtmlInput) { MultiValueMap queryParams = exchange.getRequest().getQueryParams(); String contextPath = exchange.getRequest().getPath().contextPath().value(); - StringBuilder page = new StringBuilder(); - page.append("\n"); - page.append("\n"); - page.append(" \n"); - page.append(" \n"); - page.append(" \n"); - page.append(" \n"); - page.append(" \n"); - page.append(" Please sign in\n"); - page.append(CssUtils.getCssStyleBlock().indent(4)); - page.append(" \n"); - page.append(" \n"); - page.append("
\n"); - page.append(formLogin(queryParams, contextPath, csrfTokenHtmlInput)); - page.append(oauth2LoginLinks(queryParams, contextPath, this.oauth2AuthenticationUrlToClientName)); - page.append("
\n"); - page.append(" \n"); - page.append(""); - return page.toString().getBytes(Charset.defaultCharset()); + + return HtmlTemplates.fromTemplate(LOGIN_PAGE_TEMPLATE) + .withRawHtml("cssStyle", CssUtils.getCssStyleBlock().indent(4)) + .withRawHtml("formLogin", formLogin(queryParams, contextPath, csrfTokenHtmlInput)) + .withRawHtml("oauth2Login", oauth2Login(queryParams, contextPath, this.oauth2AuthenticationUrlToClientName)) + .render() + .getBytes(Charset.defaultCharset()); } private String formLogin(MultiValueMap queryParams, String contextPath, String csrfTokenHtmlInput) { if (!this.formLoginEnabled) { return ""; } + boolean isError = queryParams.containsKey("error"); boolean isLogoutSuccess = queryParams.containsKey("logout"); - StringBuilder page = new StringBuilder(); - page.append("
\n"); - page.append("

Please sign in

\n"); - page.append(createError(isError)); - page.append(createLogoutSuccess(isLogoutSuccess)); - page.append("

\n"); - page.append(" \n"); - page.append(" \n"); - page.append("

\n" + "

\n"); - page.append(" \n"); - page.append(" \n"); - page.append("

\n"); - page.append(csrfTokenHtmlInput); - page.append(" \n"); - page.append("
\n"); - return page.toString(); + + return HtmlTemplates.fromTemplate(LOGIN_FORM_TEMPLATE) + .withValue("loginUrl", contextPath + "/login") + .withRawHtml("errorMessage", createError(isError)) + .withRawHtml("logoutMessage", createLogoutSuccess(isLogoutSuccess)) + .withRawHtml("csrf", csrfTokenHtmlInput) + .render(); } - private static String oauth2LoginLinks(MultiValueMap queryParams, String contextPath, + private static String oauth2Login(MultiValueMap queryParams, String contextPath, Map oauth2AuthenticationUrlToClientName) { if (oauth2AuthenticationUrlToClientName.isEmpty()) { return ""; } boolean isError = queryParams.containsKey("error"); - StringBuilder sb = new StringBuilder(); - sb.append("

Login with OAuth 2.0

"); - sb.append(createError(isError)); - sb.append("\n"); - for (Map.Entry clientAuthenticationUrlToClientName : oauth2AuthenticationUrlToClientName - .entrySet()) { - sb.append(" \n"); - } - sb.append("
"); - String url = clientAuthenticationUrlToClientName.getKey(); - sb.append(""); - String clientName = HtmlUtils.htmlEscape(clientAuthenticationUrlToClientName.getValue()); - sb.append(clientName); - sb.append(""); - sb.append("
\n"); - return sb.toString(); + + String oauth2Rows = oauth2AuthenticationUrlToClientName.entrySet() + .stream() + .map((urlToName) -> oauth2LoginLink(contextPath, urlToName.getKey(), urlToName.getValue())) + .collect(Collectors.joining("\n")) + .indent(2); + return HtmlTemplates.fromTemplate(OAUTH2_LOGIN_TEMPLATE) + .withRawHtml("errorMessage", createError(isError)) + .withRawHtml("oauth2Rows", oauth2Rows) + .render(); + } + + private static String oauth2LoginLink(String contextPath, String url, String clientName) { + return HtmlTemplates.fromTemplate(OAUTH2_ROW_TEMPLATE) + .withValue("url", contextPath + url) + .withValue("clientName", clientName) + .render(); } private static String csrfToken(CsrfToken token) { - return " \n"; + return HtmlTemplates.fromTemplate(CSRF_INPUT_TEMPLATE) + .withValue("name", token.getParameterName()) + .withValue("value", token.getToken()) + .render(); } private static String createError(boolean isError) { @@ -174,4 +155,53 @@ public class LoginPageGeneratingWebFilter implements WebFilter { : ""; } + private static final String LOGIN_PAGE_TEMPLATE = """ + + + + + + + + Please sign in + {{cssStyle}} + + +
+ {{formLogin}} + {{oauth2Login}} +
+ + """; + + private static final String LOGIN_FORM_TEMPLATE = """ + """; + + private static final String CSRF_INPUT_TEMPLATE = """ + + """; + + private static final String OAUTH2_LOGIN_TEMPLATE = """ +

Login with OAuth 2.0

+ {{errorMessage}} + + {{oauth2Rows}} +
"""; + + private static final String OAUTH2_ROW_TEMPLATE = """ + {{clientName}}"""; + } diff --git a/web/src/main/java/org/springframework/security/web/server/ui/LogoutPageGeneratingWebFilter.java b/web/src/main/java/org/springframework/security/web/server/ui/LogoutPageGeneratingWebFilter.java index a691e2fdcb..34e850f80b 100644 --- a/web/src/main/java/org/springframework/security/web/server/ui/LogoutPageGeneratingWebFilter.java +++ b/web/src/main/java/org/springframework/security/web/server/ui/LogoutPageGeneratingWebFilter.java @@ -70,33 +70,45 @@ public class LogoutPageGeneratingWebFilter implements WebFilter { } private static byte[] createPage(String csrfTokenHtmlInput, String contextPath) { - StringBuilder page = new StringBuilder(); - page.append("\n"); - page.append("\n"); - page.append(" \n"); - page.append(" \n"); - page.append(" \n"); - page.append(" \n"); - page.append(" \n"); - page.append(" Confirm Log Out?\n"); - page.append(CssUtils.getCssStyleBlock().indent(4)); - page.append(" \n"); - page.append(" \n"); - page.append("
\n"); - page.append("
\n"); - page.append("

Are you sure you want to log out?

\n"); - page.append(csrfTokenHtmlInput); - page.append(" \n"); - page.append("
\n"); - page.append("
\n"); - page.append(" \n"); - page.append(""); - return page.toString().getBytes(Charset.defaultCharset()); + return HtmlTemplates.fromTemplate(LOGOUT_PAGE_TEMPLATE) + .withRawHtml("cssStyle", CssUtils.getCssStyleBlock().indent(4)) + .withValue("contextPath", contextPath) + .withRawHtml("csrf", csrfTokenHtmlInput.indent(8)) + .render() + .getBytes(Charset.defaultCharset()); } private static String csrfToken(CsrfToken token) { - return " \n"; + return HtmlTemplates.fromTemplate(CSRF_INPUT_TEMPLATE) + .withValue("name", token.getParameterName()) + .withValue("value", token.getToken()) + .render(); } + private static final String LOGOUT_PAGE_TEMPLATE = """ + + + + + + + + Confirm Log Out? + {{cssStyle}} + + +
+
+

Are you sure you want to log out?

+ {{csrf}} + +
+
+ + """; + + private static final String CSRF_INPUT_TEMPLATE = """ + + """; + } diff --git a/web/src/test/java/org/springframework/security/web/server/ui/LoginPageGeneratingWebFilterTests.java b/web/src/test/java/org/springframework/security/web/server/ui/LoginPageGeneratingWebFilterTests.java index 731097013b..6bbbc307e0 100644 --- a/web/src/test/java/org/springframework/security/web/server/ui/LoginPageGeneratingWebFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/server/ui/LoginPageGeneratingWebFilterTests.java @@ -16,6 +16,8 @@ package org.springframework.security.web.server.ui; +import java.util.Collections; + import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; @@ -45,4 +47,175 @@ public class LoginPageGeneratingWebFilterTests { assertThat(exchange.getResponse().getBodyAsString().block()).contains("action=\"/login\""); } + @Test + void filtersThenRendersPage() { + String clientName = "Google < > \" \' &"; + LoginPageGeneratingWebFilter filter = new LoginPageGeneratingWebFilter(); + filter.setOauth2AuthenticationUrlToClientName( + Collections.singletonMap("/oauth2/authorization/google", clientName)); + filter.setFormLoginEnabled(true); + MockServerWebExchange exchange = MockServerWebExchange + .from(MockServerHttpRequest.get("/test/login").contextPath("/test")); + filter.filter(exchange, (e) -> Mono.empty()).block(); + assertThat(exchange.getResponse().getBodyAsString().block()).isEqualTo(""" + + + + + + + + Please sign in + + + +
+ +

Login with OAuth 2.0

+ + + +
Google < > " ' &
+
+ + """); + } + } diff --git a/web/src/test/java/org/springframework/security/web/server/ui/LogoutPageGeneratingWebFilterTests.java b/web/src/test/java/org/springframework/security/web/server/ui/LogoutPageGeneratingWebFilterTests.java index a3b5b29ab2..fc5547767e 100644 --- a/web/src/test/java/org/springframework/security/web/server/ui/LogoutPageGeneratingWebFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/server/ui/LogoutPageGeneratingWebFilterTests.java @@ -49,6 +49,151 @@ public class LogoutPageGeneratingWebFilterTests { MockServerWebExchange exchange = MockServerWebExchange .from(MockServerHttpRequest.get("/test/logout").contextPath("/test")); filter.filter(exchange, (e) -> Mono.empty()).block(); + assertThat(exchange.getResponse().getBodyAsString().block()).isEqualTo(""" + + + + + + + + Confirm Log Out? + + + +
+
+

Are you sure you want to log out?

+ + +
+
+ + """); } }