<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Spring Security Archives - Codersee blog- Kotlin on the backend</title>
	<atom:link href="https://blog.codersee.com/tag/spring-security/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>Kotlin &#38; Backend Tutorials - Learn Through Practice.</description>
	<lastBuildDate>Wed, 16 Apr 2025 04:49:51 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://blog.codersee.com/wp-content/uploads/2025/04/cropped-codersee_logo_circle_2-32x32.png</url>
	<title>Spring Security Archives - Codersee blog- Kotlin on the backend</title>
	<link></link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Spring Boot 3 (Spring Security 6) with Kotlin &#038; JWT</title>
		<link>https://blog.codersee.com/spring-boot-3-spring-security-6-with-kotlin-jwt/</link>
					<comments>https://blog.codersee.com/spring-boot-3-spring-security-6-with-kotlin-jwt/#comments</comments>
		
		<dc:creator><![CDATA[Piotr]]></dc:creator>
		<pubDate>Thu, 26 Oct 2023 05:30:09 +0000</pubDate>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[Access Tokens]]></category>
		<category><![CDATA[Authentication]]></category>
		<category><![CDATA[Authorization]]></category>
		<category><![CDATA[JSON Web Tokens]]></category>
		<category><![CDATA[Refresh Tokens]]></category>
		<category><![CDATA[Spring Boot 3]]></category>
		<category><![CDATA[Spring Security]]></category>
		<guid isPermaLink="false">https://codersee.com/?p=9008217</guid>

					<description><![CDATA[<p>In this article, I will show you how to implement a secure REST API with Spring Boot 3, Spring Security, Kotlin, and JWT tokens.</p>
<p>The post <a href="https://blog.codersee.com/spring-boot-3-spring-security-6-with-kotlin-jwt/">Spring Boot 3 (Spring Security 6) with Kotlin &#038; JWT</a> appeared first on <a href="https://blog.codersee.com">Codersee blog- Kotlin on the backend</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>If you would like to learn how to secure a REST API with <strong>Spring Boot 3</strong> (<strong>Spring Security 6</strong>), <strong>Kotlin</strong>, and <strong>JWT tokens</strong>, then you came to the right place 😉 </p>



<p>In this, comprehensive guide I will show you step-by-step how to:</p>



<ul class="wp-block-list">
<li>authenticate and authorize users, </li>



<li>assign and verify roles, </li>



<li>generate JWT tokens,</li>



<li>and implement a refresh token flow.</li>
</ul>



<p>And everything that with our beloved Kotlin programming language! </p>



<h2 class="wp-block-heading" id="h-video-tutorial">Video Tutorial</h2>



<p>If you prefer <strong>video content</strong>, then you can find this tutorial as a YouTube playlist <a href="https://www.youtube.com/playlist?list=PLvN8k8yxjoeud4ESoB-wjiieqYGaDVqPR" target="_blank" rel="noreferrer noopener">right here</a>. </p>



<p>Alternatively, you can start from the introduction:</p>



<div style="text-align: center; width: 90%; margin-left: 5%;">
<a href="https://blog.codersee.com/spring-boot-3-spring-security-6-with-kotlin-jwt/"><img decoding="async" src="https://blog.codersee.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=%2F%2Fi.ytimg.com%2Fvi%2FPCIkfv6cC0k%2Fhqdefault.jpg" alt="YouTube Video"></a><br /><br /></p></div>



<p>If you find this content useful,<strong> please leave a subscription&nbsp;</strong> 😉</p>



<h2 class="wp-block-heading" id="h-what-exactly-will-we-implement">What Exactly Will We Implement? </h2>



<div style="height:35px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="wp-block-image aligncenter size-large is-resized"><img fetchpriority="high" decoding="async" width="1024" height="665" src="http://blog.codersee.com/wp-content/uploads/2023/11/articles_users_auth_api-1024x665.png" alt="Image shows sticky notes presenting what exactly will be implemented in this tutorial. " class="wp-image-9008335" style="aspect-ratio:1.5398496240601505;width:805px;height:auto" srcset="https://blog.codersee.com/wp-content/uploads/2023/11/articles_users_auth_api-1024x665.png 1024w, https://blog.codersee.com/wp-content/uploads/2023/11/articles_users_auth_api-300x195.png 300w, https://blog.codersee.com/wp-content/uploads/2023/11/articles_users_auth_api-768x499.png 768w, https://blog.codersee.com/wp-content/uploads/2023/11/articles_users_auth_api.png 1287w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p></p>



<div style="height:35px" aria-hidden="true" class="wp-block-spacer"></div>



<p>Well, in our project we will implement a REST API for <strong>articles</strong> and <strong>users</strong>. </p>



<p><strong>Articles</strong> will be visible to any user who successfully authenticates using the JWT access token. </p>



<p><strong>Users </strong>endpoint, on the other hand, will be accessible <strong>only for admin users</strong> in our system (with one exception- a public endpoint for creating new users). </p>



<p>Of course, we will expose additional authentication endpoints, which will take data from users, like <code>email</code> and <code>password</code> and generate access and refresh tokens for our system. </p>



<p>Long story short- I believe this project will be simple enough to easily understand the topic, and comprehensive enough to cover the most popular real-life cases. </p>



<h2 class="wp-block-heading" id="h-a-tiny-bit-of-theory">A Tiny Bit Of Theory</h2>



<p>In this paragraph, I&#8217;d like to cover what exactly JWT tokens are, the difference between authorization and authentication, and present from a bird&#8217;s eye view how Spring Security works. </p>



<p>So, if you feel that you understand these and came here for the practice, then please skip to the next chapter 😉 </p>



<h3 class="wp-block-heading" id="h-authentication-vs-authorization">Authentication vs Authorization </h3>



<p>I am pretty sure that you heard both terms plenty of times already and even heard people using them alternately. </p>



<p>Nevertheless, although similar, these two terms refer to completely different things. </p>



<p>Imagine you&#8217;re at the entrance of a super-secret club:</p>



<p><strong>Authentication</strong> is like showing your ID to prove you are who you say you are. It&#8217;s the process of confirming your identity. So, in our club scenario, it&#8217;s like showing your driver&#8217;s license to the bouncer.</p>



<p><strong>Authorization</strong>, on the other hand, is like being allowed into different parts of the club based on your VIP status. Once you&#8217;re inside (thanks to authentication), authorization decides what you can and cannot do. For example, VIP members might access the VIP lounge, while regular guests can&#8217;t.</p>



<h3 class="wp-block-heading" id="h-jwt-tokens">JWT Tokens </h3>



<p>Among plenty of existing ways to authenticate users, JWTs (JSON Web Tokens) are one of the most popular ones. </p>



<p>They are like a digital secret handshake on the internet. When we log into a website, the server gives us a special JWT. This token is like a digital badge that says, &#8220;Hey, this person is legit!&#8221; </p>



<p>Why are they so cool? Well, they are <strong>safe, compact, </strong>and allow us to <strong>hold information</strong>. </p>



<p>JWTs consist of three parts separated by dots: header.payload.signature: </p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="534" src="http://blog.codersee.com/wp-content/uploads/2023/10/spring_boot_3_security_jwt_io-1024x534.png" alt="The image is a screenshot from jwt.io page and present and example encoded JWT token with its decoded value." class="wp-image-9008239" srcset="https://blog.codersee.com/wp-content/uploads/2023/10/spring_boot_3_security_jwt_io-1024x534.png 1024w, https://blog.codersee.com/wp-content/uploads/2023/10/spring_boot_3_security_jwt_io-300x156.png 300w, https://blog.codersee.com/wp-content/uploads/2023/10/spring_boot_3_security_jwt_io-768x400.png 768w, https://blog.codersee.com/wp-content/uploads/2023/10/spring_boot_3_security_jwt_io.png 1191w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>As we can see, the encoded value can be easily decoded and JWT token values can be read. </p>



<p>The <strong>header </strong>typically consists of two parts: the type of the token (missing above), and the signing algorithm being used (HMAC SHA512).</p>



<p>The second part of the token is the payload, which contains the <strong>claims</strong>. Claims, Claims are statements about an entity (typically, the user) and additional data.</p>



<p>Lastly, the <strong>signature</strong> is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn&#8217;t changed along the way.</p>



<h3 class="wp-block-heading" id="h-bird-s-eye-view-on-spring-security">Bird&#8217;s Eye View on Spring Security</h3>



<p>At this point, we know the difference between authentication and authorization and also what JWT tokens are. Awesome! </p>



<p>So, now I&#8217;ll try to do the impossible- explain how Spring Security works in a few sentences 🙂 </p>



<p><strong>Spring Security</strong> is like the security team of a building. It manages authentication and authorization for our app with:</p>



<ol class="wp-block-list">
<li><strong>Filters</strong>&#8211; think of security filters as checkpoints at different doors in the building. When a request comes in, it goes through these filters. These filters handle tasks like authentication and authorization. For instance, there might be a filter that checks if you have a proper access card (authentication), and another that ensures you can enter specific rooms (authorization).</li>



<li><strong>Authentication</strong>&#8211; when you log in, Spring Security checks your credentials (like username and password). If they match, you&#8217;re authenticated. Spring Security uses authentication providers, which can be a database, LDAP, or any other source, to verify your identity.</li>



<li><strong>Security Context</strong>&#8211; once authenticated, your security details are stored in the Security Context. It&#8217;s like being given a special pass after passing through the checkpoint. This pass (security context) contains your roles and permissions.</li>



<li><strong>Authorization</strong>&#8211; now, when you try to access a specific part of the application, Spring Security checks your roles and permissions stored in the security context. If you&#8217;re authorized (based on your roles), you&#8217;re allowed in. Otherwise, you might be denied access.</li>



<li><strong>Customization</strong>&#8211; Spring Security allows you to customize the security filters, authentication providers, and access rules according to your application&#8217;s requirements. You can configure which URLs need authentication, what roles are required, etc.</li>
</ol>



<p> And that&#8217;s <strong>basically what we&#8217;re gonna learn today</strong>.</p>



<h2 class="wp-block-heading" id="h-import-spring-boot-3-project">Import Spring Boot 3 Project</h2>



<p>As the first step, let&#8217;s generate a new Spring Boot 3 project. </p>



<p>To do so, we can use the <a href="https://start.spring.io/" target="_blank" rel="noreferrer noopener">Spring Initializr</a> page:</p>



<div style="height:35px" aria-hidden="true" class="wp-block-spacer"></div>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="509" src="http://blog.codersee.com/wp-content/uploads/2023/10/spring_boot_3_security_jwt_1-1024x509.png" alt="Image is a screenshot from Spring Initializr page and shows a minimum project configuration." class="wp-image-9008218" srcset="https://blog.codersee.com/wp-content/uploads/2023/10/spring_boot_3_security_jwt_1-1024x509.png 1024w, https://blog.codersee.com/wp-content/uploads/2023/10/spring_boot_3_security_jwt_1-300x149.png 300w, https://blog.codersee.com/wp-content/uploads/2023/10/spring_boot_3_security_jwt_1-768x382.png 768w, https://blog.codersee.com/wp-content/uploads/2023/10/spring_boot_3_security_jwt_1.png 1502w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<div style="height:35px" aria-hidden="true" class="wp-block-spacer"></div>



<p>As we can see, in this project, we will use <em>Spring Boot 3.1.5</em>, <em>Kotlin</em> as a programming language, and <em>Kotlin DSL</em> for our Gradle build config. </p>



<p>At this point, the only dependency required to expose a REST API is <em>Spring Web</em>. We will add Spring Security, and libraries necessary for JWT tokens later (and we will see why later, too). </p>



<p>With all of that done, we can hit the <strong>generate</strong> button, download the zip file, and import it to IntelliJ. </p>



<h2 class="wp-block-heading" id="h-expose-articles-api">Expose Articles API </h2>



<p>Following, let&#8217;s implement the logic necessary to expose our first endpoint- <code>GET /api/article</code> .</p>



<p>In the future, this endpoint will be accessible only to users with a valid JWT token. </p>



<h3 class="wp-block-heading" id="h-create-article-model">Create Article Model</h3>



<p>As the first step, let&#8217;s introduce a new package- <code>model</code> &#8211; and create a new data class- <code>Article</code>: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import java.util.*

data class Article(
  val id: UUID,
  val title: String,
  val content: String,
)</pre>



<p>This class consists of three example fields simulating a real-life article. </p>



<h3 class="wp-block-heading" id="h-implement-article-repository">Implement Article Repository</h3>



<p>Secondly, we must introduce a new class responsible for article retrieval and storage. </p>



<p>Let&#8217;s add the <code>repository</code> package and implement <code>ArticleRepository</code>: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import com.codersee.jwtauth.model.Article
import org.springframework.stereotype.Repository
import java.util.UUID

@Repository
class ArticleRepository {

  private val articles = listOf(
    Article(id = UUID.randomUUID(), title= "Article 1", content= "Content 1"),
    Article(id = UUID.randomUUID(), title= "Article 2", content= "Content 2"),
  )

  fun findAll(): List&lt;Article> =
    articles

}</pre>



<p>In our example, articles are nothing else, than a hardcoded private list of items. </p>



<p>Additionally, we expose the <code>findAll()</code> method, which encapsulates the list and which we will be invoking from outside the class. </p>



<p>Of course, I did it this way to keep it simple and so that we do not lose focus on what matters in this tutorial- Spring Boot security with Kotlin and JWT tokens. </p>



<p>Nevertheless, you can easily adjust this project to your needs. In real life, this would be the class where you can put logic responsible for communication with your database. </p>



<h3 class="wp-block-heading" id="h-create-service">Create Service</h3>



<p>As the next step, let&#8217;s create the <code>service</code> package and introduce the <code>ArticleService</code>: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import com.codersee.jwtauth.model.Article
import com.codersee.jwtauth.repository.ArticleRepository
import org.springframework.stereotype.Service

@Service
class ArticleService(
  private val articleRepository: ArticleRepository
) {

  fun findAll(): List&lt;Article> =
    articleRepository.findAll()
}</pre>



<p>As we can see, this class exposes the <code>findAll()</code> function and does nothing else than invoking the <code>findAll()</code> method from our repository. </p>



<p>Again, this might look a bit like an <strong>overengineering</strong>. But trust me, keeping a well-organized project from the very beginning will pay off in the future. </p>



<h3 class="wp-block-heading" id="h-expose-article-rest-api">Expose Article REST API </h3>



<p>Lastly, let&#8217;s add the <code>controller.article</code> package and put two classes in it. </p>



<p>Let&#8217;s start with the <code>ArticleResponse</code>: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import java.util.*

data class ArticleResponse(
  val id: UUID,
  val title: String,
  val content: String,
)</pre>



<p>Before returning any article from our REST API, we will map model objects into the response objects. </p>



<p>And with that done, let&#8217;s implement the <code>ArticleController</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import com.codersee.jwtauth.model.Article
import com.codersee.jwtauth.service.ArticleService
import org.springframework.web.bind.annotation.*
import java.util.*

@RestController
@RequestMapping("/api/article")
class ArticleController(
  private val articleService: ArticleService
) {

  @GetMapping
  fun listAll(): List&lt;ArticleResponse> =
    articleService.findAll()
      .map { it.toResponse() }

  private fun Article.toResponse(): ArticleResponse =
    ArticleResponse(
      id = this.id,
      title = this.title,
      content = this.content,
    )
}</pre>



<p>As we can see, we must annotate our controller class with the <em>@RestController </em>annotation in order to expose a REST API in Spring Boot. </p>



<p>Additionally, we add the <code>@RequestMapping</code> annotation so that whenever we hit the <code>/api/article</code> endpoint, Spring knows that this is the class it should use to handle the request. </p>



<p>Lastly, we mark the <code>listAll()</code> function with <code>@GetMapping</code>, and convert all found <em>Article</em> instances to the <em>ArticleResponse.</em> </p>



<p>Later, when we add the JWT security to our Spring Boot Kotlin project, these endpoints will be accessible only for <code>ADMIN</code> users with one exception- the endpoint responsible for creating new users- which will be publicly exposed.   </p>



<h3 class="wp-block-heading" id="h-add-user-model">Add User Model</h3>



<p>With that said, let&#8217;s add the <code>User.kt</code> file to the <code>model</code> package:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import java.util.*

data class User(
  val id: UUID,
  val email: String,
  val password: String,
  val role: Role
)

enum class Role {
  USER, ADMIN
}</pre>



<p>As we can see, apart from the <code>id</code>, the User class contains three important fields: <code>email</code>, <code>password</code>, and <code>role</code>, which we will extensively when dealing with JWT tokens. </p>



<h3 class="wp-block-heading" id="h-implement-userrepository">Implement UserRepository</h3>



<p>Following, let&#8217;s create the <code>UserRepository</code> in the <code>repository</code> package:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import com.codersee.jwtauth.model.Role
import com.codersee.jwtauth.model.User
import org.springframework.stereotype.Repository
import java.util.*

@Repository
class UserRepository {

  private val users = mutableSetOf(
    User(
      id = UUID.randomUUID(),
      email = "email-1@gmail.com",
      password = "pass1",
      role = Role.USER,
    ),
    User(
      id = UUID.randomUUID(),
      email = "email-2@gmail.com",
      password = "pass2",
      role = Role.ADMIN,
    ),
    User(
      id = UUID.randomUUID(),
      email = "email-3@gmail.com",
      password = "pass3",
      role = Role.USER,
    ),
  )

  fun save(user: User): Boolean =
    users.add(user)

  fun findByEmail(email: String): User? =
    users
      .firstOrNull { it.email == email }

  fun findAll(): Set&lt;User> =
    users

  fun findByUUID(uuid: UUID): User? =
    users
      .firstOrNull { it.id == uuid }

  fun deleteByUUID(uuid: UUID): Boolean {
    val foundUser = findByUUID(uuid)

    return foundUser?.let {
      users.removeIf {
        it.id == uuid
      }
    } ?: false
  }
}</pre>



<p>Similarly to our previous repository- we simply introduce a mutable list, which we can edit with a bunch of util methods. </p>



<p>And don&#8217;t worry about the password stored in plain text- we will get back to that topic, too 🙂 </p>



<h3 class="wp-block-heading" id="h-add-userservice">Add UserService</h3>



<p>Nextly, we must go to the <code>service</code> package and introduce this <code>UserService</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import com.codersee.jwtauth.model.User
import com.codersee.jwtauth.repository.UserRepository
import org.springframework.stereotype.Service
import java.util.*

@Service
class UserService(
  private val userRepository: UserRepository
) {

  fun createUser(user: User): User? {
    val found = userRepository.findByEmail(user.email)

    return if (found == null) {
      userRepository.save(user)
      user
    } else null
  }

  fun findByUUID(uuid: UUID): User? =
    userRepository.findByUUID(uuid)

  fun findAll(): List&lt;User> =
    userRepository.findAll()
      .toList()

  fun deleteByUUID(uuid: UUID): Boolean =
    userRepository.deleteByUUID(uuid)
}</pre>



<p>Nothing spectacular here, so let&#8217;s move to the next step. </p>



<h3 class="wp-block-heading" id="h-expose-user-rest-api">Expose User REST API </h3>



<p>Just like with articles, let&#8217;s start with introducing request/response objects. </p>



<p>This time, we will need both the <code>UserRequest</code>: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data class UserRequest(
  val email: String,
  val password: String,
)</pre>



<p>And the <code>UserResponse</code>, which will be serialized into JSON objects:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import java.util.*

data class UserResponse(
  val uuid: UUID,
  val email: String,
)</pre>



<p>And with that done, we can add the <code>UserController</code> class:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import com.codersee.jwtauth.model.Role
import com.codersee.jwtauth.model.User
import com.codersee.jwtauth.service.UserService
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.server.ResponseStatusException
import java.util.*

@RestController
@RequestMapping("/api/user")
class UserController(
  private val userService: UserService
) {

  @PostMapping
  fun create(@RequestBody userRequest: UserRequest): UserResponse =
    userService.createUser(userRequest.toModel())
      ?.toResponse()
      ?: throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Cannot create user.")

  @GetMapping
  fun listAll(): List&lt;UserResponse> =
    userService.findAll()
      .map { it.toResponse() }

  @GetMapping("/{uuid}")
  fun findByUUID(@PathVariable uuid: UUID): UserResponse =
    userService.findByUUID(uuid)
      ?.toResponse()
      ?: throw ResponseStatusException(HttpStatus.NOT_FOUND, "User not found.")


  @DeleteMapping("/{uuid}")
  fun deleteByUUID(@PathVariable uuid: UUID): ResponseEntity&lt;Boolean> {
    val success = userService.deleteByUUID(uuid)

    return if (success)
      ResponseEntity.noContent()
        .build()
    else
      throw ResponseStatusException(HttpStatus.NOT_FOUND, "User not found.")
  }

  private fun User.toResponse(): UserResponse =
    UserResponse(
      uuid = this.id,
      email = this.email,
    )

  private fun UserRequest.toModel(): User =
    User(
      id = UUID.randomUUID(),
      email = this.email,
      password = this.password,
      role = Role.USER,
    )
}</pre>



<p>As we can see, the logic above is pretty similar to what we&#8217;ve done before. </p>



<p>We mark our class with <code>@RestController</code> and <code>@RequestMapping</code>, functions with annotations matching HTTP Methods they are gonna handle, and also our path variables and request bodies. </p>



<p>When converting between models/requests/responses, we make use of <strong>extension functions</strong>, which are my favorite approach for mappers in Kotlin. </p>



<p>Lastly, whenever we want to return anything else than <code>200 OK</code>, we use the <strong>ResponseStatusException</strong>, which is a clean way to do so. </p>



<p>If you would like to test this API now, then check out the following <a href="https://drive.google.com/file/d/1eNG-bOqBmepaZQDZbNpywyh5sWSeazt2/view?usp=sharing" target="_blank" rel="noreferrer noopener">Postman collection</a>.</p>



<h2 class="wp-block-heading" id="h-import-spring-security-and-jwt-library">Import Spring Security and JWT Library</h2>



<p>Wonderful. At this point, we have everything we need to finally add Spring Security to our Spring Boot Kotlin project, and start implementing <strong>JWT authentication</strong> and <strong>authorization</strong>.</p>



<h3 class="wp-block-heading" id="h-update-build-gradle-kts">Update build.gradle.kts</h3>



<p>As the first step, let&#8217;s add the following to the <code>build.gradle.kts</code> file:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">dependencies {
	// other imports
	implementation("io.jsonwebtoken:jjwt-api:0.12.3")
	implementation("io.jsonwebtoken:jjwt-impl:0.12.3")
	implementation("io.jsonwebtoken:jjwt-jackson:0.12.3")
	implementation("org.springframework.boot:spring-boot-starter-security")
	testImplementation("org.springframework.security:spring-security-test")
}</pre>



<p>As we can see, in order to secure our Spring Boot 3 REST API, we must add not only the Spring Security but also an additional library to deal with JWT tokens. </p>



<p>Although the Spring security is a must-have, please feel free to choose whatever JWT library suits you best (you can find a full list <a href="https://jwt.io/libraries" target="_blank" rel="noreferrer noopener">here</a>). I have decided to go with <code>io.jsonwebtoken</code> which is the most popular Java library.</p>



<h3 class="wp-block-heading" id="h-sync-and-rerun-project">Sync and Rerun Project</h3>



<p>Following, let&#8217;s sync our Gradle project and rerun our application. </p>



<p>Among other logs, we will see the following lines: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Using generated security password: 52d7d5b8-ce49-4d93-a4e1-721780290e58

This generated password is for development use only. Your security configuration must be updated before running your application in production.</pre>



<p>Moreover, when we try to query our endpoints, we will get <code>401 Unauthorized</code> for each request. </p>



<p>But what happened? </p>



<p>Well, whenever we add Spring Security to our Spring Boot project, the <strong>authentication gets enabled by default. </strong></p>



<p>In other words, we can query our endpoint now using the <strong>basic access authentication</strong> with <code>user</code> as a username and the randomly generated password as the <code>password</code>. </p>



<p>As a proof, when we update the <code>Authorization</code> in our Postman collection, we will start seeing results again: </p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="350" src="http://blog.codersee.com/wp-content/uploads/2023/10/spring_boot_3_security_jwt_2-1024x350.png" alt="Image presents Postman request using the Basic Auth as the authorization mechanism. " class="wp-image-9008223" srcset="https://blog.codersee.com/wp-content/uploads/2023/10/spring_boot_3_security_jwt_2-1024x350.png 1024w, https://blog.codersee.com/wp-content/uploads/2023/10/spring_boot_3_security_jwt_2-300x102.png 300w, https://blog.codersee.com/wp-content/uploads/2023/10/spring_boot_3_security_jwt_2-768x262.png 768w, https://blog.codersee.com/wp-content/uploads/2023/10/spring_boot_3_security_jwt_2.png 1163w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading" id="h-create-jwt-tokens">Create JWT Tokens</h2>



<p>Although basic auth may be a good choice in some cases, in this tutorial, I would like to show you how to authenticate and authorize requests using <strong>JWT access tokens</strong>. </p>



<p>So, let&#8217;s start everything by implementing a service responsible for token operations. </p>



<h3 class="wp-block-heading" id="h-edit-application-yaml-file">Edit application.yaml file</h3>



<p>As the first step, let&#8217;s navigate to the <code>resources</code> folder and edit the <code>application.yaml</code> file: </p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p></p>
<cite>Note: when generating a new Spring Boot project, the <code>application.properties</code> file is created automatically. So before we start, let&#8217;s change the extension to <code>yaml</code>.</cite></blockquote>



<pre class="EnlighterJSRAW" data-enlighter-language="yaml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">jwt:
  key: ${JWT_KEY}
  access-token-expiration: 3600000
  refresh-token-expiration: 86400000</pre>



<p>As we can see, we introduce 3 custom properties: the key and expiration time (in milliseconds) for both access and refresh tokens. </p>



<p>The key is value will be sourced from the <code>JWT_TOKEN</code> environment variable, which is nothing else than a randomly generated String value. Later, we will see where and why we need it. </p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p></p>
<cite><strong>Important:</strong> vulnerable values should never be hardcoded when implementing a Spring Boot (and not only) application. <br><br>Regardless of the environment the app is running in, values should be stored securely and sourced to our application using environment variables. <br></cite></blockquote>



<h3 class="wp-block-heading" id="h-make-use-of-configurationproperties">Make Use Of @ConfigurationProperties</h3>



<p>As the next step, let&#8217;s make use of the <em>@ConfigurationProperties</em> to easily convert our properties into Kotlin objects.</p>



<p>Let&#8217;s start by adding the <code>configuration</code> package and the <code>JwtProperties</code> class:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import org.springframework.boot.context.properties.ConfigurationProperties

@ConfigurationProperties("jwt")
data class JwtProperties(
  val key: String,
  val accessTokenExpiration: Long,
  val refreshTokenExpiration: Long,
)</pre>



<p>If you&#8217;d like to learn more about @ConfigurationProperties, then I have <a href="https://blog.codersee.com/fail-spring-boot-app-on-missing-environment-variables/" target="_blank" rel="noreferrer noopener">another article</a> you might want to check out later. </p>



<p>Additionally, let&#8217;s add the <code>Configuration</code> class: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Configuration


@Configuration
@EnableConfigurationProperties(JwtProperties::class)
class Configuration</pre>



<p>This way, we enable support for beans annotated with @ConfigurationProperties in our project. </p>



<h3 class="wp-block-heading" id="h-add-tokenservice">Add TokenService</h3>



<p>With all of that done, let&#8217;s add the <code>TokenService</code> class: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Service
class TokenService(
  jwtProperties: JwtProperties
) {

  private val secretKey = Keys.hmacShaKeyFor(
    jwtProperties.key.toByteArray()
  )

  fun generate(
    userDetails: UserDetails,
    expirationDate: Date,
    additionalClaims: Map&lt;String, Any> = emptyMap()
  ): String =
    Jwts.builder()
      .claims()
      .subject(userDetails.username)
      .issuedAt(Date(System.currentTimeMillis()))
      .expiration(expirationDate)
      .add(additionalClaims)
      .and()
      .signWith(secretKey)
      .compact()

  fun isValid(token: String, userDetails: UserDetails): Boolean {
    val email = extractEmail(token)

    return userDetails.username == email &amp;&amp; !isExpired(token)
  }

  fun extractEmail(token: String): String? =
    getAllClaims(token)
      .subject

  fun isExpired(token: String): Boolean =
    getAllClaims(token)
      .expiration
      .before(Date(System.currentTimeMillis()))

  private fun getAllClaims(token: String): Claims {
    val parser = Jwts.parser()
      .verifyWith(secretKey)
      .build()

    return parser
      .parseSignedClaims(token)
      .payload
  }
}</pre>



<p>As we can see, this class exposes functions, which we can use to deal with JWT access and refresh tokens. </p>



<p>Let&#8217;s walk quickly through our logic: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">private val secretKey = Keys.hmacShaKeyFor(
  jwtProperties.key.toByteArray()
)</pre>



