Skip to content
Open
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
4 changes: 3 additions & 1 deletion example/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,9 @@ The main configuration file `src/main/resources/application.yaml` is shared by a

Besides configuration settings, the trusted certificate authority certificates may need to be configured as described in section [_3. Configure the trusted certificate authority certificates_](#3-configure-the-trusted-certificate-authority-certificates) above.

Spring Security has CSRF protection enabled by default. Web eID requires CSRF protection.
Spring Security has CSRF protection enabled by default. Web eID requires CSRF protection. By default, the frontend reads
CSRF tokens from Thymeleaf meta tags. Set `web-eid-auth-token.csrf.use-spa-configuration=true` to use Spring Security's
SPA-compatible CSRF setup with a JavaScript-readable `XSRF-TOKEN` cookie.

### Integration with Web eID components

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,14 @@

import eu.webeid.example.security.AuthTokenDTOAuthenticationProvider;
import eu.webeid.example.security.WebEidAjaxLoginProcessingFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
Expand All @@ -15,16 +21,38 @@
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler;
import org.springframework.security.web.csrf.CsrfTokenRequestHandler;
import org.springframework.security.web.csrf.XorCsrfTokenRequestAttributeHandler;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.function.Supplier;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = true)
public class ApplicationConfiguration implements WebMvcConfigurer {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http, AuthTokenDTOAuthenticationProvider authTokenDTOAuthenticationProvider, AuthenticationConfiguration authConfig) throws Exception {
public SecurityFilterChain filterChain(
HttpSecurity http,
AuthTokenDTOAuthenticationProvider authTokenDTOAuthenticationProvider,
AuthenticationConfiguration authConfig,
YAMLConfig config,
@Value("${web-eid-auth-token.csrf.use-spa-configuration:false}") boolean useSpaCsrfConfiguration,
@Value("${web-eid-auth-token.validation.local-origin}") String localOrigin
) throws Exception {
if (useSpaCsrfConfiguration) {
http
.csrf(csrf -> csrf
.csrfTokenRepository(createDefaultCsrfTokenRepository(localOrigin))
.csrfTokenRequestHandler(new SpaCsrfTokenRequestHandler()))
.cors(Customizer.withDefaults());
}
return http
.authenticationProvider(authTokenDTOAuthenticationProvider)
.addFilterBefore(new WebEidAjaxLoginProcessingFilter("/auth/login", authConfig.getAuthenticationManager()),
Expand All @@ -34,10 +62,62 @@ public SecurityFilterChain filterChain(HttpSecurity http, AuthTokenDTOAuthentica
.build();
}

@ConditionalOnProperty(name = "web-eid-auth-token.csrf.use-spa-configuration", havingValue = "true")
@Bean
public WebMvcConfigurer corsConfigurer(YAMLConfig config) {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins(config.getCorsAllowedOrigin())
Comment thread
svenzik marked this conversation as resolved.
.allowCredentials(true);
}
};
}

@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/welcome").setViewName("welcome");
}

private CookieCsrfTokenRepository createDefaultCsrfTokenRepository(String localOrigin) {
CookieCsrfTokenRepository cookieCsrfTokenRepository = CookieCsrfTokenRepository.withHttpOnlyFalse();
cookieCsrfTokenRepository.setCookieCustomizer(cookie -> cookie
.domain(toApexDomain(localOrigin))
.sameSite("Lax")
);
return cookieCsrfTokenRepository;
}

private String toApexDomain(String localOrigin) {
if (StringUtils.isBlank(localOrigin)) {
return null;
}

String hostname = StringUtils.substringAfter(localOrigin, "//");
String[] labels = hostname.split("\\.");
if (labels.length <= 2) {
return hostname;
}
return labels[labels.length - 2] + "." + labels[labels.length - 1];
}

