Leantel

Quickstart: Kotlin and Spring Boot

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

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:

implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-oauth2-client")
implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server")
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.kt
package com.example.northwind

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.JwtTypeValidator
import org.springframework.security.oauth2.jwt.JwtIssuerValidator
import org.springframework.security.oauth2.jwt.JwtTimestampValidator
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder
import org.springframework.security.web.SecurityFilterChain
import java.time.Duration

fun leantelAccessTokenDecoder(issuer: String, audience: String): JwtDecoder {
    val decoder = NimbusJwtDecoder.withJwkSetUri("$issuer/.well-known/jwks.json")
        .jwsAlgorithm(SignatureAlgorithm.RS256)
        .validateType(false)
        .build()
    decoder.setJwtValidator(
        DelegatingOAuth2TokenValidator(
            JwtTimestampValidator(Duration.ofSeconds(60)),
            JwtIssuerValidator(issuer),
            JwtTypeValidator(listOf("at+jwt")),
            JwtClaimValidator<List<String>>("aud") { it?.contains(audience) == true },
            required("exp"), required("iat"), required("sub"), required("jti"), required("client_id"), required("tenant_id"),
        ),
    )
    return decoder
}

private fun required(claim: String) = JwtClaimValidator<Any>(claim) { it != null && it.toString().isNotBlank() }

@Configuration
class SecurityConfig(
    @Value("\${leantel.issuer}") private val issuer: String,
    @Value("\${leantel.audience}") private val audience: String,
    @Value("\${leantel.post-logout-uri}") private val postLogoutUri: String,
) {
    @Bean
    fun jwtDecoder(): JwtDecoder = leantelAccessTokenDecoder(issuer, audience)

    @Bean
    @Order(1)
    fun apiSecurity(http: HttpSecurity): SecurityFilterChain {
        http.securityMatcher("/api/**")
            .authorizeHttpRequests { it.anyRequest().authenticated() }
            .oauth2ResourceServer { it.jwt { } }
            .sessionManagement { it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) }
            .csrf { it.disable() }
        return http.build()
    }

    @Bean
    @Order(2)
    fun webSecurity(http: HttpSecurity, registrations: ClientRegistrationRepository): SecurityFilterChain {
        val resolver = DefaultOAuth2AuthorizationRequestResolver(registrations, "/oauth2/authorization")
        resolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce())
        val logoutHandler = OidcClientInitiatedLogoutSuccessHandler(registrations)
        logoutHandler.setPostLogoutRedirectUri(postLogoutUri)
        http.authorizeHttpRequests { it.requestMatchers("/", "/webhooks/leantel").permitAll().anyRequest().authenticated() }
            .oauth2Login { it.authorizationEndpoint { endpoint -> endpoint.authorizationRequestResolver(resolver) } }
            .logout { it.logoutSuccessHandler(logoutHandler) }
            .csrf { it.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.kt
package com.example.northwind

import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
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
import org.springframework.web.client.body

@SpringBootApplication
class Application

fun main(args: Array<String>) {
    runApplication<Application>(*args)
}

@RestController
class MeController {
    @GetMapping("/api/me")
    fun apiMe(@AuthenticationPrincipal token: Jwt): Map<String, String?> =
        mapOf("tenantId" to token.getClaimAsString("tenant_id"), "userId" to token.subject)

    @GetMapping("/me")
    fun me(@AuthenticationPrincipal user: OidcUser): Map<String, String?> =
        mapOf("userId" to user.subject, "tenantId" to user.getClaimAsString("tenant_id"), "email" to user.email)
}

@RestController
class HomeController(clients: OAuth2AuthorizedClientManager, @Value("\${app.api-url}") apiUrl: String) {
    private val api = RestClient.builder()
        .baseUrl(apiUrl)
        .requestInterceptor(OAuth2ClientHttpRequestInterceptor(clients).apply { setClientRegistrationIdResolver { "leantel" } })
        .build()

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

3. Receive webhooks

LeantelWebhookController.kt
package com.example.northwind

import tools.jackson.databind.JsonNode
import tools.jackson.databind.ObjectMapper
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 java.security.MessageDigest
import java.time.Instant
import java.util.HexFormat
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.math.abs

fun isValidLeantelSignature(header: String, body: ByteArray, secret: String, now: Instant = Instant.now()): Boolean {
    val parts = header.split(",").associate { it.substringBefore("=") to it.substringAfter("=", "") }
    val timestamp = parts["t"]?.toLongOrNull() ?: return false
    if (abs(now.epochSecond - timestamp) > 300) return false
    val mac = Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec(secret.toByteArray(), "HmacSHA256")) }
    mac.update("$timestamp.".toByteArray())
    val expected = HexFormat.of().formatHex(mac.doFinal(body))
    return MessageDigest.isEqual(expected.toByteArray(), (parts["v1"] ?: "").toByteArray())
}

@RestController
class LeantelWebhookController(
    @Value("\${leantel.webhook-secret}") private val secret: String,
    private val objectMapper: ObjectMapper,
) {
    private val handledEventIds = java.util.concurrent.ConcurrentHashMap.newKeySet<String>()

    @PostMapping("/webhooks/leantel")
    fun receive(@RequestHeader("Auth-Signature") signature: String, @RequestBody body: ByteArray): ResponseEntity<Void> {
        if (!isValidLeantelSignature(signature, body, secret)) return ResponseEntity.status(401).build()
        val event: JsonNode = objectMapper.readTree(body)
        if (handledEventIds.add(event["id"].asString())) {
            println("leantel event ${event["type"].asString()} ${event["id"].asString()}")
        }
        return ResponseEntity.ok().build()
    }
}

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.