<p>The <code>secretKey</code> is nothing else than an instance of <code>SecretKey</code>, which we will use to <strong>sign</strong> and <strong>verify</strong> JWT tokens in our system. In our case, we will use the <code>HMAC-SHA</code> algorithm based on the random key we provided to our project. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">fun generate(
  userDetails: UserDetails,
  expirationDate: Date,
  additionalClaims: Map&lt;String, Any> = emptyMap()
): String =
  Jwts.builder()
    .claims()
    .subject(userDetails.username)
    .issuedAt(Date(System.currentTimeMillis()))
    .expiration(expirationDate)
    .add(additionalClaims)
    .and()
    .signWith(secretKey)
    .compact()</pre>



<p>The <code>generate</code> function is responsible for creating a serialized, URL-safe String with JWT tokens. We set the <code>subject</code>, expiration date, and additional claims based on the arguments passed to it. </p>



<p>Lastly, we sign the token using the <code>SecretKey</code> instance created in the previous step. </p>



<p>Additionally, we provide more functions which we will use later to extract values from tokens and validate them:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">fun isValid(token: String, userDetails: UserDetails): Boolean {
  val email = extractEmail(token)

  return userDetails.username == email &amp;&amp; !isExpired(token)
}

fun extractEmail(token: String): String? =
  getAllClaims(token)
    .subject

