[Spring boot] Common library

brandon·2025년 5월 27일

spring-boot

목록 보기
7/15

In this post, I will try to make a common library for JWT authentications.

Step 1. Dependencies

build.gradle:

// jwt-security-starter/build.gradle
plugins {
    id 'java'
    id 'org.springframework.boot' version '3.2.5' // Use your desired Spring Boot version
    id 'io.spring.dependency-management' version '1.1.4'
}

group = 'com.yourcompany.common' // This matches your Group ID
version = '0.0.1-SNAPSHOT' // IMPORTANT: Use proper versioning
java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17) // Or your desired Java version
    }
}

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

ext {
    set('jjwtVersion', '0.12.5') // Check for the latest JJWT version
}

dependencies {
    // Spring Boot Starters
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'

    // Lombok (optional, but highly recommended)
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'

    // JJWT (Java JWT) dependencies
    implementation "io.jsonwebtoken:jjwt-api:${jjwtVersion}"
    runtimeOnly "io.jsonwebtoken:jjwt-impl:${jjwtVersion}"
    runtimeOnly "io.jsonwebtoken:jjwt-jackson:${jjwtVersion}" // For parsing/serializing JSON payload

    // Test dependencies
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.security:spring-security-test'
}

// This is crucial for a library project:
// Remove the spring-boot-gradle-plugin 'bootJar' task if you want *only* a plain JAR, not an executable fat JAR.
// For a library, you typically want a plain JAR.
// If you want to keep the bootJar for local testing/example, but skip it during normal build for library use,
// you can comment out 'bootJar' or use configuration to skip.
// A simpler way is to just ensure 'jar' task runs.
jar {
    enabled = true // Ensure the standard JAR is built
}

// If you have the Spring Boot plugin, it will create 'bootJar' by default.
// To prevent it from creating an executable JAR for a library, you can disable it:
bootJar {
    enabled = false
}

// You can also add this to ensure the standard jar is produced when you 'build'
tasks.named('build') {
    dependsOn 'jar'
}

Step 2. Implement JWT Service logic

NEVER hardcode your secret key. Use environment variables or a secrets management solution (e.g., HashiCorp Vault, AWS Secrets Manager, Kubernetes Secrets) in production.

The secret-key value must be Base64 encoded and sufficiently long (at least 256 bits for HS256, so 32 characters Base64 encoded). You can generate one with
java.util.Base64.Encoder encoder = java.util.Base64.getEncoder(); System.out.println(encoder.encodeToString(new byte[32]));

profile
everything happens for a reason

0개의 댓글