Leantel

Quickstart: Java and Spring Boot

A Spring Boot app in Java that signs people in with Leantel, protects an API route, and receives webhooks. Tested with Spring Boot 4.1, Spring Security 7, Java 17 and Maven. Read auth.md for an explanation of each step. Using Kotlin? See the Kotlin quickstart.

1. Set up

In the Leantel console, create a Web app with a backend. Register https://<your app>/login/oauth2/code/leantel as a redirect URL (Spring's default) and https://<your app>/ as a sign-out redirect URL. To try it on your computer first, also register http://localhost:<port> versions of both URLs: Leantel accepts exact http://localhost and http://127.0.0.1 URLs for apps with a backend, and for single-page apps in development workspaces; the port must match exactly. Add these dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
src/main/resources/application.yml
leantel:
  issuer: ${LEANTEL_ISSUER}
  audience: ${LEANTEL_AUDIENCE}
  post-logout-uri: ${LEANTEL_POST_LOGOUT_URI}
  webhook-secret: ${LEANTEL_WEBHOOK_SECRET}

app:
  api-url: ${APP_API_URL}

spring:
  security:
    oauth2:
      client:
        registration:
          leantel:
            client-id: ${LEANTEL_CLIENT_ID}
            client-secret: ${LEANTEL_CLIENT_SECRET}
            authorization-grant-type: authorization_code
            redirect-uri: ${LEANTEL_REDIRECT_URI}
            scope: openid,email
        provider:
          leantel:
            issuer-uri: ${LEANTEL_ISSUER}

Set LEANTEL_REDIRECT_URI to the redirect URL above.

2. Sign in, sign out and protect the API

SecurityConfig.java
package com.example.northwind;

import java.time.Duration;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.client.oidc.web.logout.OidcClientInitiatedLogoutSuccessHandler;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizationRequestResolver;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestCustomizers;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.JwtClaimValidator;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtIssuerValidator;
import org.springframework.security.oauth2.jwt.JwtTimestampValidator;
import org.springframework.security.oauth2.jwt.JwtTypeValidator;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {
    private final String issuer;
    private final String audience;
    private final String postLogoutUri;

    public SecurityConfig(
            @Value("${leantel.issuer}") String issuer,
            @Value("${leantel.audience}") String audience,
            @Value("${leantel.post-logout-uri}") String postLogoutUri) {
        this.issuer = issuer;
        this.audience = audience;
        this.postLogoutUri = postLogoutUri;
    }

    public static JwtDecoder leantelAccessTokenDecoder(String issuer, String audience) {
        NimbusJwtDecoder decoder = NimbusJwtDecoder.withJwkSetUri(issuer + "/.well-known/jwks.json")
                .jwsAlgorithm(SignatureAlgorithm.RS256)
                .validateType(false)
                .build();
        decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(
                new JwtTimestampValidator(Duration.ofSeconds(60)),
                new JwtIssuerValidator(issuer),
                new JwtTypeValidator(List.of("at+jwt")),
                new JwtClaimValidator<List<String>>("aud", values -> values != null && values.contains(audience)),
                required("exp"), required("iat"), required("sub"), required("jti"), required("client_id"), required("tenant_id")));
        return decoder;
    }

    private static JwtClaimValidator<Object> required(String claim) {
        return new JwtClaimValidator<>(claim, value -> value != null && !value.toString().isBlank());
    }

    @Bean
    public JwtDecoder jwtDecoder() {
        return leantelAccessTokenDecoder(issuer, audience);
    }

    @Bean
    @Order(1)
    public SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
        http.securityMatcher("/api/**")
                .authorizeHttpRequests(requests -> requests.anyRequest().authenticated())
                .oauth2ResourceServer(server -> server.jwt(jwt -> { }))
                .sessionManagement(sessions -> sessions.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .csrf(csrf -> csrf.disable());
        return http.build();
    }

    @Bean
    @Order(2)
    public SecurityFilterChain webSecurity(HttpSecurity http, ClientRegistrationRepository registrations) throws Exception {
        DefaultOAuth2AuthorizationRequestResolver resolver =
                new DefaultOAuth2AuthorizationRequestResolver(registrations, "/oauth2/authorization");
        resolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce());
        OidcClientInitiatedLogoutSuccessHandler logoutHandler = new OidcClientInitiatedLogoutSuccessHandler(registrations);
        logoutHandler.setPostLogoutRedirectUri(postLogoutUri);
        http.authorizeHttpRequests(requests -> requests
                        .requestMatchers("/", "/webhooks/leantel").permitAll()
                        .anyRequest().authenticated())
                .oauth2Login(login -> login.authorizationEndpoint(endpoint -> endpoint.authorizationRequestResolver(resolver)))
                .logout(logout -> logout.logoutSuccessHandler(logoutHandler))
                .csrf(csrf -> csrf.ignoringRequestMatchers("/webhooks/leantel"));
        return http.build();
    }
}