fun isExpired(token: String): Boolean =
  getAllClaims(token)
    .expiration
    .before(Date(System.currentTimeMillis()))

private fun getAllClaims(token: String): Claims {
  val parser = Jwts.parser()
    .verifyWith(secretKey)
    .build()

  return parser
    .parseSignedClaims(token)
    .payload
}</pre>



<h2 class="wp-block-heading" id="h-implement-custom-userdetailsservice">Implement Custom UserDetailsService</h2>



<p>As the next step, let&#8217;s introduce a custom implementation of <code>UserDetailsService</code>.</p>



<p>But what exactly is <code>UserDetailsService</code> and <code>UserDetails</code>? </p>



<p>Well, the <strong>UserDetails</strong> represents the core user information. In our case, we will use the default implementation called <code>User</code>, which holds the default information, such as username, password, and a collection of granted authorities (roles). </p>



<p>The <strong>UserDetailsService</strong> is nothing else than an interface used to load user-specific data. It is used by Spring Security to interact with our data source and validate users during authentication. </p>



<p>With that said, let&#8217;s add a new class- <code>CustomUserDetailsService</code>&#8211; to the <code>service</code> package:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import com.codersee.jwtauth.repository.UserRepository
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.stereotype.Service

typealias ApplicationUser = com.codersee.jwtauth.model.User

