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
7 changes: 6 additions & 1 deletion example/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,12 @@ 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 `WEBEID-XSRF-TOKEN` cookie. When
`web-eid-auth-token.csrf.cookie-domain` is not set, the cookie domain is derived from
`web-eid-auth-token.validation.local-origin`. Set `web-eid-auth-token.csrf.cookie-domain` to explicitly configure the
cookie domain.

### Integration with Web eID components

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,39 +5,116 @@

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.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
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;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
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 {

private static final String CSRF_COOKIE_NAME = "WEBEID-XSRF-TOKEN";

@Bean
public SecurityFilterChain filterChain(HttpSecurity http, AuthTokenDTOAuthenticationProvider authTokenDTOAuthenticationProvider, AuthenticationConfiguration authConfig) throws Exception {
public SecurityFilterChain filterChain(
HttpSecurity http,
AuthTokenDTOAuthenticationProvider authTokenDTOAuthenticationProvider,
AuthenticationConfiguration authConfig,
YAMLConfig validationConfig,
CsrfConfigurationProperties csrfConfig,
ServerProperties serverConfig
) throws Exception {
if (csrfConfig.isUseSpaConfiguration()) {
String cookieDomain = StringUtils.defaultIfBlank(
csrfConfig.getCookieDomain(), CookieDomainResolver.toApexDomain(validationConfig.getLocalOrigin()));
http
.csrf(csrf -> csrf
.csrfTokenRepository(createDefaultCsrfTokenRepository(cookieDomain))
.csrfTokenRequestHandler(new SpaCsrfTokenRequestHandler()))
.cors(Customizer.withDefaults());
}
return http
.authenticationProvider(authTokenDTOAuthenticationProvider)
.addFilterBefore(new WebEidAjaxLoginProcessingFilter("/auth/login", authConfig.getAuthenticationManager()),
UsernamePasswordAuthenticationFilter.class)
.logout(logout -> logout.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler()))
.logout(logout -> logout
.deleteCookies(StringUtils.defaultIfBlank(serverConfig.getServlet().getSession().getCookie().getName(), "JSESSIONID"))
.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler()))
.headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin))
.exceptionHandling(ex -> ex.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)))
.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 cookieDomain) {
CookieCsrfTokenRepository cookieCsrfTokenRepository = CookieCsrfTokenRepository.withHttpOnlyFalse();
cookieCsrfTokenRepository.setCookieName(CSRF_COOKIE_NAME);
cookieCsrfTokenRepository.setCookieCustomizer(cookie -> cookie
.domain(cookieDomain)
.sameSite("Lax")
);
return cookieCsrfTokenRepository;
}

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
@@ -0,0 +1,26 @@
// SPDX-FileCopyrightText: Estonian Information System Authority
// SPDX-License-Identifier: MIT

package eu.webeid.example.config;

import org.apache.commons.lang3.StringUtils;

public final class CookieDomainResolver {

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

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

private CookieDomainResolver() {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// SPDX-FileCopyrightText: Estonian Information System Authority
// SPDX-License-Identifier: MIT

package eu.webeid.example.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "web-eid-auth-token.csrf")
public class CsrfConfigurationProperties {

private boolean useSpaConfiguration;
private String cookieDomain;

public boolean isUseSpaConfiguration() {
return useSpaConfiguration;
}

public void setUseSpaConfiguration(boolean useSpaConfiguration) {
this.useSpaConfiguration = useSpaConfiguration;
}

public String getCookieDomain() {
return cookieDomain;
}

public void setCookieDomain(String cookieDomain) {
this.cookieDomain = cookieDomain;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,6 @@ public AuthTokenValidator validator(YAMLConfig yamlConfig) {
}
}

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

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

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

private String corsAllowedOrigin;

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

Expand All @@ -31,6 +33,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
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@

package eu.webeid.example.web.rest;

import com.fasterxml.jackson.core.JsonProcessingException;
import eu.webeid.example.security.ajax.AjaxAuthenticationSuccessHandler.AuthSuccessDTO;
import eu.webeid.example.service.dto.ChallengeDTO;
import eu.webeid.security.challenge.ChallengeNonceGenerator;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
Expand All @@ -23,4 +27,10 @@ public ChallengeController(ChallengeNonceGenerator challengeNonceGenerator) {
public ChallengeDTO challenge() {
return new ChallengeDTO(challengeNonceGenerator.generateAndStoreNonce().getBase64EncodedNonce());
}

@PreAuthorize("isAuthenticated()")
@GetMapping("user")
public String user(Authentication authentication) throws JsonProcessingException {
return AuthSuccessDTO.asJson(authentication);
}
}
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 = "WEBEID-XSRF-TOKEN";
const CSRF_COOKIE_HEADER_NAME = "X-XSRF-TOKEN";

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

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

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;
}
}
13 changes: 7 additions & 6 deletions example/src/main/resources/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>

<meta id="csrftoken" name="csrftoken" th:content="${_csrf.token}"/>
<meta id="csrfheadername" name="csrfheadername" th:content="${_csrf.headerName}"/>
<th:block th:unless="${@csrfConfigurationProperties.isUseSpaConfiguration()}">
<meta id="csrftoken" name="csrftoken" th:content="${_csrf.token}"/>
<meta id="csrfheadername" name="csrfheadername" th:content="${_csrf.headerName}"/>
</th:block>

<title>Web eID: electronic ID smart cards on the Web</title>
<link
Expand Down Expand Up @@ -250,15 +252,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,9 +279,10 @@ <h3><a id="for-developers"></a>For developers</h3>

const authTokenResponse = await fetch("/auth/login", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
[csrfHeaderName]: csrfToken
...csrfHeader()
},
body: `{"auth-token": ${JSON.stringify(authToken)}}`
});
Expand Down
19 changes: 11 additions & 8 deletions example/src/main/resources/templates/welcome.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>

<meta id="csrftoken" name="csrftoken" th:content="${_csrf.token}"/>
<meta id="csrfheadername" name="csrfheadername" th:content="${_csrf.headerName}"/>
<th:block th:unless="${@csrfConfigurationProperties.isUseSpaConfiguration()}">
<meta id="csrftoken" name="csrftoken" th:content="${_csrf.token}"/>
<meta id="csrfheadername" name="csrfheadername" th:content="${_csrf.headerName}"/>
</th:block>

<title>Welcome!</title>
<link
Expand Down Expand Up @@ -53,6 +55,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 +64,13 @@ <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",
credentials: "include",
headers: {
"Content-Type": "application/json",
[csrfHeaderName]: csrfToken
...csrfHeader()
}
});
window.location.href = "/";
Expand All @@ -93,9 +94,10 @@ <h2 class="adding-signature">Digital signing</h2>

const prepareSigningResponse = await fetch("/sign/prepare", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
[csrfHeaderName]: csrfToken
...csrfHeader()
},
body: JSON.stringify({certificate, supportedSignatureAlgorithms}),
});
Expand All @@ -112,9 +114,10 @@ <h2 class="adding-signature">Digital signing</h2>

const finalizeSigningResponse = await fetch("/sign/sign", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
[csrfHeaderName]: csrfToken
...csrfHeader()
},
body: JSON.stringify({signature, signatureAlgorithm}),
});
Expand Down
Loading
Loading