Spring › Wanted-Challenge

Designing account and token endpoints in Spring Boot

Build Kotlin registration and account endpoints with Hibernate soft deletes, Jakarta Validation, and Redis-backed refresh token rotation.

Designing account and token endpoints in Spring Boot

The account API had to preserve old posts and comments after an account closed while allowing the same email to register again. I paired Hibernate soft deletes with separate query and command services, and used Redis-backed refresh token rotation for sessions.

The examples use Kotlin 1.9, Spring Boot 3.5, Java 21, Hibernate 6, and Spring Data Redis.

Keeping account history after deletion

User inherits BaseTimeEntity, which fills createdAt and updatedAt through JPA auditing. Hibernate 6.4’s @SoftDelete(columnName = "is_deleted") turns deletion into an update and excludes deleted rows from ordinary entity queries. The record remains available to database foreign keys from existing posts and comments.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// src/main/kotlin/org/project/portfolio/user/domain/User.kt
@Entity
@Table(name = "users")
@SoftDelete(columnName = "is_deleted")
class User(
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long = 0L,
    @Column(unique = true)
    var email: String,
    var name: String,
    var phone: String,
    var profileImage: String? = null,
    var password: String,
    @ElementCollection(fetch = FetchType.LAZY)
    @Enumerated(EnumType.STRING)
    var roles: MutableSet<UserRole> = mutableSetOf(UserRole.USER),
) : BaseTimeEntity() {
    companion object {
        fun create(email: String, name: String, phone: String, password: String): User {
            return User(
                email = email,
                name = name,
                phone = phone,
                password = password,
                profileImage = "https://i.pravatar.cc/300?img=${(1..70).random()}",
            )
        }
    }

    fun addRole(role: UserRole) {
        roles.add(role)
    }

    fun changePassword(encodedPassword: String) {
        this.password = encodedPassword
    }
}

Roles use FetchType.LAZY. Login, refresh, and the account details response need the collection. A public profile can leave it unloaded. With open-in-view: false, I convert entities into DTOs inside the service transaction so the controller does not read roles from a detached entity or issue extra queries during serialization.

Validating Kotlin request properties

For a primary-constructor property, @field: places a Jakarta Validation annotation on the backing field. Without an explicit target, Kotlin 1.9 can put an annotation that’s valid on both a parameter and a field on the constructor parameter. Normal bean validation of the already-constructed request body may then miss it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// src/main/kotlin/org/project/portfolio/auth/presentation/request/RegisterForm.kt
@Schema(description = "Registration form")
data class RegisterForm(
    @field:Schema(description = "Email", example = "test12345@test.com")
    @field:Size(max = 254, message = "Email must be at most 254 characters.")
    @field:Pattern(
        regexp = "^[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$",
        message = "Enter a valid email address.",
    )
    val email: String,
    @field:Pattern(
        regexp = "^01(?:0|1|[6-9])-(?:\\d{3}|\\d{4})-\\d{4}\$",
        message = "Enter a valid phone number.",
    )
    @field:Schema(description = "Phone number", example = "010-1234-5678")
    @field:NotNull(message = "Enter your phone number.")
    val phone: String,
    @field:Schema(description = "Name", example = "JaneDoe")
    @field:NotBlank(message = "Enter your name.")
    @field:Pattern(
        regexp = "^[\uAC00-\uD7A3a-zA-Z]{2,10}\$",
        message = "Use Korean or English letters in the name.",
    )
    val name: String,
    @field:Schema(description = "Password", example = "Password1234~!")
    @field:NotBlank(message = "Enter your password.")
    @field:Size(min = 8, max = 72, message = "Password must be 8 to 72 characters.")
    @field:Pattern(
        regexp = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^\\da-zA-Z]).{5,}\$",
        message = "Use at least five characters with uppercase and lowercase letters, a number, and a symbol.",
    )
    val password: String,
)