@Service
class CustomUserDetailsService(
  private val userRepository: UserRepository
) : UserDetailsService {

  override fun loadUserByUsername(username: String): UserDetails =
    userRepository.findByEmail(username)
      ?.mapToUserDetails()
      ?: throw UsernameNotFoundException("Not found!")

  private fun ApplicationUser.mapToUserDetails(): UserDetails =
    User.builder()
      .username(this.email)
      .password(this.password)
      .roles(this.role.name)
      .build()
}</pre>



<p>As we can see, both the <code>username</code> and <code>email</code> in our system refer to the same thing, which is used to uniquely identify users. </p>



<p>And in order to fetch <code>UserDetails</code> we must find the user in our repository and map it to the <code>User</code> instance. </p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p></p>
<cite>Additionally, we make use of the <code>typealias</code> which is a great way to avoid fully qualified name (we have both User in our <code>model</code> package and User from Spring Security</cite></blockquote>



<h2 class="wp-block-heading" id="h-update-configuration">Update Configuration </h2>



<p>With that done, let&#8217;s get back to the <code>Configuration</code> class and register a few beans:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import com.codersee.jwtauth.repository.UserRepository
import com.codersee.jwtauth.service.CustomUserDetailsService
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.AuthenticationProvider
import org.springframework.security.authentication.dao.DaoAuthenticationProvider
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder

@Configuration
@EnableConfigurationProperties(JwtProperties::class)
class Configuration {

  @Bean
  fun userDetailsService(userRepository: UserRepository): UserDetailsService =
    CustomUserDetailsService(userRepository)

  @Bean
  fun encoder(): PasswordEncoder = BCryptPasswordEncoder()

  @Bean
  fun authenticationProvider(userRepository: UserRepository): AuthenticationProvider =
    DaoAuthenticationProvider()
      .also {
        it.setUserDetailsService(userDetailsService(userRepository))
        it.setPasswordEncoder(encoder())
      }

  @Bean
  fun authenticationManager(config: AuthenticationConfiguration): AuthenticationManager =
    config.authenticationManager
}</pre>



<p>Firstly, we must register the bean of type <code>UserDetailsService</code>, which we introduced in the previous step. </p>



<p>Following, we register a <code>PasswordEncoder</code>. To put it simply, <strong>we should never store passwords</strong> in plain text. They should be always <strong>encrypted</strong>, or <strong>hashed</strong>. In this tutorial, we will use the <code>BCrypt</code> strong hashing function for that purpose. </p>



<p>Following, we must provide the <code>AuthenticationProvider</code> and configure which UserDetailsService we will use and the password encoder. </p>



<h2 class="wp-block-heading" id="h-update-userrepository">Update UserRepository</h2>



<p>In the previous step, I mentioned that we should never store passwords in plain text. </p>



<p>So, to fix that, let&#8217;s get back to the <code>UserRepository</code> and make the necessary changes:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Repository
class UserRepository(
  private val encoder: PasswordEncoder
) {

  private val users = mutableSetOf(
    User(
      id = UUID.randomUUID(),
      email = "email-1@gmail.com",
      password = encoder.encode("pass1"),
      role = Role.USER,
    ),
    User(
      id = UUID.randomUUID(),
      email = "email-2@gmail.com",
      password = encoder.encode("pass2"),
      role = Role.ADMIN,
    ),
    User(
      id = UUID.randomUUID(),
      email = "email-3@gmail.com",
      password = encoder.encode("pass3"),
      role = Role.USER,
    ),
  )

  fun save(user: User): Boolean {
    val updated = user.copy(password = encoder.encode(user.password))

    return users.add(updated)
  }
}</pre>



<p>As we can see, after this step both our predefined users and all users which we will create will have their passwords hashed. </p>



<h2 class="wp-block-heading" id="h-implement-authenticationfilter">Implement AuthenticationFilter</h2>



<p>Uff, quite a lot of preparation must be done before we secure our Spring Boot 3 Kotlin app with JWT tokens, isn&#8217;t it? </p>



<p>But don&#8217;t worry, we&#8217;re almost there. </p>



<p>As the next step, let&#8217;s navigate to the <code>config</code> package and introduce our custom Filter:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import com.codersee.jwtauth.service.CustomUserDetailsService
import com.codersee.jwtauth.service.TokenService
import jakarta.servlet.FilterChain
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource
import org.springframework.stereotype.Component
import org.springframework.web.filter.OncePerRequestFilter

@Component
class JwtAuthenticationFilter(
  private val userDetailsService: CustomUserDetailsService,
  private val tokenService: TokenService,
) : OncePerRequestFilter() {

  override fun doFilterInternal(
    request: HttpServletRequest,
    response: HttpServletResponse,
    filterChain: FilterChain
  ) {
    val authHeader: String? = request.getHeader("Authorization")

    if (authHeader.doesNotContainBearerToken()) {
      filterChain.doFilter(request, response)
      return
    }

    val jwtToken = authHeader!!.extractTokenValue()
    val email = tokenService.extractEmail(jwtToken)

    if (email != null &amp;&amp; SecurityContextHolder.getContext().authentication == null) {
      val foundUser = userDetailsService.loadUserByUsername(email)

      if (tokenService.isValid(jwtToken, foundUser))
        updateContext(foundUser, request)

      filterChain.doFilter(request, response)
    }
  }

  private fun String?.doesNotContainBearerToken() =
    this == null || !this.startsWith("Bearer ")

  private fun String.extractTokenValue() =
    this.substringAfter("Bearer ")

  private fun updateContext(foundUser: UserDetails, request: HttpServletRequest) {
    val authToken = UsernamePasswordAuthenticationToken(foundUser, null, foundUser.authorities)
    authToken.details = WebAuthenticationDetailsSource().buildDetails(request)
    SecurityContextHolder.getContext().authentication = authToken
  }

}</pre>



<p>I know, quite a lot of logic, but I&#8217;ll explain it step-by-step in a moment. </p>



<p>But before that, let&#8217;s understand <strong>what are Filters in Spring Framework.</strong> </p>



<p>Well, every request made to our Spring Framework application goes through the filter chain, where each filter in the chain can perform some operations on the request or response.</p>



<p>In our case, we want to use this feature to <strong>authenticate </strong>requests made to our REST API. We want to check whether a user sent a JWT token and validate it, and if everything is fine, we want to update the Spring Security Context. </p>



<p>And that&#8217;s exactly what&#8217;s happening in the code above. </p>



<p>Firstly, we check if the request <strong>contains an Authorization header</strong>. If no, we do not proceed with this function and we simply pass the request down the filter chain.  </p>



<p>Nextly, we extract the JWT token. A valid <code>Authorization</code> header value consists of the <code>Bearer &lt;JWT&gt;</code>, so we must extract the token itself. </p>



<p>Following, we read the <code>email</code> value from the token. And when we make sure it is not null and there&#8217;s no previously authenticated principal in the security context, we fetch the <code>UserDetails</code>, which we then use to validate them with the token. </p>



<p>Lastly, we simply update the security context in our system with <code>foundUser</code> (which is <code>UserDetails</code>) and authorities (which, in our case will be either <code>ADMIN</code> or <code>USER</code>).</p>



<p>To sum up, this function <strong>will be invoked once per each request.</strong> In simple terms, it will check the JWT token and if everything is fine, it will update the Spring Security context with information about user and its roles.</p>



<h2 class="wp-block-heading" id="h-add-security-configuration">Add Security Configuration</h2>



<p>At this point, we did everything we needed to to in order to <strong>authenticate the user</strong>. </p>



<p>In this step, we will learn how to <strong>authorize</strong> him.</p>



<p>And to do so, let&#8217;s introduce a new class- <code>SecurityConfiguration</code> &#8211; in the <code>config</code> package:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpMethod
import org.springframework.security.authentication.AuthenticationProvider
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.web.DefaultSecurityFilterChain
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter

@Configuration
@EnableWebSecurity
class SecurityConfiguration(
  private val authenticationProvider: AuthenticationProvider
) {

  @Bean
  fun securityFilterChain(
    http: HttpSecurity,
    jwtAuthenticationFilter: JwtAuthenticationFilter
  ): DefaultSecurityFilterChain {
    http
      .csrf { it.disable() }
      .authorizeHttpRequests {
        it
          .requestMatchers("/api/auth", "api/auth/refresh", "/error")
          .permitAll()
          .requestMatchers(HttpMethod.POST, "/api/user")
          .permitAll()
          .requestMatchers("/api/user**")
          .hasRole("ADMIN")
          .anyRequest()
          .fullyAuthenticated()
      }
      .sessionManagement {
        it.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
      }
      .authenticationProvider(authenticationProvider)
      .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter::class.java)

    return http.build()
  }
}</pre>



