<?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 Noor Al Din Ahmed on Medium]]></title>
        <description><![CDATA[Stories by Noor Al Din Ahmed on Medium]]></description>
        <link>https://medium.com/@nooraldinahmed?source=rss-30cfdbfe0910------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BOpk-AqdArplN_qVBypRTw@2x.jpeg</url>
            <title>Stories by Noor Al Din Ahmed on Medium</title>
            <link>https://medium.com/@nooraldinahmed?source=rss-30cfdbfe0910------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 19:08:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nooraldinahmed/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[Getting started with Python ASYNCIO [Part-1]]]></title>
            <link>https://medium.com/@nooraldinahmed/getting-started-with-python-asyncio-part-1-9eee7944f9f7?source=rss-30cfdbfe0910------2</link>
            <guid isPermaLink="false">https://medium.com/p/9eee7944f9f7</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[asyncio]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Noor Al Din Ahmed]]></dc:creator>
            <pubDate>Fri, 04 Feb 2022 21:31:06 GMT</pubDate>
            <atom:updated>2022-02-04T21:31:06.336Z</atom:updated>
            <content:encoded><![CDATA[<p>Python is an interpreted language. Which means by default it executes code line by line freely at runtime. But sometimes when you execute your code there are certain places where your whole code blocks for a request to finish or it gets stuck due to complex computations. And then all of a sudden your whole code blocks which makes your whole program block and you wish there was a way to run the damn thing seperately on its own and somehow later notified you when it finished. And in the mean time you could execute other code and comeback to it later when you got notified of the finished task. <br>This is exactly what asyncio does for you. You can run your code concurently along side other code in harmony without blocking each other.</p><p>We’ll be using Python 3.10 for this article where the asyncio library has been made a lot easier to use. I cannot guarantee the workability of your code if you use other versions.</p><p>Let’s jump in.</p><p>First things first. Let’s get familiarized about the terms used for the asyncio library. I will explain everything at a beginner level and will try to keep things as simple to grasp as possible. If you want to dive deeper into this topic, check python’s official documentions where everything is explained in details.</p><p><strong>Couroutines: </strong>These are just regular functions with the async keyword at the beginning and is awaitable. Coroutines can execute other coroutines inside it with the await keyword. We will create these to control the flow of asynchronous code.</p><p><strong>Await: </strong>It’s a keyword used to give control back to the event loop and waits until a task is done or has returned with a result.</p><p><strong>Event loop:</strong> When running a coroutine where an await keyword is encountered the event loop gets the control. It then checks if a particular awaited task is done. If it isn’t, it moves on to check for other tasks that are done or has returned some result. This is when the loop gives the control back to the couroutine to execute rest of the code inside it until another await is encountered.</p><figure><img alt="eventloop" src="https://cdn-images-1.medium.com/max/898/1*mhopIIMmI5SZgGHQXZTbwQ.png" /></figure><h3>Two coroutines running together</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7d3f34fd85328d1e705b62db4945181/href">https://medium.com/media/c7d3f34fd85328d1e705b62db4945181/href</a></iframe><p>Output:</p><pre>coro1()<br>coro2()<br>coro1()<br>coro1()<br>coro2()<br>coro1()<br>coro1()<br>coro2()<br>coro2()<br>coro2()</pre><p>You can run the code as it is. The coroutine coro1() has run 5 times once every second. And the coroutine coro2() has run 5 times every 2 seconds. The part where we awaited asyncio.sleep() is where the event loop recieved control and the coroutine stopped and waited until the event loop gave the control back after the time was done. And in the mean time gave control to the other coroutine. And the cycle repeated for each iteration.</p><p>Please note that there’s no guarantee what coroutine will run first when they both execute simultaneously at the same time. This is when the infamous “race condition” occur if one of the coroutines depend on the other somehow.</p><p>Although it seems like task 2 should run after task 1 is done, this is not the case. Both tasks have already started the moment we called asyncio.create_task() . We were merely awaiting for them to finish or else the program would have exited immedietly.</p><p><em>Note: If you know for sure how long your coroutines should run you can even omit the </em><em>await task1 and </em><em>await task2 . Instead prevent the program from exiting by adding </em><em>await asyncio.sleep(YOUR_TIME_OUT_VALUE) in its place.</em></p><p>To <strong>manually cancel</strong> the tasks before they finish you can call task1.cancel() or task2.cancel().</p><h3><strong>Turning Blocking code into non-blocking awaitable code</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67452186a375872a17efa984cadb5c8a/href">https://medium.com/media/67452186a375872a17efa984cadb5c8a/href</a></iframe><p>Output:</p><pre>Type something: coro1()<br>coro2()<br>coro1()<br>coro1()<br>coro2()<br>coro1()<br>coro1()<br>coro2()<br>coro2()<br>coro2()<br>Hello world<br>Your input is:  Hello world</pre><p>There are a few interesting things going on here.</p><ol><li>We have writen the program in a way that three coroutines are running simultaneously.</li><li>We have only awaited task3 but task1 and task2 are also running. If you had provided any input through the console before task1 or task2 was done the program would have exited because there won’t be anything blocking main().</li><li>If you had called input() directly instead of using asyncio.to_thread() . The whole program would have blocked because as we know from before the await keyword tells the event loop to switch between tasks.</li><li>The asyncio.to_thread() does another thing that is interesting. It creates it’s own thread seperate from the main thread and does it’s computations independently there and returns a result to the event loop when it’s done.</li></ol><p>This was the end of part 1. If this article gets enough response I’ll write a part 2 where I’ll talk about sharing data between coroutines. And then may be a part 3 with practical applications of asyncio with examples.</p><p>Please follow me here and provide feedbacks. I’d love to hear from you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9eee7944f9f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Very basic JWT Authentication with Golang]]></title>
            <link>https://medium.com/@nooraldinahmed/very-basic-jwt-authentication-with-golang-3516b21c2740?source=rss-30cfdbfe0910------2</link>
            <guid isPermaLink="false">https://medium.com/p/3516b21c2740</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Noor Al Din Ahmed]]></dc:creator>
            <pubDate>Sat, 01 Jan 2022 21:20:37 GMT</pubDate>
            <atom:updated>2022-01-08T20:28:28.130Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*9pWUdYPAwCQoWdEnvZli4A.jpeg" /></figure><p>If you ever need stateless user authentication with your backend that is simple and works with minimal effort, what other way is there but to use JSON Web Tokens or JWT in short.</p><p>This blog exists to serve the purpose of sharing this information to you guys and also as something I can comeback to if I ever need to brush up.</p><p>Let’s get started!</p><p>First, let’s check out how we can create JWT tokens in Golang and what they look like.</p><p>Get the JWT package using:</p><p>go get github.com/golang-jwt/jwt/v4</p><p>Create a struct to hold your Claims. This determines how your decoded tokens would be structured. The *jwt.RegisteredClaims include the basic claims suchexp , sub , jti , aud , etc imported from the JWT package. The UserInfo interface{} is whatever you include inside your token. This is usually a bunch of key:value pair.</p><ul><li><em>Never populate the struct with any sensitive information such as the user’s password or secret keys.</em></li></ul><pre>type MyJWTClaims struct {<br>    *jwt.RegisteredClaims<br>    UserInfo interface{}<br>}</pre><p>Globaly define a randomly generated secret key in a byte array to sign the JWT Token with.</p><pre>// Generate your own secret key!</pre><pre>var secret = []byte(&quot;can-you-keep-a-secret?&quot;)</pre><p>Now lets make a function to Create the Token!</p><pre>func CreateToken(sub string, userInfo interface{}) (string,error) {<br>// Get the token instance with the Signing method</pre><pre>    token := jwt.New(jwt.GetSigningMethod(&quot;HS256&quot;))</pre><pre>// Choose an expiration time. Shorter the better</pre><pre>    exp := time.Now().Add(time.Hour * 24)</pre><pre>// Add your claims</pre><pre>    token.Claims = &amp;MyJWTClaims{<br>        &amp;jwt.RegisteredClaims{</pre><pre>// Set the exp and sub claims. sub is usually the userID<br>        ExpiresAt: jwt.NewNumericDate(exp),<br>        Subject:   sub,<br>    },<br>    userInfo,<br>  }</pre><pre>// Sign the token with your secret key</pre><pre>    val, err := token.SignedString(secret)<br>    <br>    if err != nil {</pre><pre>// On error return the error</pre><pre>        return &quot;&quot;, err<br>    }</pre><pre>// On success return the token string</pre><pre>    return val, nil<br>}</pre><p>The next snippet is for verifying the token and retrieving the claims from the JWT string.</p><pre>func GetClaimsFromToken(tokenString string) (jwt.MapClaims, error) {</pre><pre>token, err := jwt.Parse(tokenString, func(token *jwt.Token)   (interface{}, error) {</pre><pre>        if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {</pre><pre>        return nil, fmt.Errorf(&quot;unexpected signing method: %v&quot;,       token.Header[&quot;alg&quot;])</pre><pre>        }</pre><pre>    return secret, nil</pre><pre>})</pre><pre>if err != nil {</pre><pre>    return nil, err</pre><pre>}</pre><pre>if claims, ok := token.Claims.(jwt.MapClaims); ok &amp;&amp; token.Valid {</pre><pre>    return claims, nil</pre><pre>}</pre><pre>return nil, err</pre><pre>}</pre><p>Now lets make a middleware to verify the JWT on a protected resource.</p><pre>func AuthenticationMW(next http.HandlerFunc) http.HandlerFunc {</pre><pre>return func(w http.ResponseWriter, r *http.Request) {</pre><pre>    auth_header := r.Header.Get(&quot;Authorization&quot;)</pre><pre>    if !strings.HasPrefix(auth_header, &quot;Bearer&quot;) {</pre><pre>        http.Error(w, &quot;Not Authorized&quot;, http.StatusUnauthorized)</pre><pre>        return<br>    }</pre><pre>    tokenString := strings.TrimPrefix(auth_header, &quot;Bearer &quot;)</pre><pre>    claims, err := GetClaimsFromToken(tokenString)</pre><pre>    if err != nil {</pre><pre>        http.Error(w, err.Error(), http.StatusUnauthorized)</pre><pre>        return<br>}</pre><pre>    r = r.WithContext(SetJWTClaimsContext(r.Context(), claims))</pre><pre>    next(w, r)</pre><pre>}</pre><pre>}</pre><p>Now what does this line do?</p><pre>r = r.WithContext(SetJWTClaimsContext(r.Context(), claims))</pre><p>This adds the decoded claims (sub, userId, username, full_name, etc) to the response object so that you can have access to it later in the request handler function where you are protecting your resources. To keep things clean we will create the SetJWTClaimsContext and JWTClaimsFromContext functions ourselves. Let begin then…</p><pre>type claimskey int<br>var claimsKey claimskey</pre><pre>func SetJWTClaimsContext(ctx context.Context, claims jwt.MapClaims) context.Context {</pre><pre>    return context.WithValue(ctx, claimsKey, claims)</pre><pre>}</pre><pre>func JWTClaimsFromContext(ctx context.Context) (jwt.MapClaims, bool) {<br>    claims, ok := ctx.Value(claimsKey).(jwt.MapClaims)<br>    return claims, ok<br>}</pre><p>Below is how you access the claims that was added to the http.request object in the middleware. The returned claim is a map of key:value pairs to help you identify the client/user.</p><pre>protectedHandler := func(w http.ResponseWriter, r *http.Request){</pre><pre>    claims, ok := JWTClaimsFromContext(r.Context())</pre><pre>// Rest of the code<br>...<br>}</pre><p>Okay! Now that we have all the pieces of the puzzle. Lets put them together with Gorilla Mux and the net/http package!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b190c6c40c2bfd542745f6f6794c063/href">https://medium.com/media/1b190c6c40c2bfd542745f6f6794c063/href</a></iframe><p>Now if you run the program you can check if the server is running at http://localhost:8080/ . It should respond with Status OK .</p><p>Get the JWT token from http://localhost:8080/login . For simplicity, any username or password is accepted without any validation. It has to be aPOST request and the content type should be application/json with the fields username &amp; password</p><p>Once you have the token you can inspect the claims by copying the token to the debugger available at <a href="https://jwt.io/">https://jwt.io/</a></p><p>Next, hit http://localhost:8080/resource with POST or GET method along the header Authorization: Bearer &lt;your-jwt-token&gt; . If the token is valid the server should return the token claims. If no header or token is passed or if the token is invalid you should error out with Not Authorized.</p><p>And we are done for today!</p><p>This blog did not cover a lot of stuff such as Refresh token, JWKS, database integration, setting up environment variables, how and where to store the tokens, etc. I’m planning to make more articles slowly but steadily that would includes these.</p><p>This is my first blog on medium so any feedback will be highly appreciated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3516b21c2740" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>