<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sahar Peretz on Medium]]></title>
        <description><![CDATA[Stories by Sahar Peretz on Medium]]></description>
        <link>https://medium.com/@saharpe.dev?source=rss-ec45e16347d2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pY04uRnZSF-040B3</url>
            <title>Stories by Sahar Peretz on Medium</title>
            <link>https://medium.com/@saharpe.dev?source=rss-ec45e16347d2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:29:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saharpe.dev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Non-Blocking Magic: Build High-Performance Kotlin Services]]></title>
            <link>https://medium.com/@saharpe.dev/non-blocking-magic-build-high-performance-kotlin-services-b42f8f1ad1ad?source=rss-ec45e16347d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b42f8f1ad1ad</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-webflux]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Sahar Peretz]]></dc:creator>
            <pubDate>Sat, 15 Feb 2025 17:00:09 GMT</pubDate>
            <atom:updated>2025-02-15T17:00:09.735Z</atom:updated>
            <content:encoded><![CDATA[<h3>Non-Blocking Magic: Build High-Performance Kotlin Services with Spring WebFlux + Coroutines + MongoDB ✨</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*546b9EGUSLzcMFkbQ-5FtA.png" /></figure><h3>Introduction ☕</h3><p>Modern apps need to be fast, scalable, and ready to handle thousands (or even millions) of requests. But traditional blocking architectures? They often hit bottlenecks, leaving your threads sitting around like they’re waiting for coffee.</p><p>Enter <strong>Spring WebFlux, Reactive MongoDB, and Kotlin Coroutines; <br></strong>a power trio that lets us build efficient, non-blocking services <em>without</em> drowning in callback hell.</p><p>This guide will walk you through setting up a <strong>fully reactive Kotlin Spring Boot service</strong> with <strong>MongoDB</strong>, keeping it clean, simple, and actually fun to work with.</p><h3>Why Non-Blocking Architecture Matter?</h3><p>Most Spring MVC apps follow a <strong>one-thread-per-request</strong> model. <br>Sounds fine… until you start making lots of blocking calls (like database queries or API requests) your threads get stuck waiting, and your app slows down.</p><p>Spring WebFlux flips the script by <strong>going non-blocking;<br></strong>handling requests asynchronously so threads don’t sit idle. <br>This means:<br>✅ <strong>Better scalability</strong> (handle more requests with fewer resources)<br>✅ <strong>Improved efficiency</strong> (no more thread exhaustion)<br>✅ <strong>Faster response times</strong> 🚀</p><h3>Why WebFlux + Kotlin Coroutines + Reactive MongoDB? 🤔</h3><p>This stack isn’t just about being modern — it’s about being <strong>fast, scalable, and easy to work with</strong>. Here’s why it’s a game-changer:</p><p>🚀 <strong>Spring WebFlux: </strong>Handles high-concurrency requests <em>without</em> blocking threads. Say goodbye to thread exhaustion!<br>⚡ <strong>Kotlin Coroutines: </strong>Makes reactive programming feel <em>natural</em> instead of forcing you into complex callback chains.<br>🛢️ <strong>Reactive MongoDB: </strong>Fully non-blocking database operations for seamless data handling.</p><p>And the best part? <strong>Kotlin Flow</strong> simplifies working with reactive streams — so instead of wrestling with complex Publisher chains, you get <strong>clean, readable, and efficient asynchronous code</strong>.</p><p>Ready to dive in? Let’s build something awesome!</p><h3>Setting Up the Project 🛠</h3><ol><li>Add Dependencies to build.gradle.kts</li></ol><pre>dependencies {<br>    implementation(&quot;org.springframework.boot:spring-boot-starter-webflux&quot;)<br>    implementation(&quot;org.springframework.boot:spring-boot-starter-data-mongodb-reactive&quot;)<br>    implementation(&quot;org.jetbrains.kotlinx:kotlinx-coroutines-reactor&quot;)<br>}</pre><p>2. Configure a mongoDB connection.</p><h3>Defining a Model and Repository 🦄</h3><p>Let’s create a simple Unicorn entity with a Reactive Repository using ReactiveFluentMongoOperations class.</p><pre>@Document<br>data class Unicorn(<br>    @Id val id: String,<br>    val name: String,<br>    val color: String,<br>    val magicPower: String<br>)</pre><pre>interface UnicornRepository {<br>    suspend fun findById(id: String): Unicorn?<br>    suspend fun findAll(): Flow&lt;Unicorn&gt;<br>    suspend fun insert(unicorn: Unicorn): Unicorn<br>    suspend fun update(unicorn: Unicorn): Unicorn<br>    suspend fun delete(id: String)<br>}</pre><pre>import kotlinx.coroutines.flow.Flow<br>import org.springframework.data.mongodb.core.*<br>import org.springframework.data.mongodb.core.query.isEqualTo<br>import org.springframework.stereotype.Component<br><br>@Component<br>class UnicornRepositoryImpl(<br>     private val mongoOperations: ReactiveFluentMongoOperations<br>): UnicornRepository {<br><br>    override suspend fun findById(id: String): Unicorn? =<br>        mongoOperations.query&lt;Unicorn&gt;()<br>                       .matching(Unicorn::id isEqualTo id)<br>                       .awaitFirstOrNull()<br><br>    override suspend fun findAll(): Flow&lt;Unicorn&gt; =<br>        mongoOperations.query&lt;Unicorn&gt;()<br>                       .flow()<br><br>    override suspend fun insert(unicorn: Unicorn): Unicorn =<br>        mongoOperations.insert&lt;Unicorn&gt;()<br>                       .oneAndAwait(unicorn)<br><br>    override suspend fun update(unicorn: Unicorn): Unicorn =<br>         mongoOperations.update&lt;Unicorn&gt;()<br>                        .matching(Unicorn::id isEqualTo id)<br>                        .replaceWith(unicorn)<br>                        .findReplaceAndAwait()<br><br>    override suspend fun delete(id: String) {<br>        mongoOperations.remove&lt;Unicorn&gt;()<br>                       .matching(Unicorn::id isEqualTo id)<br>                       .allAndAwait()<br>    }<br>}</pre><h3>Building a Non-Blocking REST API 🚀</h3><p>Now, let’s create a service layer and WebFlux controller.</p><pre>@Service<br>class UnicornService(<br>     private val unicornRepository: UnicornRepository<br>) {<br>    <br>    suspend fun getUnicorn(id: String): Unicorn? =<br>         repository.findById(id)<br>    <br>    suspend fun getAllUnicorns(): Flow&lt;Unicorn&gt; =<br>         repository.findAll()<br>    <br>    suspend fun createUnicorn(unicorn: Unicorn): Unicorn =<br>         repository.insert(unicorn)<br><br>    suspend fun updateUnicorn(unicorn: Unicorn): Unicorn =<br>         repository.update(unicorn)<br>    <br>    suspend fun deleteUnicorn(id: String) =<br>         repository.deleteById(id)<br>}</pre><pre>interface UnicornApi {<br><br>    companion object {<br>        const val BASE_PATH = &quot;/unicorns&quot;<br>    }<br><br>    @GetMapping(&quot;/{unicornId}/&quot;)<br>    suspend fun getUnicorn(@RequestParam unicornId: String): UnicornDto?<br><br>    @GetMapping(&quot;/all&quot;)<br>    suspend fun getAllUnicorns(@RequestParam unicornId: String): UnicornsDto?<br><br>    @PostMapping(&quot;/&quot;)<br>    suspend fun createUnicorn(@RequestBody unicorn: UnicornDto): UnicornDto<br><br>    @PutMapping(&quot;/{unicornId}/&quot;)<br>    suspend fun updateUnicorn(@PathVariable unicornId: String, @RequestBody unicorn: UnicornDto): UnicornDto<br><br>    @DeleteMapping(&quot;/{unicornId}/&quot;)<br>    suspend fun deleteUnicorn(@PathVariable unicornId: String)<br><br>}</pre><pre>@RestController<br>@RequestMapping(UnicornApi.BASE_PATH)<br>class UnicornController(<br>    private val unicornService: UnicornService<br>) : RulebookApi {<br><br>    override suspend fun getUnicorn(unicornId: String): UnicornDto? {<br>        // add validations, mappings, then call service to getUnicorn()<br>    }<br><br>    override suspend fun getAllUnicorns(unicornId: String): UnicornsDto {<br>        // add validations, mappings, then call service to getAllUnicorns()<br>    }<br><br>    override suspend fun createUnicorn(unicorn: UnicornDto): UnicornDto {<br>        // add validations, mappings, then call service to createUnicorn()<br>    }<br><br>    override suspend fun updateUnicorn(unicornId: String, unicorn: UnicornDto): UnicornDto {<br>        // add validations, mappings, then call service to updateUnicorn()<br>    }<br><br>    override suspend fun deleteUnicorn(unicornId: String) {<br>        // add validations, mappings, then call service to deleteUnicorn()<br>    }<br>}</pre><h3>🎯 Conclusion</h3><p>By using <strong>Spring WebFlux, Kotlin Coroutines, and Reactive MongoDB</strong>, we can build modern, scalable, and efficient applications with minimal complexity. This setup enables high concurrency without blocking threads, making it ideal for microservices, streaming APIs, and other high-throughput applications.</p><p>Now, it’s your turn! 🚀 Start experimenting with WebFlux and Coroutines to unlock the full potential of reactive programming in your Kotlin applications.</p><p>If you found it helpful, show some love with a clap 👏, share it with others, and follow for more insights! (:</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b42f8f1ad1ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FastAPI + Auth0: Secure Your API with JWT and Permissions (Step-by-Step) ]]></title>
            <link>https://medium.com/@saharpe.dev/implementing-jwt-authentication-with-fastapi-and-auth0-9d8dacf1f4ef?source=rss-ec45e16347d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d8dacf1f4ef</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[auth0]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Sahar Peretz]]></dc:creator>
            <pubDate>Thu, 23 Jan 2025 19:00:14 GMT</pubDate>
            <atom:updated>2025-07-02T10:26:34.478Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yh6hOfGLspc7ltzd" /></figure><p><strong>link for free access:</strong><br><a href="https://medium.com/@saharpe.dev/implementing-jwt-authentication-with-fastapi-and-auth0-9d8dacf1f4ef?sk=e2942b433a6a054c9c9731a92bf35433">https://medium.com/@saharpe.dev/implementing-jwt-authentication-with-fastapi-and-auth0-9d8dacf1f4ef?sk=e2942b433a6a054c9c9731a92bf35433</a></p><p>Implementing secure and scalable authentication for an application is crucial, especially when dealing with APIs. <br>JWTs and Auth0 make it easier to handle authentication efficiently. <br>This blog post will walk you through a practical implementation of JWT authentication in a FastAPI project with a focus on <strong><em>permissions claims</em></strong> embedded in the JWT.</p><h3>Why Should Permissions claims in the JWT?</h3><p>Think of the permissions claims in the JWT like VIP tickets at a concert. They’re embedded in the token itself, so the API knows what level of access someone has without needing to ask a backstage database. <br>Here’s why that’s a big deal:</p><ol><li><strong>Speedy Access 🚀</strong>: No back-and-forth checking roles or permissions. <br>It’s all in the token, and no need to query the database or external services on every request.</li><li><strong>Self-Contained Security</strong>: Permissions claims in the JWT allow the token to “cary” all necessary claims; easy to validate, hard to fake.</li><li><strong>Scalable AF</strong>: Stateless = better performance. Who doesn’t want that?</li><li><strong>Security</strong>: by validating tokens using Auth0’s public keys you ensure the integrity of permissions and other claims.</li></ol><p>Now, let’s roll up our sleeves and implement this magic.</p><h3>Setting up permissions with FastAPI and Auth0</h3><h4>Core Dependencies</h4><ol><li><strong>FastAPI: </strong>pip install fastapi</li><li><strong>Uvicorn</strong>: pip install uvicorn</li><li><strong>PyJWT: </strong>pip install PyJWT</li></ol><h4>Step 1: Extracting the Bearer Token 🕵️‍♀️</h4><p>Let’s grab the Authorization header from incoming requests and validate it, we want to check that the Authorization header is formatted properly.<br>Only Bearer {token} gets through, anything else = <strong>UNAUTHORIZED</strong> 🚫</p><pre>from typing import NamedTuple<br><br>from fastapi.requests import Request<br>from app.core.auth.custom_exceptions import BadCredentialsException, RequiresAuthenticationException<br><br>class BearerTokenElements(NamedTuple):<br>    authorization_scheme: str<br>    bearer_token: str<br>    are_valid: bool<br><br>def get_bearer_token(request: Request) -&gt; str:<br>    bearer_token = extract_bearer_token(request)<br>    if bearer_token:<br>        bearer_token_elements = get_bearer_token_elements(bearer_token)<br>        if not bearer_token_elements.are_valid:<br>            raise BadCredentialsException<br>        return bearer_token_elements.bearer_token<br>    else:<br>        raise RequiresAuthenticationException<br><br>def extract_bearer_token(request: Request) -&gt; str:<br>    return request.headers.get(&#39;Authorization&#39;)<br><br>def get_bearer_token_elements(bearer_token: str) -&gt; BearerTokenElements:<br>    try:<br>        authorization_scheme, bearer_token = bearer_token.split()<br>    except ValueError:<br>        raise BadCredentialsException<br>    else:<br>        valid = authorization_scheme.lower() == &#39;bearer&#39; and bool(bearer_token.strip())<br>        return BearerTokenElements(authorization_scheme, bearer_token, valid)</pre><h4>Step 2: Validate the token with Auth0 🔑</h4><p>Once we’ve extracted the token from the incoming request header, we need to verify it with Auth0; the <strong>signature</strong>, <strong>audience</strong>, and <strong>issuer</strong>.<br>If the token audience or issuer doesn’t match = <strong>UNAUTHORIZED</strong> 🚫</p><pre>import jwt<br>from fastapi import Depends<br>from jwt import InvalidTokenError, PyJWKClientError<br><br>from app.core.auth.auth_header_elements import get_bearer_token<br>from app.core.auth.custom_exceptions import BadCredentialsException<br>from app.core.config import settings # pydantic&#39;s settings<br><br>def validate_token(token: str = Depends(get_bearer_token)):<br>    return auth0_jwt_validator.validate(token)<br><br>class Auth0JWTBearerTokenValidator:<br>    def __init__(self):<br>        self.auth0_audience = settings.auth0_audience<br>        self.algorithm = &#39;RS256&#39;<br>        self.auth0_issuer_url: str = f&#39;https://{settings.auth0_domain}/&#39;<br>        jwks_uri: str = f&#39;{self.auth0_issuer_url}.well-known/jwks.json&#39;<br>        self.jwks_client = jwt.PyJWKClient(uri=jwks_uri, lifespan=3600)<br>    def validate(self, token):<br>        try:<br>            jwt_signing_key = self.jwks_client.get_signing_key_from_jwt(token).key<br>            payload = jwt.decode(<br>                token,<br>                jwt_signing_key,<br>                algorithms=[self.algorithm],<br>                audience=self.auth0_audience,<br>                issuer=self.auth0_issuer_url,<br>            )<br>            return payload<br>        except InvalidTokenError:<br>            raise BadCredentialsException<br>        except PyJWKClientError:<br>            raise BadCredentialsException<br><br>auth0_jwt_validator = Auth0JWTBearerTokenValidator()</pre><h4>Step 3: Check the permissions 🎟️</h4><p>Here’s where the fun begins. Permissions are embedded in the JWT, and we’ll validate them against what each route requires.<br>This PermissionsValidator class checks if the required permissions exists in the token, if not = <strong>UNAUTHORIZED</strong> 🚫</p><pre>from fastapi import Depends<br><br>from app.core.auth.custom_exceptions import PermissionDeniedException<br>from app.core.auth.jwt_validator import validate_token<br><br>class PermissionsValidator:<br>    def __init__(self, required_permissions: list[str]):<br>        self.required_permissions = required_permissions<br><br>    def __call__(self, token: str = Depends(validate_token)):<br>        token_permissions = token.get(&#39;permissions&#39;)<br>        token_permissions_set = set(token_permissions)<br>        required_permissions_set = set(self.required_permissions)<br>        if not required_permissions_set.issubset(token_permissions_set):<br>            raise PermissionDeniedException</pre><h4>Step 4: Protect routes like a pro 🛡️</h4><p>Let’s use the PermissionsValidator to protect our routes.</p><pre>from fastapi import APIRouter, Depends<br>from app.core.auth.permissions_validator import PermissionsValidator<br><br>router = APIRouter(<br>    prefix=&#39;/protected-unicorns&#39;,<br>    tags=[&#39;Unicorns&#39;],<br>    dependencies=[Depends(PermissionsValidator([&#39;read:unicorns&#39;]))]<br>)<br><br>@router.post(&#39;/&#39;)<br>async def protected_unicorns():<br>    return &#39;Welcome to the secret unicorn sanctuary 🦄&#39;</pre><p>Routes now are protected by permissions.<br>It’s clean, reusable, and easy to scale-up for more endpoints.</p><h4>Custom Exceptions</h4><p>Leverage FastAPI’s HTTPExceptions to automatically return the response to the client, let know what went wrong. (:</p><pre>from fastapi import HTTPException, status<br><br>class BadCredentialsException(HTTPException):<br>    def __init__(self):<br>        super().__init__(<br>            status_code=status.HTTP_401_UNAUTHORIZED,<br>            detail=&#39;Bad credentials&#39;<br>        )<br><br>class PermissionDeniedException(HTTPException):<br>    def __init__(self):<br>        super().__init__(<br>            status_code=status.HTTP_403_FORBIDDEN,<br>            detail=&#39;Permission denied&#39;<br>        )<br><br>class RequiresAuthenticationException(HTTPException):<br>    def __init__(self):<br>        super().__init__(<br>            status_code=status.HTTP_401_UNAUTHORIZED,<br>            detail=&#39;Requires authentication&#39;<br>        )</pre><h3>Why This Approach Wins 🏆</h3><ol><li><strong>Stateless &amp; Scalable</strong>: No extra DB queries, the JWT carries everything you need.</li><li><strong>Secure by Default</strong>: Auth0 handles key management, and the RS256 algorithm ensures bullet-proof tokens.</li><li><strong>Easy to Extend</strong>: Add more permissions or validators as needed.</li><li><strong>FastAPI Integration</strong>: Dependencies and exceptions make the code clean and intuitive.</li></ol><h3>Conclusion 🎉</h3><p>By embedding permissions in JWTs and using Auth0, you’ve got a modern, secure, and efficient authentication setup. <br>FastAPI’s powerful dependency injection system makes this approach clean and easy to maintain. <br>So go ahead; lock down those endpoints 🔒</p><p>If you found it helpful, show some love with a clap 👏, share it with others, and follow for more insights! (:</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d8dacf1f4ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>