<p>As we can see, the above config exposes a new bean of type <code>DefaultSecurityFilterChain</code>. </p>



<p>To put it simply, this is the way we can modify the default chain by adding, removing, or replacing filters to tailor the security configuration according to our needs. </p>



<p>The first thing we do is <strong>disable the CSRF protection</strong>. It&#8217;s enabled by default, and in most cases not needed (but in real-life projects, please learn a bit more about CSRF attacks and whether your codebase is vulnerable). </p>



<p>Following, we configure the <strong>authorization</strong>. We can clearly see that requests to &#8220;/api/auth&#8221;, &#8220;api/auth/refresh&#8221;, &#8220;/error&#8221;, and POST requests to &#8220;/api/user&#8221; will be <strong>accessible without a token</strong>. And that&#8217;s correct- we cannot require a valid access token for users, who want to sign in, who want to create a new account, and when the API client wants to refresh the token. </p>



<p>And if you are wondering why is the &#8220;/error&#8221; in this list, too, then here comes the answer. It is because of the way Spring handles errors internally. Without that, every exception we throw in our codebase <strong>will return 403 Forbidden</strong>, instead of the HTTP status code we provided. </p>



<p>When it comes to the rest of the &#8220;/api/user&#8221; requests- we want to allow only users with role <code>ADMIN</code>.</p>