The request model checks the email format and limits it to 254 characters. A phone-number pattern verifies format. The name rule accepts Korean or English letters and enforces a length of two to ten characters. Password changes use the same field targets and require both the current and the new password.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/main/kotlin/org/project/portfolio/user/presentation/request/PasswordChangeRequest.kt
@Schema(description = "Password change request")
data class PasswordChangeRequest(
    @field:Schema(description = "Current password", example = "Password1234~!")
    @field:NotBlank(message = "Enter your current password.")
    val currentPassword: String,
    @field:Schema(description = "New password", example = "NewPassword1234~!")
    @field:NotBlank(message = "Enter your new password.")
    @field:Size(min = 8, max = 72, message = "Password must be 8 to 72 characters.")
    @field:Pattern(
        regexp = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^\\da-zA-Z]).{5,}\$",
        message = "Use at least five characters with uppercase and lowercase letters, a number, and a symbol.",
    )
    val newPassword: String,
)

The schema’s 72-character upper bound is intended to match BCrypt’s 72-byte limit. A Bean Validation character count does not ensure a UTF-8 byte limit. The password policy needs a byte-length check before BCrypt if the API accepts multibyte passwords. The composition pattern has its own minimum, but the size constraint controls the effective minimum of eight characters.

Refresh token rotation and endpoint behavior

OperationEndpointSuccessExpected failure
RegisterPOST /api/v1/auth/register201 Created with UserSummaryResponse409 Conflict
Check emailPOST /api/v1/auth/register/email200 OK with EmailCheckResponse409 Conflict
Log inPOST /api/v1/auth/login200 OK with TokenResponse400 Bad Request
Rotate refresh tokenPOST /api/v1/auth/refresh200 OK with TokenResponse401 Unauthorized
Log outPOST /api/v1/auth/logout204 No Content401 Unauthorized

Registration returns a Location header pointing to /api/v1/users/{id}. Login gives the same failure message for an unknown email and an incorrect password, so its response does not disclose which condition failed. The email-check endpoint intentionally reports availability and needs its own abuse controls.

Login generates a UUID for the refresh token and saves it in Redis for seven days. The code uses the field name jit for the identifier that is serialized as the JWT jti claim. Refresh decodes the Refresh-Token header, checks that the identifier still exists, deletes that identifier, and issues a replacement. Logout deletes the identifier without replacing it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// src/main/kotlin/org/project/portfolio/auth/application/AuthService.kt
@Service
class AuthService(
    private val userRepository: UserRepository,
    private val refreshTokenRepository: RefreshTokenRedisRepository,
    private val jwtProvider: JwtProvider,
    private val passwordEncoder: PasswordEncoder,
) {
    @Transactional
    fun login(email: String, password: String): TokenResponse {
        val user: User = userRepository.findByEmail(email)
            ?: throw BadRequestException(message = "The email or password is incorrect.")
        if (!passwordEncoder.matches(password, user.password)) {
            throw BadRequestException(message = "The email or password is incorrect.")
        }

        val refreshToken: String = UUID.randomUUID().toString()
        refreshTokenRepository.save(RefreshToken(jit = refreshToken, email = user.email))

        return TokenResponse(
            accessToken = jwtProvider.createAccessToken(email = user.email, roles = user.roles),
            refreshToken = jwtProvider.createRefreshToken(email = user.email, jit = refreshToken),
        )
    }

    @Transactional
    fun reissueAccessToken(token: String): TokenResponse {
        val refreshToken: RefreshToken = jwtProvider.decodeRefreshToken(token)
        if (!refreshTokenRepository.existsById(refreshToken.jit)) {
            throw UnauthorizedException("The refresh token is unavailable.")
        }

        val user: User = userRepository.findByEmail(refreshToken.email)
            ?: throw UnauthorizedException("The account does not exist.")

        refreshTokenRepository.deleteById(refreshToken.jit)

        val newRefreshToken: String = UUID.randomUUID().toString()
        refreshTokenRepository.save(RefreshToken(jit = newRefreshToken, email = user.email))

        return TokenResponse(
            accessToken = jwtProvider.createAccessToken(email = user.email, roles = user.roles),
            refreshToken = jwtProvider.createRefreshToken(email = user.email, jit = newRefreshToken),
        )
    }

    @Transactional
    fun logout(token: String) {
        val refreshToken: RefreshToken = jwtProvider.decodeRefreshToken(token)
        refreshTokenRepository.deleteById(refreshToken.jit)
    }
}

