<?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 Sanad Haj on Medium]]></title>
        <description><![CDATA[Stories by Sanad Haj on Medium]]></description>
        <link>https://medium.com/@hajsanad?source=rss-4c123c2c83b0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*j4DoLxU4EeK6lkNxFxxmLQ.jpeg</url>
            <title>Stories by Sanad Haj on Medium</title>
            <link>https://medium.com/@hajsanad?source=rss-4c123c2c83b0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 08:45:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hajsanad/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[Hitless TLS Certificate Rotation in Go]]></title>
            <link>https://medium.com/better-programming/hitless-tls-certificate-rotation-in-go-8f24a26ec267?source=rss-4c123c2c83b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f24a26ec267</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Sanad Haj]]></dc:creator>
            <pubDate>Sun, 05 Jun 2022 18:29:20 GMT</pubDate>
            <atom:updated>2022-06-20T09:04:12.105Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this tutorial, we’ll be discussing how to handle certificate rotation in Golang without any downtime.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zoXYVe2K3211cwsw" /><figcaption>Photo by <a href="https://unsplash.com/@joannakosinska?utm_source=medium&amp;utm_medium=referral">Joanna Kosinska</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>What is certificate rotation and why it&#39;s needed?</strong></h3><p>Certificate rotation means the replacement of existing certificates with new ones.</p><p>There is an old TLS maxim that states that:</p><blockquote>If a certificate got issued, it will have to be rotated.</blockquote><p>Well, It’s needed when:</p><ul><li>Any certificate expires.</li><li>A new CA authority is substituted for the old; thus requiring a replacement root certificate for all services.</li><li>New or modified constraints need to be imposed on one or more certificates.</li><li>A security breach has occurred, such that existing certificate chains can no longer be trusted.</li></ul><p>Rotating TLS certificates manually may quickly get out of hand — particularly when you have to manage hundreds of certificates — and becomes completely unmanageable if you issue certificates that expire within hours, instead of months.</p><p><a href="https://github.com/shaj13/tlsreconciler">tlsreconciler</a> is here to help with that, by reloading rotated certificate including root CA and providing TLS reconciliation to connections in real-time and without restarting the application.</p><h3><strong>Code</strong></h3><p>We are going to start by creating our project.</p><pre>mkdir medium &amp;&amp; cd medium &amp;&amp; go mod init medium &amp;&amp; touch main.go</pre><p>This will create a new directory called “medium” and initialize the project with go.mod.</p><p>We also need to install <a href="https://github.com/shaj13/tlsreconciler">tlsreconciler</a>.</p><pre>go get github.com/shaj13/tlsreconciler</pre><p>Before we write any <strong>certificate rotation </strong>code we need to write some mandatory code that describes our tutorial program.</p><pre>package main<br><br>import (<br>	&quot;crypto/tls&quot;<br>         &quot;log&quot;<br>	&quot;net/http&quot;</pre><pre>)<br><br>func HelloMedium(w http.ResponseWriter, req *http.Request) {<br>	w.Header().Set(&quot;Content-Type&quot;, &quot;text/plain&quot;)<br>	w.Write([]byte(&quot;Hello Medium.\n&quot;))<br>}<br><br>func main() {<br><br>	config := new(tls.Config)<br>	server := http.Server{<br>		Addr:      &quot;:443&quot;,<br>		Handler:   http.HandlerFunc(HelloMedium),<br>		TLSConfig: config,<br>	}<br><br>  	err := server.ListenAndServeTLS(&quot;&quot;, &quot;&quot;)<br>        if err != nil {<br>            log.Fatal(err)<br>        }</pre><pre>}</pre><p>Running the program will return the following error.</p><pre>open : no such file or directory</pre><p>Basically, this error returned from http.ListenAndServeTLS because we have initialized server with empty tls.Config, So it&#39;s fallback to certs paths arguments that are not defined, will fix that later.</p><p>We need to make our program to catch SIGHUB so we can reload the rotated certs.</p><p>This can be done, like so:</p><pre>sigc := make(chan os.Signal, 1)<br>defer close(sigc)<br><br>signal.Notify(sigc, syscall.SIGHUP)</pre><p>Now, we need to configure tlsreconciler, like so.</p><pre>sig := tlsreconciler.WithSIGHUPReload(sigc)<br>certs := tlsreconciler.WithCertificatesPaths(&quot;./cert&quot;, &quot;./key&quot;, &quot;&quot;)<br>cb := tlsreconciler.WithOnReload(func(c *tls.Config) {<br>      log.Println(&quot;TLS certificates rotated !!&quot;)<br>})</pre><p>The above create tlsreconciler configuration to reload certificate when an SIGHUB received and call our callback function to print a pretty log entry beside to reload certs from the given paths.</p><p>Its time to connect the dots, we need to replace the following line:</p><pre>config := new(tls.Config)</pre><p>With returned tls.Config from tlsreconciler:</p><pre>config := tlsreconciler.TLSConfig(sig, certs, cb)</pre><p>Your file now should look like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/695d9fa8aea676162e7a4914c3854135/href">https://medium.com/media/695d9fa8aea676162e7a4914c3854135/href</a></iframe><h3><strong>Testing Our Code</strong></h3><p>First let&#39;s generate a certificate and private key:</p><pre>openssl genrsa -out ./key 2048<br>openssl req -new -x509 -sha256 -key ./key -out ./cert -days 3650</pre><p>Now let&#39;s run our program:</p><pre>go build main.go<br>./main </pre><p>From a different shell let&#39;s send an HTTPS request:</p><pre>curl -k https://127.0.0.1:443/</pre><p>In the program logs, you will find out the following log entry “TLS certificates rotated !!”.</p><p>This happened because tlsreconciler has reloaded certificate for the first time, running more curls will no longer print the above log entry.</p><p>Now let&#39;s check the rotation, for that we will use openssl to show certificates</p><pre>openssl s_client -showcerts -connect 127.0.0.1:443 2&gt;&amp;1|openssl x509 -noout -serial</pre><p>The above command will print the certificate serial number.</p><p>Let’s rotate certificates by generating new ones using openssl and sending SIGHUP to our program</p><pre>rm -rf ./key ./cert <br>openssl genrsa -out ./key 2048<br>openssl req -new -x509 -sha256 -key ./key -out ./cert -days 3650 <br>kill -SIGHUP &lt;PID&gt;</pre><p>Now let&#39;s verify the serial number is different from the previous one</p><pre>openssl s_client -showcerts -connect 127.0.0.1:443 2&gt;&amp;1|openssl x509 -noout -serial</pre><p>I hope you found this article helpful. You can read more about tlsreconciler can be found on <a href="https://github.com/shaj13/tlsreconciler"><em>GitHub</em></a><em> </em>and <a href="https://pkg.go.dev/github.com/shaj13/tlsreconciler"><em>GoDoc</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f24a26ec267" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/hitless-tls-certificate-rotation-in-go-8f24a26ec267">Hitless TLS Certificate Rotation in Go</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Distributed and Replicated State Machine in Golang Using Raft]]></title>
            <link>https://medium.com/better-programming/writing-distributed-and-replicated-state-machine-in-golang-using-raft-dad79b58cd3a?source=rss-4c123c2c83b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/dad79b58cd3a</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Sanad Haj]]></dc:creator>
            <pubDate>Fri, 20 May 2022 13:25:08 GMT</pubDate>
            <atom:updated>2022-06-20T09:12:45.866Z</atom:updated>
            <content:encoded><![CDATA[<h4>Well, you may hear a lot about “distributed system” or “raft” itself. But, you may wonder how to use it.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qgwLvGVgYIhEsMot" /><figcaption>Photo by <a href="https://unsplash.com/@joshuaearle?utm_source=medium&amp;utm_medium=referral">Joshua Earle</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this tutorial, we’ll be discussing how to handle kv database running in cluster mode using Golang and <a href="https://github.com/shaj13/raft">Raft library</a>. This tutorial is more focused on the code and using raft clusters rather than discussing the raft algorithms.</p><h3><strong>What is Raft?</strong></h3><p>Raft is a protocol with which a cluster of nodes can maintain a replicated state machine.</p><p>The state machine is kept in sync through the use of a replicated log. However, the details of the Raft protocol are outside the scope of this tutorial, For more details on Raft, see<a href="https://raft.github.io/raft.pdf"> In Search of an Understandable Consensus Algorithm</a></p><h4><strong>Golang implementation of the raft</strong></h4><p>Raft algorithm comes in search of an understandable consensus algorithm. Unfortunately, most of the go libraries out there required a deep knowledge of their implementation and APIs.</p><p>The raft library we’ll be using in this tutorial was born to align with the understandability raft principle and its sole purpose is to provide consensus with the minimalistic, simple, clean, and idiomatic API.</p><p>Etcd Raft is the most widely used Raft library in production. But, it follows a minimalistic design philosophy by only implementing the core raft algorithm which leaves gaps and ambiguities.</p><p>So, instead of reinventing the wheel, <a href="https://github.com/shaj13/raft">shaj13/raft</a> library uses etcd raft as its core.</p><p>That’s how you can benefit from the power and stability of etcd raft, with an understandable API. Indeed, it keeps your focus on building awesome software.</p><h3>Creating our project</h3><p>We are going to start by creating our project.</p><pre>mkdir raft &amp;&amp; cd raft &amp;&amp; go mod init raft &amp;&amp; touch raft.go</pre><p>This will create a new directory called raft and initialize the project with go.mod.</p><h3>Our first lines of code</h3><p>Before we write any code we need to write some mandatory code to make the program run.</p><pre>package main<br>import (<br>  &quot;log&quot;<br>)<br>func main() {<br>  log.Println(&quot;Raft !!&quot;)<br>}</pre><h3>Creating our process command line</h3><p>We are going to remove the line that prints out Raft!!, add the flag package and initialize it.</p><pre>package main <br>import &quot;flag&quot;<br>func main() {<br>   addr := flag.String(&quot;raft&quot;, &quot;&quot;, &quot;raft server address&quot;)<br>   join := flag.String(&quot;join&quot;, &quot;&quot;, &quot;join cluster address&quot;)<br>   api := flag.String(&quot;api&quot;, &quot;&quot;, &quot;api server address&quot;)<br>   state := flag.String(&quot;state_dir&quot;, &quot;&quot;, &quot;raft state directory (WAL, Snapshots)&quot;)<br>   flag.Parse() <br>}</pre><h3>Creating our kv database</h3><p>We are going to implement a struct named stateMachine define kv database that reads and applies a key value alongside taking database snapshot and restoring it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b41b28c01f6d7217abc5ca6a26da8eb/href">https://medium.com/media/3b41b28c01f6d7217abc5ca6a26da8eb/href</a></iframe><h3>Creating our endpoints</h3><p>We are going to add the gorilla mux package and initialize the router inside the main function.</p><pre>router := mux.NewRouter()</pre><p>Now we are going to establish the endpoints of our API, the way we will set this up is to create all of our endpoints in the main function, every endpoint needs a function to handle the request and we will define those below the main function.</p><pre>router.HandleFunc(&quot;/&quot;, http.HandlerFunc(save)).Methods(&quot;PUT&quot;, &quot;POST&quot;)<br>router.HandleFunc(&quot;/{key}&quot;, http.HandlerFunc(get)).Methods(&quot;GET&quot;)<br>router.HandleFunc(&quot;/mgmt/nodes&quot;, http.HandlerFunc(nodes)).Methods(&quot;GET&quot;)<br>router.HandleFunc(&quot;/mgmt/nodes/{id}&quot;, http.HandlerFunc(removeNode)).Methods(&quot;DELETE&quot;)</pre><h3>Routes handlers</h3><p>Now we just need to define the functions that will handle the requests.<br>Before we start we need to declare two variables to allow routes access data.</p><ul><li>Node represents raft process</li><li>FSM represents raft process state machine</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/353f932264ca261c0766fd52c764e9fd/href">https://medium.com/media/353f932264ca261c0766fd52c764e9fd/href</a></iframe><h3>Creating our raft node and server</h3><p>In the main function and below the router we need to declare our raft node and gRPC server to allow current raft node to communicate with other raft nodes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04843718b26175032be31de747c7bebb/href">https://medium.com/media/04843718b26175032be31de747c7bebb/href</a></iframe><p>Your file should now look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b493f45b62a21aae930f27a7b56d60e/href">https://medium.com/media/4b493f45b62a21aae930f27a7b56d60e/href</a></iframe><h3>Testing our code</h3><h4>Building raft cluster</h4><pre>go mod tidy &amp;&amp; go build raft.go </pre><h4>Running single node raft</h4><p>First, start a single-member cluster of raft:</p><pre>./raft -state_dir=$TMPDIR/1 -raft :8080 -api :9090</pre><p>Each raft process maintains a single raft instance and a key-value server.</p><p>raft server address (-raft), state dir (-state_dir), and http key-value server address (-api) are passed through the command line.</p><p>Next, store a value (“medium”) to a key (“hello”):</p><pre>curl -L http://127.0.0.1:9090/ -X PUT -d &#39;{&quot;Key&quot;:&quot;hello&quot;, &quot;Value&quot;:&quot;medium&quot;}&#39;</pre><p>Finally, retrieve the stored key:</p><pre>curl -L <a href="http://127.0.0.1:9090/hello">http://127.0.0.1:9090/hello</a></pre><h4>Running a local cluster</h4><p>Let&#39;s bring two additional raft instances.</p><pre>./raft -state_dir $TMPDIR/2 -raft :8081 -api :9091 -join :8080<br>./raft -state_dir $TMPDIR/3 -raft :8082 -api :9092 -join :8080</pre><p>Now it’s possible to write a key-value pair to any member of the cluster and likewise retrieve it from any member.</p><h4>Fault Tolerance</h4><p>To test cluster recovery, write a value “foo” to key “foo”:</p><pre>curl -L <a href="http://127.0.0.1:9090/">http://127.0.0.1:9090/</a> -X PUT -d &#39;{&quot;Key&quot;:&quot;foo&quot;, &quot;Value&quot;:&quot;foo&quot;}&#39;</pre><p>Next, stop a node (9092) and replace the value with “bar” to check cluster availability:</p><pre>curl -L <a href="http://127.0.0.1:9090/">http://127.0.0.1:9090/</a> -X PUT -d &#39;{&quot;Key&quot;:&quot;foo&quot;, &quot;Value&quot;:&quot;bar&quot;}&#39;<br>curl -L <a href="http://127.0.0.1:9090/foo">http://127.0.0.1:9090/foo</a></pre><p>Finally, bring the node back up and verify it recovers with the updated value “bar”:</p><pre>curl -L <a href="http://127.0.0.1:9092/foo">http://127.0.0.1:9092/foo</a></pre><h4>Cluster Reconfiguration</h4><p>Nodes can be added, removed, or updated from a running cluster. Let’s remove node using requests to the REST API.</p><p>First, list all raft cluster nodes, and get node id.</p><pre>curl -L <a href="http://127.0.0.1:9090/mgmt/nodes">http://127.0.0.1:9090/mgmt/nodes</a></pre><p>Then remove a node using a DELETE request:</p><pre>curl -L http://127.0.0.1:9090/&lt;ID&gt; -X DELETE</pre><p>The node will shut itself down once the cluster has processed this request.</p><p>More about raft library can be found on <a href="https://github.com/shaj13/raft">GitHub</a> and <a href="https://pkg.go.dev/github.com/shaj13/raft">GoDoc</a>. Thank you so much for reading. I hope you found this article helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dad79b58cd3a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/writing-distributed-and-replicated-state-machine-in-golang-using-raft-dad79b58cd3a">Writing Distributed and Replicated State Machine in Golang Using Raft</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes Token Review And Authentication]]></title>
            <link>https://medium.com/@hajsanad/kubernetes-token-review-and-authentication-56e06cc55ed3?source=rss-4c123c2c83b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/56e06cc55ed3</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[go-guardian]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Sanad Haj]]></dc:creator>
            <pubDate>Sat, 05 Sep 2020 18:36:29 GMT</pubDate>
            <atom:updated>2020-09-05T18:39:43.488Z</atom:updated>
            <content:encoded><![CDATA[<p>In building web and REST API application, it is very important to build a system users can trust and rely on.</p><p>Authentication is important because it enables organizations and apps to keep their networks secure by permitting only authenticated users to access its protected resources.</p><p>In this tutorial, We’ll be discussing how pod authenticate pod running in k8s cluster using <a href="https://golang.org/">Golang</a> and <a href="https://github.com/shaj13/go-guardian">Go-Guardian </a>library along with k8s <a href="https://docs.openshift.com/online/pro/rest_api/apis-authentication.k8s.io/v1.TokenReview.html">token review API</a>.</p><h3>Go-Guardian Overview</h3><p>Go-Guardian is a golang library that provides a simple, clean, and idiomatic way to create powerful modern API and web authentication.</p><p>Go-Guardian sole purpose is to authenticate requests, which it does through an extensible set of authentication methods known as strategies.<br> Go-Guardian does not mount routes or assume any particular database schema, which maximizes flexibility and allows decisions to be made by the developer.<br> The API is simple: you provide go-guardian a request to authenticate, and go-guardian invoke strategies to authenticate end-user request.<br> Strategies provide callbacks for controlling what occurs when authentication should succeeds or fails.</p><h3>Why Go-Guardian?</h3><p>When building a modern application, you don’t want to implement authentication module from scratch;<br> you want to focus on building awesome software. go-guardian is here to help with that.</p><p>Here are a few bullet point reasons you might like to try it out:</p><ul><li>provides simple, clean, and idiomatic API.</li><li>provides top trends and traditional authentication methods.</li><li>provides a package to caches the authentication decisions, based on different mechanisms and algorithms.</li><li>provides two-factor authentication and one-time password as defined in <a href="https://tools.ietf.org/html/rfc4226">RFC-4226</a> and <a href="https://tools.ietf.org/html/rfc6238">RFC-6238</a></li></ul><h3>Token Review</h3><p>K8s Token Review attempts to authenticate a token to a known user or service account. In other words, k8s token review API enables access token verification and returning user information.<br>This authentication method makes it easy to introduce apps into a k8s pod and allows the pod to authenticate other pods.</p><h3>Use Case And Token Review Flow</h3><p>assume we have two pods<strong>(A,B)</strong> running in k8s cluster, pods A attempts to access a protected resource in the pod B where the authentication required.<br>To solve the above use case pod B sends an HTTP request to the k8s API server to authenticate pod A. <br>To successfully make HTTP requests to the k8s token review API a bearer token for pod B must be included as an authorization header and pod A access token in request body.</p><pre>curl -k -X &quot;POST&quot; &quot;https://127.0.0.1:8443/apis/authentication.k8s.io/v1/tokenreviews&quot; \<br>     -H &#39;Authorization: Bearer &lt;Pod B Token&gt;&#39; \<br>     -H &#39;Content-Type: application/json; charset=utf-8&#39; \<br>     -d $&#39;{<br>  &quot;kind&quot;: &quot;TokenReview&quot;,<br>  &quot;apiVersion&quot;: &quot;authentication.k8s.io/v1&quot;,<br>  &quot;spec&quot;: {<br>    &quot;token&quot;: &quot;&lt;Pod A Token&gt;&quot;	<br>    }<br>}&#39;</pre><h3>Prerequisite</h3><p><strong><em>Note:</em></strong> if you wish to follow this tutorial without running or setup Kubernetes use the following <a href="https://github.com/shaj13/go-guardian/blob/master/_examples/kubernetes/mock.go">mock </a>and skip this section.</p><p>Before we start our tutorial you must have a running k8s cluster with service-account-lookup flag. This is defaulted to true in Kubernetes 1.7, but any versions prior should ensure the Kubernetes API server is started with this setting.</p><p>We need two service accounts for pod <strong>A </strong>and <strong>B</strong><br>besides grant pod <strong>B </strong>permission to access token review API If Kubernetes is configured to use <strong><em>RBAC </em></strong>roles.</p><pre>$ cat &lt;&lt; EOF &gt; token.yaml <br>apiVersion: v1<br>kind: ServiceAccount<br>metadata:<br>  name: PodA<br>  namespace: default<br>---<br>apiVersion: v1<br>kind: ServiceAccount<br>metadata:<br>  name: PodB<br>  namespace: default<br>---<br>apiVersion: rbac.authorization.k8s.io/v1beta1<br>kind: ClusterRoleBinding<br>metadata:<br>  name: role-tokenreview-binding<br>  namespace: default<br>roleRef:<br>  apiGroup: rbac.authorization.k8s.io<br>  kind: ClusterRole<br>  name: system:auth-delegator<br>subjects:<br>- kind: ServiceAccount<br>  name: PodB<br>  namespace: default <br>EOF</pre><pre>$ kubectl apply -f token.yaml </pre><p>Let’s get access tokens for both pods we will use them later in this tutorial.</p><pre>$ kubectl describe secret  podA<br>$ kubectl describe secret  podB</pre><p><strong><em>Note:</em></strong> To simplify the tutorial we will not deploy our code to Kubernetes, so we will assume our code process as pod <strong>B </strong>and curl as pod <strong>A</strong></p><h3>Creating our project</h3><p>We are going to start by creating our project.</p><pre>mkdir k8s-auth &amp;&amp; cd k8s-auth &amp;&amp; go mod init k8s-auth &amp;&amp; touch main.go</pre><p>This will create a new directory called “k8s-auth” and and initialize the project with go.mod.</p><p>We also need to install gorilla mux, go-guardian.</p><pre>go get github.com/gorilla/mux<br>go get github.com/shaj13/go-guardian</pre><h3>Our first lines of code</h3><p>Before we write any code we need to write some mandatory code to make the program run.</p><pre>package main<br>import (<br>  &quot;log&quot;<br>)<br>func main() {<br>  log.Println(&quot;Auth !!&quot;)<br>}</pre><h3>Creating our endpoints</h3><p>We are going to remove the line that prints out “Auth !!” and add the gorilla Mux package and initialize the router.</p><pre>package main<br>import (<br>  &quot;github.com/gorilla/mux&quot;<br>)<br>func main() {<br>  router := mux.NewRouter()<br>}</pre><p>Now we are going to establish the endpoints of our API, the way we will set this up is to create all of our endpoints in the main function, every endpoint needs a function to handle the request and we will define those below the main function.</p><pre>package main<br>import (<br>  &quot;net/http&quot;<br>  &quot;log&quot;<br>  &quot;github.com/gorilla/mux&quot;<br>)<br>func main() {<br>  router := mux.NewRouter() <br>  router.HandleFunc(&quot;/v1/book/{id}&quot;, getBookAuthor).Methods(&quot;GET&quot;)<br>  log.Println(&quot;server started and listening on <a href="http://127.0.0.1:8080/">http://127.0.0.1:8080</a>&quot;)<br>  http.ListenAndServe(&quot;127.0.0.1:8080&quot;, router)<br>}</pre><p>What I’ve done is to create a route to access a protected resource that returns a book author by id.</p><h3>Route handlers</h3><p>Now we just need to define the functions that will handle the requests.</p><p><strong>getBookAuthor()</strong></p><pre>func getBookAuthor(w http.ResponseWriter, r *http.Request) {    vars := mux.Vars(r)<br>    id := vars[&quot;id&quot;]<br>    books := map[string]string{<br>        &quot;1449311601&quot;: &quot;Ryan Boyd&quot;,<br>        &quot;148425094X&quot;: &quot;Yvonne Wilson&quot;,<br>        &quot;1484220498&quot;: &quot;Prabath Siriwarden&quot;,<br>    }<br>    body := fmt.Sprintf(&quot;Author: %s \n&quot;, books[id])<br>    w.Write([]byte(body))<br>}</pre><p><strong>Your file should now look something like this:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08b68c10bc6642253f22a94658278d70/href">https://medium.com/media/08b68c10bc6642253f22a94658278d70/href</a></iframe><p>Now lets run sample requests to test our code !!</p><pre>curl  -k <a href="http://127.0.0.1:8080/v1/book/1449311601">http://127.0.0.1:8080/v1/book/1449311601</a> <br>Author: Ryan Boyd</pre><h3>Integrate with Go-Guardian</h3><p>first let’s add the following line before the main function.</p><pre>var authenticator auth.Authenticator<br>var cache store.Cache</pre><p>now we need a function to setup Go-Guardian.</p><pre>func setupGoGuardian() {                        <br>authenticator = auth.New()                        <br>cache = store.NewFIFO(context.Background(), time.Minute*10)<br>account := kubernetes.SetServiceAccountToken(&quot;&lt;PodB Token/secrets&gt;&quot;)<br>address := kubernetes.SetAddress(&quot;http://&lt;k8s host ip&gt;:&lt;k8s port&gt;&quot;)<br>kubeStrategy := kubernetes.New(cache, account, address)                        authenticator.EnableStrategy(token.CachedStrategyKey, kubeStrategy)                       }</pre><p>What I’ve done is to setup Go-Gurdian, by creating authenticator that takes request and dispatch it to kubernetes strategy and return user information when successfully authenticates the request.<br>besides, initialize a cache to caches the authentication decision to improve server performance.</p><p><strong><em>Note: </em></strong>make sure to replace &lt;PodB Token/secrets&gt; with actual secret that we done in <strong>Prerequisite </strong>section. and also replace &lt;k8s host ip&gt;:&lt;k8s port&gt; with the k8s API server IP and port</p><p>Before we continue, we need an HTTP middleware to intercept the request and authenticate users before it reaches the final route.</p><pre>func middleware(next http.Handler) http.HandlerFunc {<br>    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {<br>        log.Println(&quot;Executing Auth Middleware&quot;)<br>        user, err := authenticator.Authenticate(r)<br>        if err != nil {<br>            code := http.StatusUnauthorized<br>            http.Error(w, http.StatusText(code), code)<br>            return<br>        }<br>        log.Printf(&quot;User %s Authenticated\n&quot;, user.UserName())<br>        next.ServeHTTP(w, r)<br>    })<br>}</pre><p>finally, we wrap the getBookAuthor function in our main with the middleware to authenticate the request.</p><pre>middleware(http.HandlerFunc(getBookAuthor))</pre><p><strong>Your file should now look something like this:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60317d46acbde96a65b7fa0fa6eb6fc3/href">https://medium.com/media/60317d46acbde96a65b7fa0fa6eb6fc3/href</a></iframe><h3>Testing our API</h3><pre>curl  -k <a href="http://127.0.0.1:8080/v1/book/1449311601">http://127.0.0.1:8080/v1/book/1449311601</a> -H &quot;Authorization: Bearer &lt;Pod A Token&gt;&quot;</pre><pre>Author: Ryan Boyd</pre><pre>curl  -k <a href="http://127.0.0.1:8080/v1/book/1449311601">http://127.0.0.1:8080/v1/book/1449311601</a> -H &quot;Authorization: Bearer invalid&quot;</pre><pre>Unauthorized</pre><h3>Thank you so much for reading!</h3><p>I hope you found this article helpful, I really hope I helped at least one person get familiar with the basics of building Server Authentication in Golang Using Go-Guardian.</p><p>More About Go-Guardian can be found in <a href="https://github.com/shaj13/go-guardian/tree/master/auth"><em>GitHub </em></a>and <a href="https://pkg.go.dev/github.com/shaj13/go-guardian?tab=doc"><em>GoDoc</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56e06cc55ed3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Scalable Authentication in Golang Using Go-Guardian]]></title>
            <link>https://medium.com/@hajsanad/writing-scalable-authentication-in-golang-using-go-guardian-83691219a73a?source=rss-4c123c2c83b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/83691219a73a</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[cluster]]></category>
            <category><![CDATA[go-guardian]]></category>
            <dc:creator><![CDATA[Sanad Haj]]></dc:creator>
            <pubDate>Fri, 14 Aug 2020 00:02:46 GMT</pubDate>
            <atom:updated>2020-08-14T00:02:46.217Z</atom:updated>
            <content:encoded><![CDATA[<p>In building web and REST API application, it is very important to build a system users can trust and rely on.</p><p>Authentication is important because it enables organizations and apps to keep their networks secure by permitting only authenticated users to access its protected resources.</p><p>In this tutorial, We’ll be discussing how to handle authentication running in cluster mode using <a href="https://golang.org/">Golang</a> and <a href="https://github.com/shaj13/go-guardian">Go-Guardian </a>library.</p><h3>Problem</h3><p>Authentication is just one of the possible places that could cause scalability issue, As long as user info stored or cached on the server-side.</p><p>running a replicated application in cluster modes like Kubernetes, docker swarm, or even behind a load balancer, doesn’t guarantee to assign a single server to a particular user.</p><h3>Use Case And Solution</h3><p>assume we have app replicated twice(A, B) and running behind a load balancer, the user asks for token the load balancer route request to replication <strong>A </strong>where the token generated and cached in the app memory now the same user request a protected resource and the load balancer route request to replication <strong>B </strong>this will end up with an authorization error.</p><p>let’s figure out how we can solve the above problem and scale the app without performance degradation and keeping in mind this kind of service must be stateless.</p><p><strong>Suggested Solutions :</strong></p><ul><li>save token in db and re-cache it in the server.</li><li>distributed cache</li><li>shared cache</li><li>sticky session</li></ul><p>in all the above solution we still have a problem, so ask your self what will happen if DB or shared cache down, or the app itself failed ?</p><p>the optimal solution for this kind of issue is to use a stateless token where it can be signed and verified again.<br>in this tutorial, we will use JWT as defined in RFC 7519,<br>cause it Internet widely and most of the readers have used it or heard about it.</p><h3>Go-Guardian Overview</h3><p>Go-Guardian is a golang library that provides a simple, clean, and idiomatic way to create powerful modern API and web authentication.</p><p>Go-Guardian sole purpose is to authenticate requests, which it does through an extensible set of authentication methods known as strategies.<br> Go-Guardian does not mount routes or assume any particular database schema, which maximizes flexibility and allows decisions to be made by the developer.<br> The API is simple: you provide go-guardian a request to authenticate, and go-guardian invoke strategies to authenticate end-user request.<br> Strategies provide callbacks for controlling what occurs when authentication should succeeds or fails.</p><h3>Why Go-Guardian?</h3><p>When building a modern application, you don’t want to implement authentication module from scratch;<br> you want to focus on building awesome software. go-guardian is here to help with that.</p><p>Here are a few bullet point reasons you might like to try it out:</p><ul><li>provides simple, clean, and idiomatic API.</li><li>provides top trends and traditional authentication methods.</li><li>provides a package to caches the authentication decisions, based on different mechanisms and algorithms.</li><li>provides two-factor authentication and one-time password as defined in <a href="https://tools.ietf.org/html/rfc4226">RFC-4226</a> and <a href="https://tools.ietf.org/html/rfc6238">RFC-6238</a></li></ul><h3>Creating our project</h3><p>We are going to start by creating our project.</p><pre>mkdir scalable-auth &amp;&amp; cd scalable-auth &amp;&amp; go mod init scalable-auth &amp;&amp; touch main.go</pre><p>This will create a new directory called “scalable-auth” and and initialize the project with go.mod.</p><p>We also need to install gorilla mux, go-guardian, <a href="https://github.com/dgrijalva/jwt-go">jwt-go</a>.</p><pre>go get github.com/gorilla/mux<br>go get github.com/shaj13/go-guardian<br>go get &quot;github.com/dgrijalva/jwt-go&quot;</pre><h3>Our first lines of code</h3><p>Before we write any code we need to write some mandatory code to make the program run.</p><pre>package main<br>import (<br>  &quot;log&quot;<br>)<br>func main() {<br>  log.Println(&quot;Auth !!&quot;)<br>}</pre><h3>Creating our endpoints</h3><p>We are going to remove the line that prints out “Auth !!” and add the gorilla Mux package and initialize the router.</p><pre>package main<br>import (<br>  &quot;github.com/gorilla/mux&quot;<br>)<br>func main() {<br>  router := mux.NewRouter()<br>}</pre><p>Now we are going to establish the endpoints of our API, the way we will set this up is to create all of our endpoints in the main function, every endpoint needs a function to handle the request and we will define those below the main function.</p><pre>package main<br>import (<br>  &quot;net/http&quot;<br>  &quot;log&quot;<br>  &quot;github.com/gorilla/mux&quot;<br>)<br>func main() {<br>  router := mux.NewRouter() <br>  router.HandleFunc(&quot;/v1/auth/token&quot;, createToken).Methods(&quot;GET&quot;)<br>  router.HandleFunc(&quot;/v1/book/{id}&quot;, getBookAuthor).Methods(&quot;GET&quot;)<br>  log.Println(&quot;server started and listening on <a href="http://127.0.0.1:8080/">http://127.0.0.1:8080</a>&quot;)<br>  http.ListenAndServe(&quot;127.0.0.1:8080&quot;, router)<br>}</pre><p>What I’ve done is to create two different routes, first, API to obtain a bearer token and the second one to access a protected resource that returns a book author by id.</p><h3>Route handlers</h3><p>Now we just need to define the functions that will handle the requests.</p><p><strong>createToken()</strong></p><pre>func createToken(w http.ResponseWriter, r *http.Request) {<br>	token := jwt.NewWithClaims(jwt.SigningMethodHS256,    jwt.MapClaims{<br>		&quot;iss&quot;: &quot;auth-app&quot;,<br>		&quot;sub&quot;:  &quot;medium&quot;,<br>		&quot;aud&quot;: &quot;any&quot;,<br>		&quot;exp&quot;: time.Now().Add(time.Minute * 5).Unix(),<br>	})</pre><pre>jwtToken, _:= token.SignedString([]byte(&quot;secret&quot;))<br>     w.Write([]byte(jwtToken))<br>}</pre><p><strong>getBookAuthor()</strong></p><pre>func getBookAuthor(w http.ResponseWriter, r *http.Request) {    vars := mux.Vars(r)<br>    id := vars[&quot;id&quot;]<br>    books := map[string]string{<br>        &quot;1449311601&quot;: &quot;Ryan Boyd&quot;,<br>        &quot;148425094X&quot;: &quot;Yvonne Wilson&quot;,<br>        &quot;1484220498&quot;: &quot;Prabath Siriwarden&quot;,<br>    }<br>    body := fmt.Sprintf(&quot;Author: %s \n&quot;, books[id])<br>    w.Write([]byte(body))<br>}</pre><p><strong>Your file should now look something like this:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff23cd56e3229a474f2f6726096d11da/href">https://medium.com/media/ff23cd56e3229a474f2f6726096d11da/href</a></iframe><p>Now lets run sample requests to test our code !!</p><pre>curl  -k <a href="http://127.0.0.1:8080/v1/book/1449311601">http://127.0.0.1:8080/v1/book/1449311601</a> <br>Author: Ryan Boyd</pre><pre>curl  -k <a href="http://127.0.0.1:8080/v1/auth/token">http://127.0.0.1:8080/v1/auth/token</a></pre><pre>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhbnkiLCJleHAiOjE1OTczNjE0NDYsImlzcyI6ImF1dGgtYXBwIiwic3ViIjoibWVkaXVtIn0.EepQzhuAS-lnljTZad3vAO2vRbgflB53aUCfCnlbku4</pre><h3>Integrate with Go-Guardian</h3><p>first let’s add the following line before the main function.</p><pre>var authenticator auth.Authenticator<br>var cache store.Cache</pre><p>and create two functions to verify the user credential and token.</p><pre>func validateUser(ctx context.Context, r *http.Request, userName, password string) (auth.Info, error) {<br>    if userName == &quot;medium&quot; &amp;&amp; password == &quot;medium&quot; {<br>        return auth.NewDefaultUser(&quot;medium&quot;, &quot;1&quot;, nil, nil), nil<br>    }<br>    return nil, fmt.Errorf(&quot;Invalid credentials&quot;)<br>}</pre><pre>func verifyToken(ctx context.Context, r *http.Request, tokenString string) (auth.Info, error) {</pre><pre>token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {<br>  if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {<br>   return nil, fmt.Errorf(&quot;Unexpected signing method: %v&quot;,     token.Header[&quot;alg&quot;])<br>}<br>   return []byte(&quot;secret&quot;), nil<br>})</pre><pre>if err != nil {<br>       return nil, err<br>}</pre><pre>if claims, ok := token.Claims.(jwt.MapClaims); ok &amp;&amp; token.Valid {</pre><pre>user := auth.NewDefaultUser(claims[&quot;medium&quot;].(string), &quot;&quot;, nil, nil)<br>return user, nil<br>}<br>return nil , fmt.Errorf(&quot;Invaled token&quot;)<br>}</pre><p>now we need another function to setup Go-Guardian.</p><pre>func setupGoGuardian() {   <br>    authenticator = auth.New()<br>    cache = store.NewFIFO(context.Background(), time.Minute*5)<br>    basicStrategy := basic.New(validateUser, cache) <br>    tokenStrategy := bearer.New(verifyToken, cache)<br>    authenticator.EnableStrategy(basic.StrategyKey, basicStrategy)<br>    authenticator.EnableStrategy(bearer.CachedStrategyKey,    tokenStrategy)<br>}</pre><p>What I’ve done is to setup Go-Gurdian, by creating authenticator that takes request and dispatch it to strategies and return user information from the first strategy that successfully authenticates the request.<br>besides, initialize a cache to caches the authentication decision to improve server performance.</p><p>Before we continue, we need an HTTP middleware to intercept the request and authenticate users before it reaches the final route.</p><pre>func middleware(next http.Handler) http.HandlerFunc {<br>    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {<br>        log.Println(&quot;Executing Auth Middleware&quot;)<br>        user, err := authenticator.Authenticate(r)<br>        if err != nil {<br>            code := http.StatusUnauthorized<br>            http.Error(w, http.StatusText(code), code)<br>            return<br>        }<br>        log.Printf(&quot;User %s Authenticated\n&quot;, user.UserName())<br>        next.ServeHTTP(w, r)<br>    })<br>}</pre><p>finally, we wrap the createToken and getBookAuthor functions in our main with the middleware to authenticate the request.</p><pre>middleware(http.HandlerFunc(createToken))<br>middleware(http.HandlerFunc(getBookAuthor))</pre><p>Don’t forget to invoke set up GoGuardian in the first of the main function.</p><pre>setupGoGuardian()</pre><p><strong>Your file should now look something like this:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e6deb005eeceb66e3d1d370ac465d7c/href">https://medium.com/media/7e6deb005eeceb66e3d1d370ac465d7c/href</a></iframe><h3>Testing our API</h3><p>first lets run app twice from two different shell.</p><pre>PORT=8080 go run main.go</pre><pre>PORT=9090 go run main.go</pre><p>Obtain a user access token from replica A (port 8080)</p><pre>curl  -k <a href="http://127.0.0.1:8080/v1/auth/token">http://127.0.0.1:8080/v1/auth/token</a> -u medium:medium</pre><pre>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhbnkiLCJleHAiOjE1OTczNjI4NjksImlzcyI6ImF1dGgtYXBwIiwic3ViIjoibWVkaXVtIn0.SlignTJE3YD9Ecl24ygoYRu_9tVucCLop4vXWKzaRTw</pre><p>Getting a book author using user access token from replica B (port 9090)</p><pre>curl  -k <a href="http://127.0.0.1:8080/v1/book/1449311601">http://127.0.0.1:8080/v1/book/1449311601</a> -H &quot;Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhbnkiLCJleHAiOjE1OTczNjI4NjksImlzcyI6ImF1dGgtYXBwIiwic3ViIjoibWVkaXVtIn0.SlignTJE3YD9Ecl24ygoYRu_9tVucCLop4vXWKzaRTw&quot;</pre><pre>Author: Ryan Boyd</pre><h3>Thank you so much for reading!</h3><p>I hope you found this article helpful, I really hope I helped at least one person get familiar with the basics of building Server Authentication in Golang Using Go-Guardian.</p><p>More About Go-Guardian can be found in <a href="https://github.com/shaj13/go-guardian/tree/master/auth"><em>GitHub </em></a>and <a href="https://pkg.go.dev/github.com/shaj13/go-guardian?tab=doc"><em>GoDoc</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83691219a73a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LDAP Authentication in Golang Using Go-Guardian]]></title>
            <link>https://medium.com/@hajsanad/ldap-authentication-in-golang-using-go-guardian-6477eade2a8e?source=rss-4c123c2c83b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6477eade2a8e</guid>
            <category><![CDATA[ldap-authentication]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[ldap]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[go-guardian]]></category>
            <dc:creator><![CDATA[Sanad Haj]]></dc:creator>
            <pubDate>Sun, 19 Jul 2020 19:22:38 GMT</pubDate>
            <atom:updated>2020-07-19T19:24:15.653Z</atom:updated>
            <content:encoded><![CDATA[<p>In building web and REST API application, it is very important to build a system users can trust and rely on.</p><p>Authentication is important because it enables organizations and apps to keep their networks secure by permitting only authenticated users to access its protected resources.</p><p>In this tutorial, We’ll be discussing how to handle LDAP based authentication using <a href="https://golang.org/">Golang</a> and <a href="https://github.com/shaj13/go-guardian">Go-Guardian </a>library integrated with an <a href="https://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/">online LDAP test server</a>.</p><h4>Go-Guardian Overview</h4><p>Go-Guardian is a golang library that provides a simple, clean, and idiomatic way to create powerful modern API and web authentication.</p><p>Go-Guardian sole purpose is to authenticate requests, which it does through an extensible set of authentication methods known as strategies.<br> Go-Guardian does not mount routes or assume any particular database schema, which maximizes flexibility and allows decisions to be made by the developer.<br> The API is simple: you provide go-guardian a request to authenticate, and go-guardian invoke strategies to authenticate end-user request.<br> Strategies provide callbacks for controlling what occurs when authentication should succeeds or fails.</p><h4>Why Go-Guardian?</h4><p>When building a modern application, you don’t want to implement authentication module from scratch;<br> you want to focus on building awesome software. go-guardian is here to help with that.</p><p>Here are a few bullet point reasons you might like to try it out:</p><ul><li>provides simple, clean, and idiomatic API.</li><li>provides top trends and traditional authentication methods.</li><li>provides a package to caches the authentication decisions, based on different mechanisms and algorithms.</li><li>provides two-factor authentication and one-time password as defined in <a href="https://tools.ietf.org/html/rfc4226">RFC-4226</a> and <a href="https://tools.ietf.org/html/rfc6238">RFC-6238</a></li></ul><h4>Creating our project</h4><p>We are going to start by creating our project.</p><pre>mkdir ldap-auth &amp;&amp; cd ldap-auth &amp;&amp; go mod init ldap-auth &amp;&amp; touch main.go</pre><p>This will create a new directory called “ldap-auth” and initialize the project with go.mod.</p><p>We also need to install gorilla mux, go-guardian.</p><pre>go get github.com/gorilla/mux<br>go get github.com/shaj13/go-guardian</pre><h4>Our first lines of code</h4><p>Before we write any code we need to write some mandatory code to make the program run.</p><pre>package main</pre><pre>import (<br>  &quot;log&quot;<br>)</pre><pre>func main() {<br>  log.Println(&quot;LDAP Auth !!&quot;)<br>}</pre><h4>Creating our endpoints</h4><p>We are going to remove the line that prints out “LDAP Auth !!” and add the gorilla Mux package and initialize the router.</p><pre>package main</pre><pre>import (<br>  &quot;github.com/gorilla/mux&quot;<br>)</pre><pre>func main() {<br>  router := mux.NewRouter()<br>}</pre><p>Now we are going to establish the endpoints of our API, the way we will set this up is to create all of our endpoints in the main function, every endpoint needs a function to handle the request and we will define those below the main function.</p><pre>package main</pre><pre>import (<br>  &quot;net/http&quot;<br>  &quot;log&quot;</pre><pre>&quot;github.com/gorilla/mux&quot;<br>)</pre><pre>func main() {<br>  router := mux.NewRouter() <br>  router.HandleFunc(&quot;/v1/book/{id}&quot;, getBookAuthor).Methods(&quot;GET&quot;)<br>  log.Println(&quot;server started and listening on <a href="http://127.0.0.1:8080/">http://127.0.0.1:8080</a>&quot;)<br>  http.ListenAndServe(&quot;127.0.0.1:8080&quot;, router)</pre><pre>}</pre><p>What I’ve done is to create API to access a protected resource that returns a book author by id.</p><h4>Route handlers</h4><p>Now we just need to define the function that will handle the requests.</p><p><strong>getBookAuthor()</strong></p><pre>func getBookAuthor(w http.ResponseWriter, r *http.Request) {</pre><pre>vars := mux.Vars(r)<br>    id := vars[&quot;id&quot;]<br>    books := map[string]string{<br>        &quot;1449311601&quot;: &quot;Ryan Boyd&quot;,<br>        &quot;148425094X&quot;: &quot;Yvonne Wilson&quot;,<br>        &quot;1484220498&quot;: &quot;Prabath Siriwarden&quot;,<br>    }<br>    body := fmt.Sprintf(&quot;Author: %s \n&quot;, books[id])<br>    w.Write([]byte(body))<br>}</pre><p><strong>Your file should now look something like this:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc6a8ab50717c2a9ef770c5becaac05b/href">https://medium.com/media/cc6a8ab50717c2a9ef770c5becaac05b/href</a></iframe><p>Now lets run sample requests to test our code !!</p><pre>curl  -k <a href="http://127.0.0.1:8080/v1/book/1449311601">http://127.0.0.1:8080/v1/book/1449311601</a> <br>Author: Ryan Boyd</pre><h4>Integrate with Go-Guardian</h4><p>first let’s add the following lines before the main function.</p><pre>var authenticator auth.Authenticator<br>var cache store.Cache</pre><p>now we need a function to setup Go-Guardian.</p><pre>func setupGoGuardian() {<br>   cfg := &amp;ldap.Config{<br>           BaseDN:       &quot;dc=example,dc=com&quot;,  <br>           BindDN:       &quot;cn=read-only-admin,dc=example,dc=com&quot;, <br>           Port:         &quot;389&quot;,                 <br>           Host:         &quot;ldap.forumsys.com&quot;,   <br>           BindPassword: &quot;password&quot;, <br>           Filter:       &quot;(uid=%s)&quot;, <br>       }<br>   authenticator = auth.New()           <br>   cache = store.NewFIFO(context.Background(), time.Minute*10)                             <br>   strategy := ldap.NewCached(cfg, cache)  <br>   authenticator.EnableStrategy(ldap.StrategyKey, strategy)}</pre><p>What I’ve done is to setup Go-Gurdian, by creating authenticator that takes request and dispatch it to strategies and return user information from the first strategy that successfully authenticates the request.<br>besides, initialize a cache to caches the authentication decision to improve server performance.</p><p>Before we continue, we need an HTTP middleware to intercept the request and authenticate users before it reaches the final route.</p><pre>func middleware(next http.Handler) http.HandlerFunc {<br>    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {<br>        log.Println(&quot;Executing Auth Middleware&quot;)<br>        user, err := authenticator.Authenticate(r)<br>        if err != nil {<br>            code := http.StatusUnauthorized<br>            http.Error(w, http.StatusText(code), code)<br>            return<br>        }<br>        log.Printf(&quot;User %s Authenticated\n&quot;, user.UserName())<br>        next.ServeHTTP(w, r)<br>    })<br>}</pre><p>finally, we wrap the getBookAuthor functions in our main with the middleware to authenticate the request.</p><pre>middleware(http.HandlerFunc(getBookAuthor))</pre><p>Don’t forget to invoke set up GoGuardian in the first of the main function.</p><pre>setupGoGuardian()</pre><p><strong>Your file should now look something like this:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8068a8ee1e3e616b7003fed28f89ffea/href">https://medium.com/media/8068a8ee1e3e616b7003fed28f89ffea/href</a></iframe><h3>Testing our API</h3><p>Getting a book author using an anonymous user</p><pre>curl  -k <a href="http://127.0.0.1:8080/v1/book/1449311601">http://127.0.0.1:8080/v1/book/1449311601</a><br>Unauthorized</pre><p>Getting a book author using user credential</p><pre>curl  -k <a href="http://127.0.0.1:8080/v1/book/1449311601">http://127.0.0.1:8080/v1/book/1449311601</a> -u tesla:password<br>Author: Ryan Boyd</pre><h3>Thank you so much for reading!</h3><p>I hope you found this article helpful, I really hope I helped at least one person get familiar with the basics of building Server Authentication in Golang Using Go-Guardian.</p><p>More About Go-Guardian can be found in <a href="https://github.com/shaj13/go-guardian/tree/master/auth"><em>GitHub </em></a>and <a href="https://pkg.go.dev/github.com/shaj13/go-guardian?tab=doc"><em>GoDoc</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6477eade2a8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication in Golang Using Go-Guardian]]></title>
            <link>https://medium.com/@hajsanad/authentication-in-golang-using-go-guardian-b1cd47da47a0?source=rss-4c123c2c83b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1cd47da47a0</guid>
            <category><![CDATA[bearer-token]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[go-guardian]]></category>
            <category><![CDATA[basic-authentication]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Sanad Haj]]></dc:creator>
            <pubDate>Wed, 27 May 2020 21:29:03 GMT</pubDate>
            <atom:updated>2020-05-27T21:57:43.869Z</atom:updated>
            <content:encoded><![CDATA[<p>In building web and REST API application, it is very important to build a system users can trust and rely on.</p><p>Authentication is important because it enables organizations and apps to keep their networks secure by permitting only authenticated users to access its protected resources.</p><p>In this tutorial, We’ll be discussing how to handle basic and bearer authentication strategies using <a href="https://golang.org/">Golang</a> and <a href="https://github.com/shaj13/go-guardian">Go-Guardian </a>library.</p><h4>Go-Guardian Overview</h4><p>Go-Guardian is a golang library that provides a simple, clean, and idiomatic way to create powerful modern API and web authentication.</p><p>Go-Guardian sole purpose is to authenticate requests, which it does through an extensible set of authentication methods known as strategies.<br> Go-Guardian does not mount routes or assume any particular database schema, which maximizes flexibility and allows decisions to be made by the developer.<br> The API is simple: you provide go-guardian a request to authenticate, and go-guardian invoke strategies to authenticate end-user request.<br> Strategies provide callbacks for controlling what occurs when authentication should succeeds or fails.</p><h4><strong>Why Go-Guardian?</strong></h4><p>When building a modern application, you don’t want to implement authentication module from scratch;<br> you want to focus on building awesome software. go-guardian is here to help with that.</p><p>Here are a few bullet point reasons you might like to try it out:</p><ul><li>provides simple, clean, and idiomatic API.</li><li>provides top trends and traditional authentication methods.</li><li>provides a package to caches the authentication decisions, based on different mechanisms and algorithms.</li><li>provides two-factor authentication and one-time password as defined in <a href="https://tools.ietf.org/html/rfc4226">RFC-4226</a> and <a href="https://tools.ietf.org/html/rfc6238">RFC-6238</a></li></ul><h4>Creating our project</h4><p>We are going to start by creating our project.</p><pre>mkdir web-auth &amp;&amp; cd web-auth &amp;&amp; go mod init web-auth &amp;&amp; touch main.go</pre><p>This will create a new directory called “web-auth” and and initialize the project with go.mod.</p><p>We also need to install gorilla mux, go-guardian, uuid.</p><pre>go get github.com/gorilla/mux<br>go get github.com/shaj13/go-guardian<br>go get github.com/google/uuid</pre><h4>Our first lines of code</h4><p>Before we write any code we need to write some mandatory code to make the program run.</p><pre>package main</pre><pre>import (<br>  &quot;log&quot;<br>)</pre><pre>func main() {<br>  log.Println(&quot;Web Auth !!&quot;)<br>}</pre><h4>Creating our endpoints</h4><p>We are going to remove the line that prints out “Web Auth !!” and add the gorilla Mux package and initialize the router.</p><pre>package main</pre><pre>import (<br>  &quot;github.com/gorilla/mux&quot;<br>)</pre><pre>func main() {<br>  router := mux.NewRouter()<br>}</pre><p>Now we are going to establish the endpoints of our API, the way we will set this up is to create all of our endpoints in the main function, every endpoint needs a function to handle the request and we will define those below the main function.</p><pre>package main</pre><pre>import (<br>  &quot;net/http&quot;<br>  &quot;log&quot;</pre><pre>  &quot;github.com/gorilla/mux&quot;<br>)</pre><pre>func main() {<br>  router := mux.NewRouter() <br>  router.HandleFunc(&quot;/v1/auth/token&quot;, createToken).Methods(&quot;GET&quot;)<br>  router.HandleFunc(&quot;/v1/book/{id}&quot;, getBookAuthor).Methods(&quot;GET&quot;)<br>  log.Println(&quot;server started and listening on <a href="http://127.0.0.1:8080/">http://127.0.0.1:8080</a>&quot;)<br>  http.ListenAndServe(&quot;127.0.0.1:8080&quot;, router)</pre><pre>}</pre><p>What I’ve done is to create two different routes, first, API to obtain a bearer token and the second one to access a protected resource that returns a book author by id.</p><h4>Route handlers</h4><p>Now we just need to define the functions that will handle the requests.</p><p><strong>createToken()</strong></p><pre>func createToken(w http.ResponseWriter, r *http.Request) {<br>    token := uuid.New().String()<br>    body := fmt.Sprintf(&quot;token: %s \n&quot;, token)<br>     w.Write([]byte(body))<br>}</pre><p><strong>getBookAuthor()</strong></p><pre>func getBookAuthor(w http.ResponseWriter, r *http.Request) {</pre><pre>    vars := mux.Vars(r)<br>    id := vars[&quot;id&quot;]<br>    books := map[string]string{<br>        &quot;1449311601&quot;: &quot;Ryan Boyd&quot;,<br>        &quot;148425094X&quot;: &quot;Yvonne Wilson&quot;,<br>        &quot;1484220498&quot;: &quot;Prabath Siriwarden&quot;,<br>    }<br>    body := fmt.Sprintf(&quot;Author: %s \n&quot;, books[id])<br>    w.Write([]byte(body))<br>}</pre><p><strong>Your file should now look something like this:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4b50ecc26782cf274aa15ed2dab7d14/href">https://medium.com/media/e4b50ecc26782cf274aa15ed2dab7d14/href</a></iframe><p>Now lets run sample requests to test our code !!</p><pre>curl  -k <a href="http://127.0.0.1:8080/v1/book/1449311601">http://127.0.0.1:8080/v1/book/1449311601</a> <br>Author: Ryan Boyd</pre><pre>curl  -k <a href="http://127.0.0.1:8080/v1/auth/token">http://127.0.0.1:8080/v1/auth/token</a><br>token: d77c894d-381b-4fd9-9e84-4f9ed445bac8</pre><h4>Integrate with Go-Guardian</h4><p>first let’s add the following line before the main function.</p><pre>var authenticator auth.Authenticator<br>var cache store.Cache</pre><p>and create simple function to verify the user credential</p><pre>func validateUser(ctx context.Context, r *http.Request, userName, password string) (auth.Info, error) {<br>    if userName == &quot;medium&quot; &amp;&amp; password == &quot;medium&quot; {<br>        return auth.NewDefaultUser(&quot;medium&quot;, &quot;1&quot;, nil, nil), nil<br>    }<br>    return nil, fmt.Errorf(&quot;Invalid credentials&quot;)<br>}</pre><p>now we need another function to setup Go-Guardian.</p><pre>func setupGoGuardian() {</pre><pre>    authenticator = auth.New()<br>    cache = store.NewFIFO(context.Background(), time.Minute*10)<br>    basicStrategy := basic.New(validateUser, cache) <br>    tokenStrategy := bearer.New(bearer.NoOpAuthenticate, cache)<br>    authenticator.EnableStrategy(basic.StrategyKey, basicStrategy)<br>    authenticator.EnableStrategy(bearer.CachedStrategyKey,    tokenStrategy)<br>}</pre><p>What I’ve done is to setup Go-Gurdian, by creating authenticator that takes request and dispatch it to strategies and return user information from the first strategy that successfully authenticates the request.<br>besides, initialize a cache to caches the authentication decision to improve server performance.</p><p>we also need to improve the createToken function to push the user token into the bearer token strategy each time the user request a new access token. we do this with the following lines.</p><pre>user := auth.NewDefaultUser(&quot;medium&quot;, &quot;1&quot;, nil, nil)<br>tokenStrategy := authenticator.Strategy(bearer.CachedStrategyKey)<br>auth.Append(tokenStrategy, token, user, r)</pre><p>Before we continue, we need an HTTP middleware to intercept the request and authenticate users before it reaches the final route.</p><pre>func middleware(next http.Handler) http.HandlerFunc {<br>    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {<br>        log.Println(&quot;Executing Auth Middleware&quot;)<br>        user, err := authenticator.Authenticate(r)<br>        if err != nil {<br>            code := http.StatusUnauthorized<br>            http.Error(w, http.StatusText(code), code)<br>            return<br>        }<br>        log.Printf(&quot;User %s Authenticated\n&quot;, user.UserName())<br>        next.ServeHTTP(w, r)<br>    })<br>}</pre><p>finally, we wrap the createToken and getBookAuthor functions in our main with the middleware to authenticate the request.</p><pre>middleware(http.HandlerFunc(createToken))<br>middleware(http.HandlerFunc(getBookAuthor))</pre><p>Don’t forget to invoke set up GoGuardian in the first of the main function.</p><pre>setupGoGuardian()</pre><p><strong>Your file should now look something like this:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff9cf0e504ea0381394d0862d7415d12/href">https://medium.com/media/ff9cf0e504ea0381394d0862d7415d12/href</a></iframe><h3>Testing our API</h3><p>Getting a book author using an anonymous user</p><pre>curl  -k <a href="http://127.0.0.1:8080/v1/book/1449311601">http://127.0.0.1:8080/v1/book/1449311601</a><br>Unauthorized</pre><p>Getting a book author using user credential</p><pre>curl  -k <a href="http://127.0.0.1:8080/v1/book/1449311601">http://127.0.0.1:8080/v1/book/1449311601</a> -u medium:medium<br>Author: Ryan Boyd</pre><p>Obtain a user access token</p><pre>curl  -k <a href="http://127.0.0.1:8080/v1/auth/token">http://127.0.0.1:8080/v1/auth/token</a> -u medium:medium<br>token: b11d1e98-5d2e-4d56-89f8-415b68fdbd74</pre><p>Getting a book author using user access token</p><pre>curl  -k <a href="http://127.0.0.1:8080/v1/book/1449311601">http://127.0.0.1:8080/v1/book/1449311601</a> -H &quot;Authorization: Bearer b11d1e98-5d2e-4d56-89f8-415b68fdbd74&quot;<br>Author: Ryan Boyd</pre><h3>Thank you so much for reading!</h3><p>I hope you found this article helpful, I really hope I helped at least one person get familiar with the basics of building Server Authentication in Golang Using Go-Guardian.</p><p>More About Go-Guardian can be found in <a href="https://github.com/shaj13/go-guardian/tree/master/auth"><em>GitHub </em></a>and <a href="https://pkg.go.dev/github.com/shaj13/go-guardian?tab=doc"><em>GoDoc</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1cd47da47a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>