<p>And what with the rest of the requests? Well, we want them to be accessed only by fully authenticated users. But what does it mean? In our, stateless REST API, it means simply that every user with a valid JWT token will be able to access them (regardless of his role). </p>



<p>After that, we informed Spring that it should never create a HttpSession (we want our security to be stateless) and that it should never use it to obtain the SecurityContext.</p>



<p>And lastly, we register our <code>CustomAuthenticationProvider</code> and let Spring Security know that <code>JwtAuthenticationFilter</code> we implemented previously should be added before the default <code>UsernamePasswordAuthenticationFilter</code> (the one that required us to specify basic auth).</p>



<h2 class="wp-block-heading" id="h-expose-login-endpoint-generate-access-token">Expose Login Endpoint &#8211; Generate Access Token</h2>



<p>With all of that done, we can finally expose the endpoint, which will be used by our REST API consumers to get the <strong>JWT access token</strong>.</p>



<p>Let&#8217;s create the <code>config.auth</code> package and add a new controller class:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import com.codersee.jwtauth.service.AuthenticationService
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping("/api/auth")
class AuthController(
  private val authenticationService: AuthenticationService
) {

  @PostMapping
  fun authenticate(
    @RequestBody authRequest: AuthenticationRequest
  ): AuthenticationResponse =
    authenticationService.authentication(authRequest)

}</pre>



