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 @@ -24,6 +24,9 @@

import eu.webeid.example.security.AuthTokenDTOAuthenticationProvider;
import eu.webeid.example.security.WebEidAjaxLoginProcessingFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
Expand All @@ -34,17 +37,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.util.StringUtils;
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 {

private final boolean useSpaCsrfConfiguration;

public ApplicationConfiguration(@Value("${web-eid-auth-token.csrf.use-spa-configuration:false}") String useSpaCsrfConfiguration) {
this.useSpaCsrfConfiguration = Boolean.TRUE.toString().equalsIgnoreCase(useSpaCsrfConfiguration);
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http, AuthTokenDTOAuthenticationProvider authTokenDTOAuthenticationProvider, AuthenticationConfiguration authConfig) throws Exception {
return http
.csrf(csrf -> {
if (useSpaCsrfConfiguration) {
csrf
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.csrfTokenRequestHandler(new SpaCsrfTokenRequestHandler());
}
})
.authenticationProvider(authTokenDTOAuthenticationProvider)
.addFilterBefore(new WebEidAjaxLoginProcessingFilter("/auth/login", authConfig.getAuthenticationManager()),
UsernamePasswordAuthenticationFilter.class)
Expand All @@ -59,4 +83,21 @@ public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/welcome").setViewName("welcome");
}

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.hasText(headerValue) ? plain : xor).resolveCsrfTokenValue(request, csrfToken);
}
}

}
2 changes: 2 additions & 0 deletions example/src/main/resources/application-dev.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
web-eid-auth-token:
csrf:
use-spa-configuration: true
validation:
use-digidoc4j-prod-configuration: false
local-origin: "https://test.web-eid.eu"
37 changes: 37 additions & 0 deletions example/src/main/resources/static/js/csrf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"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 @@ -248,15 +248,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 @@ -279,7 +277,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 @@ -51,6 +51,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 @@ -59,15 +60,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 @@ -93,7 +91,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 @@ -112,7 +110,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,66 @@
/*
* Copyright (c) 2020-2026 Estonian Information System Authority
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

package eu.webeid.example;

import jakarta.servlet.Filter;
import jakarta.servlet.http.Cookie;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
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();

Cookie csrfCookie = response.getCookie("XSRF-TOKEN");

assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(csrfCookie).isNotNull();
assertThat(csrfCookie.isHttpOnly()).isFalse();
assertThat(csrfCookie.getValue()).isNotBlank();
assertThat(response.getContentAsString()).contains("id=\"csrftoken\"", "id=\"csrfheadername\"");
}
}
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 @@ -47,14 +47,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 @@ -78,7 +83,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