Two refreshes can both pass a separate existence check before either deletes the key. If parallel requests from one session are possible, consume the record with an atomic operation and make issuance conditional on success. A failure after consuming the old identifier can require the client to log in again. The Resource Server configuration covers distinct access and refresh decoders.

Separating private account data from public profiles

UserQueryService runs under @Transactional(readOnly = true). UserCommandService owns changes to the account. This isolates the query policy today and keeps a future read-replica decision in the service layer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// src/main/kotlin/org/project/portfolio/user/application/UserQueryService.kt
@Service
@Transactional(readOnly = true)
class UserQueryService(
    private val userRepository: UserRepository,
) {
    fun getUser(email: String): User {
        return userRepository.findByEmail(email)
            ?: throw NotFoundException(User::class.java, mapOf("email" to email))
    }

    fun getUser(userId: Long): User {
        return userRepository.findByIdOrNull(userId)
            ?: throw NotFoundException(User::class.java, mapOf("userId" to userId))
    }
}
AudienceEndpointDTOFields
Account ownerGET /api/v1/userUserResponseid, email, name, phone, profileImage, roles, createdAt, updatedAt
Public profileGET /api/v1/users/{userId}UserPublicResponseid, email, name, profileImage, createdAt

The account endpoint reads its subject from @AuthenticationPrincipal jwt: Jwt. The public response omits the phone number, roles, and modification timestamp. Because this example includes email in the public DTO, verify that the field matches the product’s privacy requirements.

1
2
3
4
5
6
7
8
9
10
11
// src/main/kotlin/org/project/portfolio/user/presentation/UserController.kt
@GetMapping("/user")
@PreAuthorize("isAuthenticated()")
fun getUserInfo(@AuthenticationPrincipal jwt: Jwt): ResponseEntity<UserResponse> {
    return ResponseEntity.ok(UserResponse.from(userQueryService.getUser(email = jwt.subject)))
}

@GetMapping("/users/{userId}")
fun getUserPublicProfile(@PathVariable userId: Long): ResponseEntity<UserPublicResponse> {
    return ResponseEntity.ok(UserPublicResponse.from(userQueryService.getUser(userId = userId)))
}

Releasing an email address on account closure

Soft-deleted rows still occupy a regular UNIQUE index slot. Before deletion, UserCommandService.deleteUser() appends .deleted.<timestamp> to the archived email. That frees the original address without relying on a PostgreSQL-specific partial index in tests that run on H2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// src/main/kotlin/org/project/portfolio/user/application/UserCommandService.kt
@Service
@Transactional
class UserCommandService(
    private val userRepository: UserRepository,
    private val passwordEncoder: PasswordEncoder,
) {
    fun changePassword(email: String, currentPassword: String, newPassword: String) {
        val user: User = userRepository.findByEmail(email)
            ?: throw NotFoundException(User::class.java, mapOf("email" to email))
        if (!passwordEncoder.matches(currentPassword, user.password)) {
            throw BadRequestException("The current password does not match.")
        }
        user.changePassword(passwordEncoder.encode(newPassword))
    }

    fun deleteUser(email: String) {
        val user: User = userRepository.findByEmail(email)
            ?: throw NotFoundException(User::class.java, mapOf("email" to email))

        user.email = "${user.email}.deleted.${System.currentTimeMillis()}"
        userRepository.delete(user)
    }
}

Allow room for the deletion suffix when sizing the column. A 320-character column leaves headroom above a 254-character address. Closing an account also needs to revoke its outstanding refresh sessions. If existing access tokens must stop working before expiry, an application-level revocation check is needed.

  • Compare the login response for unknown emails and incorrect passwords.
  • Use a refresh token twice and check that the second request fails. Repeat the test with concurrent requests before claiming single-use behavior.
  • Close an account at the email length limit, then register the same address again and verify the old posts still resolve.
  • Check the public response for private fields and verify that a detached role collection is never serialized.
원티드 8월 프리온보딩 백엔드 챌린지 (게시글 CRUD). Contribute to cmsong111/Wanted-PreOnBoarding-Backend-Challenge development by creating an account on GitHub.
This post is licensed under CC BY 4.0 by the author.