<p>As we can see, this controller uses <code>AuthenticationService</code> which we will implement in a moment.</p>



<p>But before we do so, let&#8217;s add the <code>AuthenticationRequest</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data class AuthenticationRequest(
  val email: String,
  val password: String,
)</pre>



<p>And the response class:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data class AuthenticationResponse(
  val accessToken: String,
)</pre>



<p>After that, let&#8217;s get back to the <code>service</code> package and implement a service, which will be responsible for authentication and token generation:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import com.codersee.jwtauth.controller.auth.AuthenticationRequest
import com.codersee.jwtauth.controller.auth.AuthenticationResponse
import com.codersee.jwtauth.controller.config.JwtProperties
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.stereotype.Service
import java.util.*

@Service
class AuthenticationService(
  private val authManager: AuthenticationManager,
  private val userDetailsService: CustomUserDetailsService,
  private val tokenService: TokenService,
  private val jwtProperties: JwtProperties,
) {

  fun authentication(authenticationRequest: AuthenticationRequest): AuthenticationResponse {
    authManager.authenticate(
      UsernamePasswordAuthenticationToken(
        authenticationRequest.email,
        authenticationRequest.password
      )
    )

    val user = userDetailsService.loadUserByUsername(authenticationRequest.email)

    val accessToken = createAccessToken(user)

    return AuthenticationResponse(
      accessToken = accessToken,
    )
  }

  private fun createAccessToken(user: UserDetails) = tokenService.generate(
    userDetails = user,
    expirationDate = getAccessTokenExpiration()
  )

  private fun getAccessTokenExpiration(): Date =
    Date(System.currentTimeMillis() + jwtProperties.accessTokenExpiration)

}</pre>



<p>As we can see, the first thing we do is invoke the <code>authenticate</code> method from <code>AuthenticationManager</code>. </p>



<p>If the <code>email</code> and <code>password</code> values don&#8217;t match with any of the users in our system, the <code>authenticate</code> method will throw <code>AuthenticationException</code> and the API will return <code>403 Forbidden</code>.</p>



<p>On the other hand, when they match, we will fetch the <code>UserDetails</code> and use it to generate a JWT token with an expiration time set in <code>application.yaml</code></p>



<p>At the moment, I highly encourage you to run our application and try to call endpoints with different cases. If you would like to use a ready-to-go Postman collection, then you can find one with all endpoints in the next chapter about refresh tokens. </p>



<h2 class="wp-block-heading" id="h-jwt-refresh-token">JWT Refresh Token</h2>



<p>Excellent! At this point, our REST API is properly secured and utilizing the JWT access tokens. </p>



<p>But depending on your needs, you may want to introduce the <strong>JWT refresh tokens </strong>to the system.</p>



<h3 class="wp-block-heading" id="h-introduce-new-endpoint">Introduce New Endpoint </h3>



<p>Firstly, let&#8217;s introduce a new endpoint and update our response classes. </p>



<p>Let&#8217;s start by adding a new <code>TokenResponse</code>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data class TokenResponse(
  val token: String
)</pre>



<p>We will use this class to return the <strong>refreshed access token.</strong></p>



<p>Following, let&#8217;s make the necessary changes to the <code>AuthenticationResponse</code>: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data class AuthenticationResponse(
  val accessToken: String,
  val refreshToken: String,
)</pre>



<p>As we can see, the <code>refreshToken</code> value will be returned when a user authenticates successfully along with the JWT token value. </p>