Two things differ from Spring's defaults, on purpose:

  • typ: at+jwt. Spring Security's default validator only accepts tokens typed JWT, and Leantel access tokens are typed at+jwt (RFC 9068). leantelAccessTokenDecoder lists the checks explicitly instead.
  • PKCE. Spring only adds PKCE for public clients by default; the customizer adds it for your confidential app too.

A bad or missing token gets 401. Permissions arrive as authorities named SCOPE_<permission>. To require one on a route, add .requestMatchers("/api/reports/**").hasAuthority("SCOPE_app:use") before .anyRequest() in apiSecurity. A token without it gets 403. Set up Auth gives your workspace the permission app:use and the role member, which everyone who signs up gets; add your own permissions under APIs and permissions and grant them through roles (auth.md section 7).

Application.java
package com.example.northwind;

import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.client.OAuth2ClientHttpRequestInterceptor;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClient;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@RestController
class MeController {
    @GetMapping("/api/me")
    Map<String, String> apiMe(@AuthenticationPrincipal Jwt token) {
        Map<String, String> result = new HashMap<>();
        result.put("tenantId", token.getClaimAsString("tenant_id"));
        result.put("userId", token.getSubject());
        return result;
    }

    @GetMapping("/me")
    Map<String, String> me(@AuthenticationPrincipal OidcUser user) {
        Map<String, String> result = new HashMap<>();
        result.put("userId", user.getSubject());
        result.put("tenantId", user.getClaimAsString("tenant_id"));
        result.put("email", user.getEmail());
        return result;
    }
}

@RestController
class HomeController {
    private final RestClient api;

    HomeController(OAuth2AuthorizedClientManager clients, @Value("${app.api-url}") String apiUrl) {
        OAuth2ClientHttpRequestInterceptor interceptor = new OAuth2ClientHttpRequestInterceptor(clients);
        interceptor.setClientRegistrationIdResolver(request -> "leantel");
        this.api = RestClient.builder().baseUrl(apiUrl).requestInterceptor(interceptor).build();
    }

    @GetMapping("/")
    String home(@AuthenticationPrincipal OidcUser user) {
        if (user == null) {
            return "<a href=\"/oauth2/authorization/leantel\">Sign in</a>";
        }
        return api.get().uri("/api/me").retrieve().body(String.class);
    }
}

3. Receive webhooks

LeantelWebhookController.java
package com.example.northwind;

import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;

@RestController
public class LeantelWebhookController {
    private final String secret;
    private final ObjectMapper objectMapper;
    private final Set<String> handledEventIds = ConcurrentHashMap.newKeySet();

    public LeantelWebhookController(@Value("${leantel.webhook-secret}") String secret, ObjectMapper objectMapper) {
        this.secret = secret;
        this.objectMapper = objectMapper;
    }

    public static boolean isValidLeantelSignature(String header, byte[] body, String secret, Instant now) {
        Map<String, String> parts = new HashMap<>();
        for (String part : header.split(",")) {
            String[] pair = part.split("=", 2);
            parts.put(pair[0], pair.length == 2 ? pair[1] : "");
        }
        long timestamp;
        try {
            timestamp = Long.parseLong(parts.getOrDefault("t", ""));
        } catch (NumberFormatException exception) {
            return false;
        }
        if (Math.abs(now.getEpochSecond() - timestamp) > 300) {
            return false;
        }
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            mac.update((timestamp + ".").getBytes(StandardCharsets.UTF_8));
            String expected = HexFormat.of().formatHex(mac.doFinal(body));
            return MessageDigest.isEqual(
                    expected.getBytes(StandardCharsets.UTF_8),
                    parts.getOrDefault("v1", "").getBytes(StandardCharsets.UTF_8));
        } catch (GeneralSecurityException exception) {
            return false;
        }
    }

    @PostMapping("/webhooks/leantel")
    public ResponseEntity<Void> receive(@RequestHeader("Auth-Signature") String signature, @RequestBody byte[] body) {
        if (!isValidLeantelSignature(signature, body, secret, Instant.now())) {
            return ResponseEntity.status(401).build();
        }
        JsonNode event = objectMapper.readTree(body);
        if (handledEventIds.add(event.get("id").asString())) {
            System.out.println("leantel event " + event.get("type").asString() + " " + event.get("id").asString());
        }
        return ResponseEntity.ok().build();
    }
}

Spring Boot 4 uses Jackson 3, whose packages start with tools.jackson. The in-memory set of handled event IDs is for trying it out; record them in your database in production.

4. Check it works

  • Open /oauth2/authorization/leantel: you land on your branded Leantel sign-in page, then back signed in; /me shows your IDs.
  • Open /: HomeController calls your API's /api/me through a RestClient with Spring's OAuth2ClientHttpRequestInterceptor, which attaches the access token, refreshes it when it has expired and stores the rotated refresh token. Set APP_API_URL to your app's own URL.
  • curl -i https://<your app>/api/me (no token) → 401.
  • In the console, Webhooks → Send test event → your log shows it.