<?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 Sanjana Raj BK on Medium]]></title>
        <description><![CDATA[Stories by Sanjana Raj BK on Medium]]></description>
        <link>https://medium.com/@sanjanarajbk?source=rss-752a01009e31------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*f1BI9wAozwDS7-Mu</url>
            <title>Stories by Sanjana Raj BK on Medium</title>
            <link>https://medium.com/@sanjanarajbk?source=rss-752a01009e31------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 08:41:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sanjanarajbk/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[How Do I Test Goroutines When I Don’t Know What Order They’ll Run In?]]></title>
            <link>https://medium.com/@sanjanarajbk/how-do-i-test-goroutines-when-i-dont-know-what-order-they-ll-run-in-ec3d3cd3abb6?source=rss-752a01009e31------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec3d3cd3abb6</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[order-of-execution]]></category>
            <category><![CDATA[goroutines]]></category>
            <dc:creator><![CDATA[Sanjana Raj BK]]></dc:creator>
            <pubDate>Tue, 21 Oct 2025 11:09:26 GMT</pubDate>
            <atom:updated>2025-10-21T11:09:26.626Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s take a use case where we iterate over a list of character IDs, hit an API for each ID, and fetch the corresponding character details — all concurrently.</p><pre>package main<br><br>import (<br>    &quot;encoding/json&quot;<br>    &quot;fmt&quot;<br>    &quot;net/http&quot;<br>    &quot;runtime&quot;<br>    &quot;strings&quot;<br>    &quot;sync&quot;<br>)<br><br>type ClientResponse struct {<br>    Name string `json:&quot;name&quot;`<br>}<br><br>func FetchCharacterNames(numbers []int) ([]string, error) {<br>    var waitGroup sync.WaitGroup<br>    var mutex sync.Mutex<br>    result := make([]string, 0)<br>    waitGroup.Add(len(numbers))<br><br>    for _, number := range numbers {<br>        go func(num int) {<br>            defer waitGroup.Done()<br><br>            response, err := http.Get(&quot;https://dattebayo-api.onrender.com/characters/&quot; + fmt.Sprint(num))<br>            if err != nil {<br>                return<br>            }<br><br>            var clientResponse ClientResponse<br>            decodeErr := json.NewDecoder(response.Body).Decode(&amp;clientResponse)<br>            response.Body.Close()<br>            if decodeErr != nil {<br>                return<br>            }<br><br>            mutex.Lock()<br>            result = append(result, clientResponse.Name)<br>            mutex.Unlock()<br>        }(number)<br>    }<br><br>    waitGroup.Wait()<br>    return result, nil<br>}<br><br>func main() {<br>    fmt.Println(&quot;Number of CPU cores available&quot;, runtime.NumCPU())<br>    numbers := []int{1344, 1307, 515, 376, 1293}<br>    names, _ := FetchCharacterNames(numbers)<br>    fmt.Println(strings.Join(names, &quot;, &quot;))<br>}</pre><p>If you run this code, you’ll see that the <strong>result slice prints the character names — but not necessarily in the same order</strong> as the input list.</p><p>Each goroutine runs independently, so whichever call completes first, its result gets appended first.<br> And that’s perfectly fine — because concurrency isn’t about order, it’s about <em>efficiency and parallelism</em>.</p><p>But here’s the interesting part…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OMh4WcP-LAzhAgHQuVvjaA.png" /></figure><h4><strong>The Testing Dilemma</strong></h4><p>We don’t want to make sequential API calls — Goroutines are supposed to handle them concurrently and efficiently.<br> But if the execution order isn’t guaranteed, what happens when we try to write a test?</p><p>Let’s see what happens when we test it.</p><pre>package main<br><br>import (<br>    &quot;testing&quot;<br><br>    &quot;github.com/stretchr/testify/assert&quot;<br>)<br><br>func TestFetchCharacterNames(t *testing.T) {<br>    numbers := []int{1344, 1307, 515, 376, 1293}<br>    names, err := FetchCharacterNames(numbers)<br>    assert.NoError(t, err)<br>    assert.Equal(t, []string{&quot;Naruto Uzumaki&quot;, &quot;Sasuke Uchiha&quot;, &quot;Jiraiya&quot;, &quot;Kakashi Hatake&quot;, &quot;Itachi Uchiha&quot;}, names)<br>}<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XrjVxVV-5PoQUCS6IsyPA.png" /><figcaption>Attempt: 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pk0Z3oJN0kWMR7rWrLnPRA.png" /><figcaption>Attempt: 2</figcaption></figure><p>You might update the test to match the “actual” order, rerun it, and see it pass.<br> You push the code, and boom — your CI pipeline fails.<br> You rerun it again, and it passes.<br> Congratulations — you’ve just met your first <em>flaky test</em>! 🎉</p><h4><strong>Why It Happens?</strong></h4><p>Goroutines don’t guarantee any specific order of execution.<br> The order in which results are appended depends on network timing, CPU scheduling, and even random factors like context switching.</p><p>Your test, however, <strong>expects a deterministic sequence</strong>, while the function itself is <strong>nondeterministic by design</strong>.</p><p>That’s the mismatch.</p><h4><strong>How Do We Fix It?</strong></h4><pre>package main<br><br>import (<br> &quot;testing&quot;<br> &quot;github.com/stretchr/testify/assert&quot;<br>)<br><br>func TestFetchCharacterNames(t *testing.T) {<br>    numbers := []int{1344, 1307, 515, 376, 1293}<br>    actualResult, err := FetchCharacterNames(numbers)<br>    expectedResult := []string{&quot;Naruto Uzumaki&quot;, &quot;Sasuke Uchiha&quot;, &quot;Jiraiya&quot;, &quot;Kakashi Hatake&quot;, &quot;Itachi Uchiha&quot;}<br>    assert.NoError(t, err)<br>    assert.ElementsMatch(t, expectedResult, actualResult)<br>}</pre><p>Instead of checking for exact order, we can simply verify that both slices contain the same elements — regardless of how they’re arranged.</p><p>By using assert.ElementsMatch, we tell the test that order doesn’t matter, just like how goroutines themselves don’t care about execution order.</p><p>And just like that — no more flaky tests, only happy, concurrent code.</p><h4><strong>Testing Goroutines When Results Are Part of a Larger Object</strong></h4><p>Sometimes, the result of goroutines isn’t just a simple slice; it may be part of a larger object that is passed as a parameter to another dependency, like a repository. In such cases, how can we test it <strong>without enforcing a strict order</strong> on the results?</p><p>We can handle this elegantly by implementing the <strong>gomock.Matcher interface</strong>, overriding the matching logic, and sorting the slices before comparison. This allows us to verify correctness regardless of the order in which goroutines complete.</p><p>Here’s an example:</p><pre>package service<br>import (<br> &quot;reflect&quot;<br> &quot;sort&quot;<br> &quot;testing&quot;<br> &quot;github.com/stretchr/testify/assert&quot;<br> . &quot;go_routine_service/mocks&quot;<br> &quot;github.com/golang/mock/gomock&quot;<br> &quot;go_routine_service/models&quot;<br>)<br>func TestProcessCharacters(t *testing.T) {<br> ctrl := gomock.NewController(t)<br> defer ctrl.Finish()<br> mockRepo := NewMockRepository(ctrl)<br> service := NewCharacterService(mockRepo)<br> expected := models.CharacterPayload{<br>  IDs:   []int{1344, 1307, 515, 376, 1293},<br>  Names: []string{&quot;Naruto Uzumaki&quot;, &quot;Sasuke Uchiha&quot;, &quot;Jiraiya&quot;, &quot;Kakashi Hatake&quot;, &quot;Itachi Uchiha&quot;},<br> }<br> mockRepo.EXPECT().<br>  Save(CharacterPayloadMatcher{expected}).<br>  Return(nil).<br>  Times(1)<br> err := service.ProcessCharacters(expected.IDs)<br> assert.NoError(t, err)<br>}<br>// CharacterPayloadMatcher ignores the order of Names<br>type CharacterPayloadMatcher struct {<br> expected models.CharacterPayload<br>}<br>func (m CharacterPayloadMatcher) Matches(x interface{}) bool {<br> actual, ok := x.(models.CharacterPayload)<br> if !ok {<br>  return false<br> }<br> expectedNames := append([]string{}, m.expected.Names...)<br> actualNames := append([]string{}, actual.Names...)<br> sort.Strings(expectedNames)<br> sort.Strings(actualNames)<br> return reflect.DeepEqual(expectedNames, actualNames)<br>}<br>func (m CharacterPayloadMatcher) String() string {<br> return &quot;matches CharacterPayload with same IDs and Names (order-independent)&quot;<br>}</pre><p>Voila! 🎉 With this approach, the test passes <strong>regardless of the order</strong> in which goroutines populate the Names slice.</p><h4><strong>Conclusion</strong></h4><p>For simple slices, assert.ElementsMatch helps ignore order, while for nested objects passed into mocks, a custom gomock.Matcher ensures data consistency without caring about sequence.</p><p>These are some of the approaches I’ve come across while working with concurrent Go code. Both have proven useful in dealing with the tricky nature of goroutines — where timing and order are never guaranteed.</p><p>I’ve learned that it’s better to go with Go’s flow — quite literally.<br>Instead of worrying about order, focus on whether the results are correct.<br>That way, your tests will be just as steady and efficient as the goroutines running behind them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec3d3cd3abb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async-Await: A Deep Dive into Asynchronous Programming in JavaScript and TypeScript]]></title>
            <link>https://medium.com/@sanjanarajbk/async-await-a-deep-dive-into-asynchronous-programming-in-javascript-and-typescript-da06b4c44e4c?source=rss-752a01009e31------2</link>
            <guid isPermaLink="false">https://medium.com/p/da06b4c44e4c</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Sanjana Raj BK]]></dc:creator>
            <pubDate>Wed, 13 Nov 2024 09:18:49 GMT</pubDate>
            <atom:updated>2024-11-14T03:43:19.709Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you come across the dynamic duo of async and await? This powerful pair transforms asynchronous workflows into code that feels almost synchronous. TypeScript and JavaScript, being <em>single-threaded</em>, can present challenges when handling async tasks, but the async keyword simplifies this. It might seem small, but it plays a crucial role in enabling asynchronous behaviour, with await naturally following in tow.</p><p>Let’s walk through an example:</p><pre>async function addAsync(): Promise&lt;number&gt; {<br>    return 4 + 4;<br>}</pre><p>In this case, the addAsync function is declared with the async keyword, and it promises to return a Promise&lt;number&gt;. Even though we’re directly returning 4 + 4 (a number), the async keyword automatically wraps this value in a promise. As a result, anything an async function returns is encapsulated in a promise.</p><p>Before we move on, let’s define a promise: it’s an object that reserves space to eventually hold either a successful result (if resolved) or an error (if rejected), based on how the operation completes.</p><p><em>But why not just return the value directly?</em> When an operation involves something time-consuming, like an API call, it requires time to fetch the data. Without a promise, the function wouldn’t wait — it would move directly to the next line, returning a value that hasn’t been set yet. This would result in undefined because the data hadn’t arrived before the function moved on.</p><p>To access the value inside this promise, we use the await keyword. await pauses the function&#39;s execution until the promise resolves, letting us retrieve the actual value.</p><p>For example:</p><pre>async function run(): Promise&lt;void&gt; {<br>   const data = await addAsync();<br>   console.log(data);<br>}</pre><p>Notice that run is also an async function. Why? Because anytime you use await inside a function, that function must be marked async. They truly are inseparable.</p><p><strong>Understanding How Async-Await Operates Under the Hood in a Single-Threaded Environment</strong></p><p>As we mentioned earlier, when the <em>JavaScript engine</em> encounters await in an async function, it pauses the function&#39;s execution. However, this does not halt the entire program.</p><p>Instead, the state of the async function is stored in an event queue, and the engine continues to execute any remaining synchronous code in the call stack. Once the call stack is empty, the <em>event loop</em> checks whether the promise has been resolved. If so, it picks up the saved context from the queue, pushes it to the call stack, and resumes execution right after the await statement. This process repeats for any contexts in the event queue.</p><p>In essence, only the execution of the async function is paused, not the whole program, which makes async programming efficient. The event loop ensures that other tasks can be executed in the meantime, making the system more responsive and preventing unnecessary blocking.</p><p><strong>Conclusion</strong></p><p>Async-await simplifies handling asynchronous operations, making your code feel almost synchronous. Thanks to the event loop, only your function takes a nap while the rest of your app keeps hustling. It’s like pressing pause on one scene, but the movie keeps playing. Utilize async to optimize your code and enhance performance — the smart approach to managing asynchronous tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da06b4c44e4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why TypeScript: A Beginner’s Journey to Understanding Types and References]]></title>
            <link>https://medium.com/@sanjanarajbk/why-typescript-a-beginners-journey-to-understanding-types-and-references-a90682449f16?source=rss-752a01009e31------2</link>
            <guid isPermaLink="false">https://medium.com/p/a90682449f16</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript-tips]]></category>
            <category><![CDATA[type]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Sanjana Raj BK]]></dc:creator>
            <pubDate>Sat, 12 Oct 2024 14:25:09 GMT</pubDate>
            <atom:updated>2024-10-12T14:51:52.030Z</atom:updated>
            <content:encoded><![CDATA[<p>Initially, when I started working with TypeScript, I questioned the need for all the extra checks. It felt like it was slowing me down, constantly throwing red lines and being overly strict about the types I was trying to use. At first, it seemed frustrating, but I realized it’s forcing me to address potential issues as I write the code, rather than letting errors slip through to runtime.</p><p>TypeScript’s approach is essentially: “<em>fix your code now so you don’t have to deal with problems later.</em>” While it might feel time-consuming at first, it’s actually pretty smart and, in the long run, saves you a lot of time by preventing future bugs.</p><p>Let’s look at a simple example to see how JavaScript and TypeScript handle code differently:</p><p>JavaScript doesn’t enforce the type of input passed into a function, so it only fails at runtime, potentially resulting in NaN (Not a Number). This means you won’t know something is wrong until you actually run the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBbJS-oYCB7UPXo-FzZIbg.png" /><figcaption>code in javascript</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmLvOfOeuE6SMI82YjAfNw.png" /></figure><p>TypeScript, on the other hand, immediately alerts you if the input type passed to the function is incorrect. This happens because the function has a type constraint on its parameter, meaning it can only accept a number and nothing else.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RlJh4CRG3x_9eGmhXvAswQ.png" /><figcaption>code in typescript</figcaption></figure><p><strong>Primitive types: number, string and boolean</strong></p><p>When we assign a specific type to a variable, TypeScript allows us to catch errors right at the typing stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LHygvWJjVButPBuzvbkfSQ.png" /><figcaption>The happy path for defining correct primitive types</figcaption></figure><p>Now, when we try to assign a string value to isAvailable, TypeScript flags it as an error instantly. This proactive error-checking helps ensure that we adhere to the defined types, reducing the risk of potential bugs later on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zP7PPGdtCr1prZeXXahbRQ.png" /><figcaption>Type error when trying to assign a different value</figcaption></figure><p><strong>Custom Types: Objects and Arrays</strong></p><p><em>Objects</em></p><p>To define a custom type for an object, we simply declare a type for each field within the object. The same approach extends to defining types for nested objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RdmDBRF6AfSuO0pYRyLt3g.png" /><figcaption>defining type for an object</figcaption></figure><p>Here, we define the type for a basic object with the fields name, phone, and address.</p><p>In more complex scenarios, like defining a nested object, you can specify the structure within another object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BlBYIofDjRPbZ-3H1GNHRw.png" /><figcaption>defining type for a nested object</figcaption></figure><p>This defines a nested object structure for address, with street and pincode fields.</p><p><em>Arrays</em></p><p>You can also define an array of objects by appending [] to the object type. This signifies an array where each element conforms to the PersonalInformation type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjZW08BQq0L9JXdDo-pWmw.png" /><figcaption>defining type of array of objects</figcaption></figure><p>Here, PersonalInformation[] refers to an array where each element follows the PersonalInformation type structure.</p><p><strong>Parameters and Return Values in Functions</strong></p><p>We have already seen this in the earlier example, taking the same example here we define the parameter grandTotal to be a number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RlJh4CRG3x_9eGmhXvAswQ.png" /></figure><p>Also, the return type for this function can be specified as number as follows,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_16aGe7d3ZcdRw7Wg8ivow.png" /><figcaption>return type of the function is defined</figcaption></figure><p>So, TypeScript is like your code’s bodyguard — keeping types in check and avoiding chaos! You can set strict rules, make certain fields optional, mix types, and more custom ways. But if you don’t define a type, TypeScript defaults to any, which is basically JavaScript’s wild party. So, use types wisely and let TypeScript keep your code neat and safe!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a90682449f16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Bean Instantiation in Spring Boot: Eager vs Lazy Initialization]]></title>
            <link>https://medium.com/@sanjanarajbk/understanding-bean-instantiation-in-spring-boot-eager-vs-lazy-initialization-619f527535cb?source=rss-752a01009e31------2</link>
            <guid isPermaLink="false">https://medium.com/p/619f527535cb</guid>
            <category><![CDATA[lazy-loading]]></category>
            <category><![CDATA[instantiation]]></category>
            <category><![CDATA[beans]]></category>
            <category><![CDATA[eager-loading]]></category>
            <category><![CDATA[spring-bean]]></category>
            <dc:creator><![CDATA[Sanjana Raj BK]]></dc:creator>
            <pubDate>Sat, 04 May 2024 09:15:44 GMT</pubDate>
            <atom:updated>2024-05-04T09:15:44.458Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>To make it simplified <strong>bean</strong> is nothing but an object of a particular class or a component in the application.</p><p>First things first, Have you ever questioned <em>when does the </em><strong><em>initialization</em></strong><em>(simply means creating the bean or object of the class) of the bean occur is it when the application starts(</em><strong><em>eager initialization</em></strong><em>) or when the bean actually is referenced anywhere in your application(</em><strong><em>lazy initialization</em></strong><em>) </em>? The answer to this is Both.</p><p>Now the question <em>how</em>? That is because you can configure the way you want your bean to be instantiated but <strong>by default it is easy <em>initialization</em></strong> of the bean.</p><h3>In Action</h3><p>Let’s see how you can configure it, set up a basic spring boot application having spring-boot-starter dependency.</p><pre>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter&#39;<br>}</pre><pre>package com.example.beandemo;<br><br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br><br><br>@SpringBootApplication<br><br>public class BeanApplication {<br><br>    public static void main(String[] args) {<br>       SpringApplication.run(BeanApplication.class, args);<br>    }<br><br></pre><p>Lets have a component class called vehicle.</p><pre>package com.example.beandemo;<br><br>import org.springframework.stereotype.Component;<br><br>@Component<br>public class Vehicle {<br><br>    private  final String name = &quot;Honda&quot;;<br><br>    public Vehicle() {<br>        System.out.println(&quot;early instantiation is the default &quot;);<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br>}</pre><p>When you run the spring boot application you can see the logs as follows which means by default your beans get instantiated when your application runs even before it is referenced anywhere in the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qaTaJiUT98fE2oUGO2xeA.png" /></figure><p>Now adding an annotation for the vehicle component indicating lazy instantiation will work the other way.</p><pre>@Component<br>@Lazy<br>public class Vehicle</pre><p>Run your spring boot application and now you don’t see the line “early instantiation is the default ” because it will only be instantiated when it referenced which we will look further.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f4pINgjN8A6YXITyAGOEpQ.png" /></figure><p>Lets have another class Person which has a Vehicle object and the remaining code remains the same.Do remember by default person will be eagerly instantiated which means Vehicle will be referenced from the Person class making it get instantiated which is nothing but lazy instantiation <em>i.e</em>, getting instantiated only when required.</p><pre>package com.example.beandemo;<br><br>import org.springframework.stereotype.Component;<br><br>@Component<br>public class Person {<br>    private Vehicle vehicle;<br><br>    public Person(Vehicle vehicle) {<br>        this.vehicle = vehicle;<br>    }<br><br>    public Vehicle getVehicle() {<br>        return vehicle;<br>    }<br>}</pre><p>And when the application runs the log will be as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BOcnonENDcz7PuCh3V_46g.png" /></figure><h3>Conclusion</h3><p>It’s important to strike a balance in Spring Boot applications when it comes to bean instantiation. Eagerly instantiating all beans can consume excessive memory, while lazily instantiating all beans can lead to dependency issues and application complexities. Finding the right balance is key for optimal application performance and maintainability</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=619f527535cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Starter to Authorization using Okta in Spring boot application]]></title>
            <link>https://medium.com/@sanjanarajbk/starter-to-authorization-using-okta-in-spring-boot-application-eb557adfd2c0?source=rss-752a01009e31------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb557adfd2c0</guid>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[okta]]></category>
            <dc:creator><![CDATA[Sanjana Raj BK]]></dc:creator>
            <pubDate>Sun, 28 Apr 2024 05:32:18 GMT</pubDate>
            <atom:updated>2024-04-28T05:36:38.408Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Authorization</em> simply means if the authenticated user has the permission to access certain resources can also be called as limiting the scope , scope here refers to the access of the api.</p><h3>Okta set-up</h3><p>Firstly we login to the <em>admin dashboard</em> in okta, you can login through this link <a href="https://developer.okta.com/login/">https://developer.okta.com/login/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oTArFYW6GrUFS_9_W6zg6Q.png" /></figure><p>when ever a service wants to use the API it has to authenticate itself by providing the <em>client secrets</em> (clientID, clientSecret) which in turn will get a token proving its identity.</p><p>To get your client secrets in the dashboard Applications-&gt;Applications-&gt; <em>Create new app Integration-</em>&gt;API services and note down your <strong>client secrets</strong>.</p><p>Navigate your way through Security-&gt; API which will lead to the below window giving out details on the authorization server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h7esDH-m_oiP62hXXN6rhQ.png" /></figure><p>The <strong>issuer URI</strong> will have the unique url specified for your<em> authorization server</em> which will be used in the properties file of the application to configure the application to use this default authorization server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5oc99n7tXS8WWhgv-X-55w.png" /></figure><p>Now let’s add custom scopes which will let us restrict access based on the scope click on the default name highlighted in blue in authorization sever tab and go to the scopes tab -&gt; Add scope.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Az6OeyTot-3yYHoEaNvUw.png" /></figure><p>Create two scopes whoami and restricttoroles to test out the access of the scopes.Now let’s start creating our spring boot project,</p><h3><strong>SpringBoot Application set-up</strong></h3><p>Go to <a href="https://start.spring.io/">springIntializr</a> , spring web and okta dependencies are configured click generate by specifying details on your project metadata.</p><ol><li>Configure your application properties with the issuer url of the authorization server of okta as follows:</li></ol><pre>spring.application.name=demo<br>server.port=8081<br>spring.security.oauth2.resourceserver.jwt.issuer-uri=https://${yourOktaDomain}/oauth2/default</pre><p>${yourOktaDomain} can be accessed by clicking on profile icon on the top right corner which ends with “okta.com” in your okta dashboard.</p><p>2. Create a sample controller having get mappings which will let us help us check if the custom scopes are working.</p><pre>package com.example.demo;<br><br>import org.springframework.security.core.Authentication;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController<br>public class SampleController {<br><br>    @GetMapping(&quot;/api/whoami&quot;)<br>    public String whoami(Authentication authentication) {<br>        return authentication.getDetails().toString();<br>    }<br><br><br>}</pre><p>3. Create a configuration class using the <em>@configuration</em> and creating a bean to handle the permissions for different api’s by providing the details on the scope.</p><pre>package com.example.demo;<br><br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.http.HttpMethod;<br>import org.springframework.security.config.Customizer;<br>import org.springframework.security.config.annotation.web.builders.HttpSecurity;<br>import org.springframework.security.web.SecurityFilterChain;<br><br>@Configuration<br>public class Config {<br>    @Bean<br>    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {<br>   <br>        return http.authorizeHttpRequests(<br>                        (authz)-&gt; authz.requestMatchers(HttpMethod.GET, &quot;/api/whoami&quot;)<br>                                .hasAuthority(&quot;SCOPE_restricttoroles&quot;)<br>                                .anyRequest()<br>                                .authenticated())<br>                .oauth2ResourceServer((oauth2) -&gt; oauth2<br>                        .jwt(Customizer.withDefaults())<br>                ).build();<br><br>    }<br><br>}</pre><p>Here we are trying to configure /api/whomai to be accessed for scope restricttoroles only.</p><h3><strong>Testing through Insomnia</strong></h3><h4><strong>whoami scope:</strong></h4><p>Without providing the bearer token which is the jwt token that validates your permission to access the api you won’t be able to access the api and it throws <em>401 Unauthorized by default</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JfRMZL_n_LlmK7blIc8zGQ.png" /></figure><p>To get the token make a post request to <a href="https://${youroktadomain}/oauth2/$%7ByourAuthServerName%7D/v1/token">https://${yourOktaDomain}/oauth2/${yourAuthServerName}/v1/token</a> , yourAuthServerName is default.</p><p>For the post request need to add the following:</p><h4><strong>Query params</strong></h4><p>grant_type : client_credentials , scope: whoami</p><h4><strong>Auth type</strong></h4><p>Choose basic auth has the auth type and provide <em>client ID</em> as username and <em>client secret</em> as the password.</p><h4><strong>Headers</strong></h4><p>Cache-Control : no-cache , Content-Type : application/x-www-form-urlencoded</p><p>You’ll get a response code of 200 OK with response body having field access_token, now having this access token pasted to the token field in the Auth tab having set the auth type as bearer you will be able to access this token but since restricttoroles scope is configured with this api you will get <em>403 Forbidden response code</em> to indicate this scope does not have permission to access this api.</p><h4><strong>restricttoroles scope:</strong></h4><p>You can try out the same with <em>restricttoroles scope</em> as well and try accessing this api through the access token you get and you will be able to access this api.</p><p>This is how certain api’s are restricted to only certain set of users and they are authorized through these json-web-tokens.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb557adfd2c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>