<p>After that, let&#8217;s add the <code>RefreshTokenRequest</code>, which will be used to deserialize refresh token sent by a user:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data class RefreshTokenRequest(
  val token: String
)</pre>



<p>Great! </p>



<p>At this point, we can add a new endpoint:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  @PostMapping("/refresh")
  fun refreshAccessToken(
    @RequestBody request: RefreshTokenRequest
  ): TokenResponse =
    authenticationService.refreshAccessToken(request.token)
      ?.mapToTokenResponse()
      ?: throw ResponseStatusException(HttpStatus.FORBIDDEN, "Invalid refresh token.")

  private fun String.mapToTokenResponse(): TokenResponse =
    TokenResponse(
      token = this
    )</pre>



<p>Don&#8217;t worry about the missing <code>refreshAccessToken</code> method, we will get back to it in a moment.</p>



<h3 class="wp-block-heading" id="h-implement-refresh-token-repository">Implement Refresh Token Repository</h3>



<p>As the next step, let&#8217;s go to the <code>repository</code> package and introduce the <code>RefreshTokenRepository</code>: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import org.springframework.security.core.userdetails.UserDetails
import org.springframework.stereotype.Component

@Component
class RefreshTokenRepository {

  private val tokens = mutableMapOf&lt;String, UserDetails>()

  fun findUserDetailsByToken(token: String) : UserDetails? =
    tokens[token]

  fun save(token: String, userDetails: UserDetails) {
    tokens[token] = userDetails
  }

}</pre>



<p>As we can see, this class will be responsible for persisting and retrieving refresh tokens. </p>



<p>Along with our tokens, we will store the associated <code>UserDetails</code> instances, so that later we could match the associated subject (email). </p>



<h3 class="wp-block-heading" id="h-edit-authenticationservice">Edit AuthenticationService</h3>



<p>As the last thing, we must get back to the <code>AuthenticationService</code> and make the necessary changes:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import com.codersee.jwtauth.controller.auth.AuthenticationRequest
import com.codersee.jwtauth.controller.auth.AuthenticationResponse
import com.codersee.jwtauth.controller.config.JwtProperties
import com.codersee.jwtauth.repository.RefreshTokenRepository
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.stereotype.Service
import java.util.*

@Service
class AuthenticationService(
  private val authManager: AuthenticationManager,
  private val userDetailsService: CustomUserDetailsService,
  private val tokenService: TokenService,
  private val jwtProperties: JwtProperties,
  private val refreshTokenRepository: RefreshTokenRepository,
) {

  fun authentication(authenticationRequest: AuthenticationRequest): AuthenticationResponse {
    authManager.authenticate(
      UsernamePasswordAuthenticationToken(
        authenticationRequest.email,
        authenticationRequest.password
      )
    )

    val user = userDetailsService.loadUserByUsername(authenticationRequest.email)

    val accessToken = createAccessToken(user)
    val refreshToken = createRefreshToken(user)

    refreshTokenRepository.save(refreshToken, user)

    return AuthenticationResponse(
      accessToken = accessToken,
      refreshToken = refreshToken
    )
  }

  fun refreshAccessToken(refreshToken: String): String? {
    val extractedEmail = tokenService.extractEmail(refreshToken)

    return extractedEmail?.let { email ->
      val currentUserDetails = userDetailsService.loadUserByUsername(email)
      val refreshTokenUserDetails = refreshTokenRepository.findUserDetailsByToken(refreshToken)

      if (!tokenService.isExpired(refreshToken) &amp;&amp; refreshTokenUserDetails?.username == currentUserDetails.username)
        createAccessToken(currentUserDetails)
      else
        null
    }
  }

  private fun createAccessToken(user: UserDetails) = tokenService.generate(
    userDetails = user,
    expirationDate = getAccessTokenExpiration()
  )

  private fun createRefreshToken(user: UserDetails) = tokenService.generate(
    userDetails = user,
    expirationDate = getRefreshTokenExpiration()
  )

  private fun getAccessTokenExpiration(): Date =
    Date(System.currentTimeMillis() + jwtProperties.accessTokenExpiration)

  private fun getRefreshTokenExpiration(): Date =
    Date(System.currentTimeMillis() + jwtProperties.refreshTokenExpiration)
}</pre>



<p>Let&#8217;s summarize what exactly has changed here. </p>



<p>Firstly, we imported the <code>RefreshTokenRepository</code>, so that we could persist new tokens and retrieve the saved ones. </p>



<p>Moreover, we must generate a new refresh token whenever a user authenticates successfully. And that&#8217;s why we added the <code>getRefreshTokenExpiration</code> function and two additional lines in the <code>authentication</code> method. </p>



<p>When it comes to the refresh token flow, it can be summarized in the following steps: </p>



<ol class="wp-block-list">
<li>We extract the user <code>email</code> from the passed refresh token. </li>



<li>If this step is completed successfully, we fetch the <strong>current</strong> user details by the value. </li>



<li>After that, we look for the <strong>persisted</strong> user details with the refresh token. </li>



<li>Lastly, if the refresh token is not expired and the email from JWT subject matches the <strong>current</strong> user details, then a new <strong>access token</strong> is generated for that user. </li>



<li>Otherwise, we return null, which will be translated to <code>403 Forbidden</code> in our controller. </li>
</ol>



<p>And basically, that&#8217;s all 🙂 </p>



<p>If you would like to use a ready-to-go Postman collection with auh headers, then you can <a href="https://drive.google.com/file/d/1fXZ2Wa672rgNAKbwtBDo-r4f_yF0-Z1w/view?usp=sharing" target="_blank" rel="noreferrer noopener">find it right here</a>.</p>



<h2 class="wp-block-heading" id="h-summary">Summary</h2>



<p>And that&#8217;s all for this tutorial in which we have learned how to secure the REST API with Spring Boot 3 (Spring Security 6) with JWT access and refresh tokens and Kotlin. Good job! </p>



<p>If you would like to get the source code for this lesson, then check out <a href="https://github.com/codersee-blog/kotlin-spring-boot-3-spring-security-jwt-access-refresh-tokens" target="_blank" rel="noreferrer noopener">this GitHub repository</a>.</p>



<p>Lastly, if you enjoyed this one, then do not forget to leave a comment and check out my <a href="https://codersee.com/the-complete-kotlin-course/">Complete Kotlin Course</a> 🙂 </p>
<p>The post <a href="https://blog.codersee.com/spring-boot-3-spring-security-6-with-kotlin-jwt/">Spring Boot 3 (Spring Security 6) with Kotlin &#038; JWT</a> appeared first on <a href="https://blog.codersee.com">Codersee blog- Kotlin on the backend</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.codersee.com/spring-boot-3-spring-security-6-with-kotlin-jwt/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 

Served from: blog.codersee.com @ 2026-04-19 13:07:53 by W3 Total Cache
-->