private static final class SpaCsrfTokenRequestHandler implements CsrfTokenRequestHandler {
private final CsrfTokenRequestHandler plain = new CsrfTokenRequestAttributeHandler();
private final CsrfTokenRequestHandler xor = new XorCsrfTokenRequestAttributeHandler();

@Override
public void handle(HttpServletRequest request, HttpServletResponse response, Supplier<CsrfToken> csrfToken) {
xor.handle(request, response, csrfToken);
csrfToken.get();
}

@Override
public String resolveCsrfTokenValue(HttpServletRequest request, CsrfToken csrfToken) {
String headerValue = request.getHeader(csrfToken.getHeaderName());
return (StringUtils.isNotBlank(headerValue) ? plain : xor).resolveCsrfTokenValue(request, csrfToken);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,6 @@ public AuthTokenValidator validator(YAMLConfig yamlConfig) {
}
}

@Bean
public YAMLConfig yamlConfig() {
return new YAMLConfig();
}

private X509Certificate[] loadTrustedCACertificatesFromCerFiles() {
List<X509Certificate> caCertificates = new ArrayList<>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ public class YAMLConfig {
@Value("local-origin")
private String localOrigin;

private String corsAllowedOrigin;

@Value("site-cert-hash")
private String siteCertHash;

Expand All @@ -34,6 +36,11 @@ public String getLocalOrigin() {

public void setLocalOrigin(String localOrigin) {
this.localOrigin = localOrigin;
this.corsAllowedOrigin = localOrigin;
}

public String getCorsAllowedOrigin() {
return corsAllowedOrigin;
}

public String getSiteCertHash() {
Expand Down
40 changes: 40 additions & 0 deletions example/src/main/resources/static/js/csrf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// SPDX-FileCopyrightText: Estonian Information System Authority
// SPDX-License-Identifier: MIT

"use strict";

const CSRF_COOKIE_NAME = "XSRF-TOKEN";
const CSRF_COOKIE_HEADER_NAME = "X-XSRF-TOKEN";

export function csrfHeader() {
const cookieToken = getCookie(CSRF_COOKIE_NAME);
if (cookieToken) {
return {[CSRF_COOKIE_HEADER_NAME]: cookieToken};
}

const metaToken = document.querySelector("#csrftoken")?.content;
const metaHeaderName = document.querySelector("#csrfheadername")?.content;
if (metaToken && metaHeaderName) {
return {[metaHeaderName]: metaToken};
}

return {};
}

function getCookie(name) {
const encodedName = encodeURIComponent(name) + "=";
return document.cookie
.split(";")
.map(cookie => cookie.trim())
.filter(cookie => cookie.startsWith(encodedName))
.map(cookie => decodeCookieValue(cookie.substring(encodedName.length)))
.shift();
}

function decodeCookieValue(value) {
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
6 changes: 2 additions & 4 deletions example/src/main/resources/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -250,15 +250,13 @@ <h3><a id="for-developers"></a>For developers</h3>
<script type="module">
"use strict";
import * as webeid from "/js/web-eid.js";
import {csrfHeader} from "/js/csrf.js";
import {hideErrorMessage, showErrorMessage, checkHttpError} from "/js/errors.js";

hideErrorMessage();

const authButton = document.querySelector("#webeid-auth-button");

const csrfToken = document.querySelector('#csrftoken').content;
const csrfHeaderName = document.querySelector('#csrfheadername').content;

const lang = new URLSearchParams(window.location.search).get("lang") || "en";

authButton.addEventListener("click", async () => {
Expand All @@ -281,7 +279,7 @@ <h3><a id="for-developers"></a>For developers</h3>
method: "POST",
headers: {
"Content-Type": "application/json",
[csrfHeaderName]: csrfToken
...csrfHeader()
},
body: `{"auth-token": ${JSON.stringify(authToken)}}`
});
Expand Down
10 changes: 4 additions & 6 deletions example/src/main/resources/templates/welcome.html
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ <h2 class="adding-signature">Digital signing</h2>
<script type="module">
"use strict";
import * as webeid from "/js/web-eid.js";
import {csrfHeader} from "/js/csrf.js";
import {hideErrorMessage, showErrorMessage, checkHttpError} from "/js/errors.js";

const signButton = document.querySelector("#webeid-sign-button");
Expand All @@ -61,15 +62,12 @@ <h2 class="adding-signature">Digital signing</h2>
const fileNameText = document.querySelector("#file-name");
const exampleDocument = document.querySelector("#example-document");

const csrfToken = document.querySelector('#csrftoken').content;
const csrfHeaderName = document.querySelector('#csrfheadername').content;

document.querySelector("#webeid-logout-button").addEventListener("click", async () => {
await fetch("/logout", {
method: "POST",
headers: {
"Content-Type": "application/json",
[csrfHeaderName]: csrfToken
...csrfHeader()
}
});
window.location.href = "/";
Expand All @@ -95,7 +93,7 @@ <h2 class="adding-signature">Digital signing</h2>
method: "POST",
headers: {
"Content-Type": "application/json",
[csrfHeaderName]: csrfToken
...csrfHeader()
},
body: JSON.stringify({certificate, supportedSignatureAlgorithms}),
});
Expand All @@ -114,7 +112,7 @@ <h2 class="adding-signature">Digital signing</h2>
method: "POST",
headers: {
"Content-Type": "application/json",
[csrfHeaderName]: csrfToken
...csrfHeader()
},
body: JSON.stringify({signature, signatureAlgorithm}),
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// SPDX-FileCopyrightText: Estonian Information System Authority
// SPDX-License-Identifier: MIT

package eu.webeid.example;

import jakarta.servlet.Filter;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

@SpringBootTest(properties = "web-eid-auth-token.csrf.use-spa-configuration=true")
@WebAppConfiguration
class SpaCsrfConfigurationTest {

@Autowired
private WebApplicationContext context;

@Autowired
private Filter[] springSecurityFilterChain;

@Test
void rootWhenSpaCsrfConfigurationIsEnabledWritesReadableXsrfTokenCookie() throws Exception {
MockHttpServletResponse response = MockMvcBuilders.webAppContextSetup(context)
.addFilters(springSecurityFilterChain)
.build()
.perform(get("/"))
.andReturn()
.getResponse();

assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getHeader(HttpHeaders.SET_COOKIE))
.startsWith("XSRF-TOKEN=")
.containsPattern("XSRF-TOKEN=[^;]+")
.contains("Path=/")
.contains("Domain=ria.ee")
.doesNotContain("HttpOnly");
}
}
11 changes: 10 additions & 1 deletion example/src/test/java/eu/webeid/example/WebApplicationTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,19 @@
import eu.webeid.security.validator.certvalidators.SubjectCertificateNotRevokedValidator;

import java.security.cert.X509Certificate;
import java.util.regex.Pattern;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

@SpringBootTest
@WebAppConfiguration
public class WebApplicationTest {

private static final Pattern CSRF_TOKEN_META_TAG = Pattern.compile("<meta id=\"csrftoken\" name=\"csrftoken\" content=\"[^\"]+\"/>");

@Autowired
private WebApplicationContext context;

Expand All @@ -59,7 +64,11 @@ public void testRoot() throws Exception {
.getResponse();
// @formatter:on
assertEquals(HttpStatus.OK.value(), response.getStatus());
System.out.println(response.getContentAsString());
assertNull(response.getCookie("XSRF-TOKEN"));
String content = response.getContentAsString();
assertTrue(CSRF_TOKEN_META_TAG.matcher(content).find());
assertTrue(content.contains("<meta id=\"csrfheadername\" name=\"csrfheadername\" content=\"X-CSRF-TOKEN\"/>"));
System.out.println(content);
}

@Test
Expand Down
Loading