<?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 Michel La Guardia Lara Castro on Medium]]></title>
        <description><![CDATA[Stories by Michel La Guardia Lara Castro on Medium]]></description>
        <link>https://medium.com/@michellaguardialaracastro?source=rss-d7b4205e5110------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Mf_uvTU8TcT0EBtMw-w_Pw.jpeg</url>
            <title>Stories by Michel La Guardia Lara Castro on Medium</title>
            <link>https://medium.com/@michellaguardialaracastro?source=rss-d7b4205e5110------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:51:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@michellaguardialaracastro/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[Krakend personal plugins — How can you improve your security rules with an API Gateway?]]></title>
            <link>https://medium.com/@michellaguardialaracastro/krakend-personal-plugins-how-can-you-improve-your-security-rules-with-an-api-gateway-ffb484e2e75?source=rss-d7b4205e5110------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffb484e2e75</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[krakend]]></category>
            <category><![CDATA[security-token]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Michel La Guardia Lara Castro]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 17:23:40 GMT</pubDate>
            <atom:updated>2023-07-13T18:33:46.986Z</atom:updated>
            <content:encoded><![CDATA[<h3>Krakend personal plugins — How can you improve your security rules with an API Gateway?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*6-Z6HYcwuGS50gvFJxmpaQ.png" /></figure><h3><strong>Summary</strong></h3><p>This project was built to solve some problems with the security of APIs mainly in the microservices environment, which you can need more control with the flow of information and the access of it.</p><p>Look at this: imagine you need to build a new APP, and this app needs to be made with microservices or distributed monolithic services. This app will need more control over the route exposition, who can be allowed to access them, observability with trace id, rate limit, and others. Note it can be a big problem and your application will not be exposed to these gaps for your information.</p><p>The solution proposed is a plugin attached to Krakend API Gateway, which will control each request and provide access control requesting another personal API as an authorization provider like oAuth2, or Auth0, but with your rules about the security. You can be able to put some information for your services and isolate your API environment/ecosystem from the public internet. Your services won’t have concerns about the access, and it will collect some information about the users, rather than decipher the token for each request. Therefore, all the developers will focus on the problem and how to solve it in the business domain they belong to.<br> <br> The image bellow explains the project concept:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xwv7VzetUMKNkG0B9MPIyw.png" /></figure><p>Abstracting the solution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-mSDJ2FEbIH_yTiP1QO9hw.png" /></figure><h3>How does it work?</h3><p>An API Gateway authenticates all traffic before routing it to the called service. The API Gateway can perform the authentication itself or use external authentication providers for that task. Authorization is the process that ensures your users have the necessary permissions to request the action from a service.</p><p>By building a plugin within the API Gateway you can enable this resource to intercept each request and provides more control over your rules.</p><p>Steps:</p><p>1) Build your personal API authorizer. This API will provide client, scope, and resource control, for each route of the API gateway can be allowed to access.</p><p>2) Build the API Gateway plugin. This plugin will have rules about the information flow and access like a concierge, which allows or does not allow access to the route.</p><p>3) Send this information aggregating some information. After this step, aggregate more information for each request providing: trace id, token, and others that you will need.</p><p>4) If your request was allowed, set more information in the response about whether you will need it.</p><h3>Why Krakend?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*ubFqZPygdOYzVfeZXU7Axg.png" /></figure><p>KrakenD is an extensible, ultra-high-performance API Gateway that helps you effortlessly adopt microservices and secure communications. KrakenD is easy to operate and run and scales out without a single point of failure.</p><p>It is a powerful tool that provides a great option to ensure security, service discovery, load balancer, and caching for each resource that will have.</p><h3>Creating the authorizer</h3><p>I’ve created my own API authorizer with a simple attribution deny or allow access, note if you will need more control like refreshing tokens or other security rules, it will be possible because you can build and attach your API authorizer afterward.</p><p>This API authorizer was created with the purpose to allow or deny access. It has some entities:</p><p>1) Client, which labeled the access control for each resource with a defined scope.</p><p>2) Scope, which defines all the resources that will be allowed.</p><p>3) Resource is the API Gateway route that can be accessed.</p><p>The authorizer project was built in Golang, with a DDD pattern, because for further updates it can be changed to implement a GRPC connector or other way to communicate with it. The project is on my GitHub: <a href="https://github.com/castmetal/golang-token-api-authorizer">https://github.com/castmetal/golang-token-api-authorizer</a> and I haven’t finished yet until this publish date: 2023–07–13.</p><p>First, create your client:</p><p>POST — <a href="http://localhost:8088/v1/client">http://{api_host:port if need}/v1/client</a></p><pre>{<br>  &quot;scope_name&quot;: &quot;internal_apis&quot;,<br>  &quot;client_name&quot;: &quot;iclinic&quot;,<br>  &quot;key_time_duration&quot;: 1,<br>  &quot;key_period&quot;: &quot;years&quot;,<br>  &quot;permissions&quot;: [<br>    {<br>      &quot;resource_path&quot;: &quot;/clients&quot;,<br>      &quot;resource_method&quot;: &quot;GET&quot;,<br>      &quot;resource_name&quot;: &quot;Find All Clients&quot;<br>    }<br>  ]<br>}</pre><p>You will receive a response similar to this:</p><pre>{<br>  &quot;id&quot;: &quot;2f663f58-7409-4595-991d-1b8d91cbddd9&quot;,<br>  &quot;client_name&quot;: &quot;iclinic&quot;,<br>  &quot;scope_id&quot;: &quot;27e93b6d-bb66-4e00-a939-dd04ac258b47&quot;,<br>  &quot;scope_name&quot;: &quot;internal_apis&quot;,<br>  &quot;api_id&quot;: &quot;CF-01H53WY0MN00596XCSZXB7HWA0&quot;,<br>  &quot;permissions&quot;: [<br>    {<br>      &quot;resource_name&quot;: &quot;Find All clients&quot;,<br>      &quot;resource_path&quot;: &quot;/clients&quot;,<br>      &quot;resource_method&quot;: &quot;GET&quot;<br>    }<br>  ],<br>  &quot;key_time_duration&quot;: 1,<br>  &quot;key_period&quot;: &quot;years&quot;<br>}</pre><p>Now, with the client_id, api_id you can create your token:</p><p>POST — <a href="http://localhost:8088/v1/client">http://{api_host:port if need}/</a>v1/token/generate</p><pre>{<br>  &quot;client_id&quot;: &quot;2f663f58-7409-4595-991d-1b8d91cbddd9&quot;,<br>  &quot;api_id&quot;: &quot;CF-01H53WY0MN00596XCSZXB7HWA0&quot;<br>}</pre><p>You will receive a response similar to this:</p><pre>{<br>  &quot;token&quot;: &quot;your JWT token&quot;<br>}</pre><p>Now you be able to request a resource on the API Gateway.</p><h3>Creating the plugin</h3><p>This project is a handler of the Krakend API Gateway plugin, which will intercept each request before sending it to a resource and it will possibly analyze, extract and add some information in any step of the request.</p><p>The project is on my github: <a href="https://github.com/castmetal/krakend-private-authorizer">https://github.com/castmetal/krakend-private-authorizer</a></p><p>If you need more information about the plugin and how to build it, please access the README.md in the source code for more details.</p><p>I’m putting the main code of the plugin to explain it:</p><pre><br>func (r registerer) registerHandlers(ctx context.Context, extra map[string]interface{}, handler http.Handler) (http.Handler, error) {<br> // return the actual handler wrapping or your custom logic so it can be used as a replacement for the default http handler<br> return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {<br>  var requestId string<br><br>  requestArgs := r.getParamsToRequest(extra, req)<br><br>  w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br><br>  requestId = uuid.NewV4().String()<br><br>  uriSplit := strings.Split(req.RequestURI, &quot;?&quot;)<br>  uri := uriSplit[0]<br><br>  newReq := req.WithContext(ctx)<br>  newReq.Header.Set(&quot;x-origin&quot;, uri)<br>  newReq.Header.Set(&quot;x-request-id&quot;, requestId)<br>  newReq.Header.Set(&quot;x-remote-ip&quot;, req.RemoteAddr)<br><br>  auth := r.InterceptWithAuthorizer(w, req, requestArgs)<br>  if !auth {<br>   return<br>  }<br><br>  rec := statusRecorder{w, 401, &amp;bytes.Buffer{}, false}<br><br>  handler.ServeHTTP(&amp;rec, newReq)<br><br>  m := make(map[string]interface{})<br>  json.Unmarshal(rec.buf.Bytes(), &amp;m)<br><br>  messageError := make(map[string]interface{})<br>  status := rec.status<br><br>  if requestArgs.ModifyErrors == true &amp;&amp; m[requestArgs.ErrorFlag] != nil {<br>   mapMessage := m[requestArgs.ErrorFlag].(map[string]interface{})<br>   statusFloat := mapMessage[&quot;http_status_code&quot;].(float64)<br>   messageStr := mapMessage[&quot;http_body&quot;].(string)<br><br>   err := json.Unmarshal([]byte(messageStr), &amp;messageError)<br>   if err != nil {<br>    messageError = make(map[string]interface{})<br>   }<br><br>   status = int(statusFloat)<br>  }<br><br>  w.WriteHeader(status)<br><br>  if status &gt;= 500 {<br>   resBody := common.ErrorResponse{<br>    Message: requestArgs.DefaultErrorMessage,<br>   }<br><br>   json.NewEncoder(w).Encode(resBody)<br>   return<br>  } else if status &gt;= 300 {<br>   json.NewEncoder(w).Encode(messageError)<br>   return<br>  }<br><br>  json.NewEncoder(w).Encode(m)<br> }), nil<br>}</pre><p>The function registerHandlers provides an interface for each krakend handlerer plugin. They are having the context of the request, extra is a map containing the plugin configuration and a HTTP handler, which is a handler to the Krakend resource.</p><p>I’ve built a struct to catch these data with the getParamsToRequest func, after this I collect some data about the request and set a traceId header, remote-ip, origin for each request. Therefore, it will be accessed by your resources in your API cluster.</p><p>InterceptWithAuthorizer, intercepts each request and sends the response after this, if it was denied, otherwise, the request follows to the next step.</p><p>StatusRecorder, records the request inside the Krakend API Gateway.</p><p>ModifyErrorsFlag: if this is true, send the same response as is on your API service.</p><h3>Configuring Krakend</h3><p>In your krakend.json add the name plugin and compile your .so version into the plugins folder:</p><pre>{<br>    &quot;$schema&quot;: &quot;https://www.krakend.io/schema/v3.json&quot;,<br>    &quot;version&quot;: 3,<br>    &quot;name&quot;: &quot;API Gateway&quot;,<br>    &quot;plugin&quot;: {<br>        &quot;pattern&quot;: &quot;.so&quot;,<br>        &quot;folder&quot;: &quot;./plugins/&quot;<br>    },<br>    &quot;extra_config&quot;: {<br>        &quot;plugin/http-server&quot;: {<br>          &quot;name&quot;: [<br>            &quot;krakend-private-authorizer&quot;<br>          ],<br>          &quot;krakend-private-authorizer&quot;: {<br>            &quot;auth_url&quot;: &quot;{{ env &quot;AUTHORIZER_SERVICE_URL&quot; }}/v1/token/access&quot;,<br>            &quot;token_header&quot;: &quot;{{ env &quot;TOKEN_HEADER&quot; }}&quot;,<br>            &quot;api_id_header&quot;: &quot;api_id&quot;,<br>            &quot;client_id_header&quot;: &quot;client_id&quot;,<br>            &quot;default_error_message&quot;: &quot;Service unavailable&quot;,<br>            &quot;params&quot;: [<br>              &quot;api_id_header&quot;,<br>              &quot;client_id_header&quot;,<br>              &quot;token_header&quot;<br>            ],<br>            &quot;modify_errors&quot;: true,<br>            &quot;public_flag&quot;: &quot;{{ env &quot;PUBLIC_FLAG&quot; }}&quot;,<br>            &quot;error_flag&quot;: &quot;{{ env &quot;ERROR_FLAG&quot; }}&quot;<br>          }<br>      }<br>....</pre><p>krakend-private-authorizer config:</p><p><em>auth_url</em>: Your Auth Provider Service Url, to request private endpoints</p><p><em>token_header</em>: Your Token Header, for sending to your Auth Provider Service</p><p><em>api_id_header</em>: Your Api Id Header, for sending to your Auth Provider Service</p><p><em>client_id_header</em>: Your Client Id Header, for sending to your Auth Provider Service</p><p><em>params</em>: Params, an array of headers to send for your Auth Provider Service</p><p><em>modify_errors</em>: If true, modify the error response to requesting resources with &gt;=300 status Code, it will take the same response as is in your requested service</p><p><em>public_flag</em>: Public Flag to allow endpoints that can’t need an Authorizer Service.</p><p><em>error_flag</em>: Error flag name of your: return_error_details, on your Krakend backends configuration</p><h3>Endpoint Config</h3><p>Create an endpoint similar to this:</p><pre>{<br>            &quot;endpoint&quot;: &quot;/clients&quot;,<br>            &quot;method&quot;: &quot;GET&quot;,<br>            &quot;output_encoding&quot;: &quot;json&quot;,<br>            &quot;input_headers&quot;: [<br>                &quot;Authorization&quot;,<br>                &quot;Content-Type&quot;,<br>                &quot;{{ env &quot;TOKEN_HEADER&quot; }}&quot;,<br>                &quot;api_id&quot;,<br>                &quot;client_id&quot;,<br>                &quot;x-request-id&quot;,<br>                &quot;x-origin&quot;,<br>                &quot;Accept-Encoding&quot;<br>            ],<br>            &quot;backend&quot;: [<br>                {<br>                    &quot;url_pattern&quot;: &quot;/v1/example&quot;,<br>                    &quot;encoding&quot;: &quot;json&quot;,<br>                    &quot;method&quot;: &quot;GET&quot;,<br>                    &quot;host&quot;: [<br>                        &quot;{{ env &quot;API_EXAMPLE_URL&quot; }}&quot;<br>                    ],<br>                    &quot;extra_config&quot;: {<br>                        &quot;backend/http&quot;: {<br>                            &quot;return_error_details&quot;: &quot;{{ env &quot;ERROR_FLAG&quot; }}&quot;<br>                        },<br>                        &quot;qos/http-cache&quot;: {<br>                            &quot;shared&quot;: false<br>                        }<br>                    }<br>                }<br>            ]<br>        }</pre><p>Note: in your input headers, you will need to add these headers:</p><pre>&quot;{{ env &quot;TOKEN_HEADER&quot; }}&quot;,<br>&quot;api_id&quot;,<br>&quot;client_id&quot;,<br>&quot;x-request-id&quot;</pre><p>Run KrakenD with FC_ENABLE=1</p><pre>ERROR_FLAG=&quot;myerror_flag&quot; PUBLIC_FLAG=&quot;/public/&quot; FC_ENABLE=1 TOKEN_HEADER=&quot;token&quot; AUTHORIZER_SERVICE_URL=&quot;http://localhost:8088&quot; API_EXAMPLE_URL=&quot;http://localhost:8888&quot; KRAKEND_PORT=8001 krakend run -d -c ./krakend.json -p 8001</pre><p>Pass the environment args before running your Krakend application.</p><p>Note: The AUTHORIZER_SERVICE_URL is the project that I’ve made and specified above in this article: <a href="https://github.com/castmetal/golang-token-api-authorizer">https://github.com/castmetal/golang-token-api-authorizer</a></p><p>If you run your Krakend with debug enabled, you will receive this log information:</p><p>INFO [SERVICE: Handler Plugin] Total plugins loaded: 1</p><p>It indicates if your plugin was loaded.</p><p><strong>Send a request to your private endpoint.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*cHLw3ttivnXewzqe0ldyig.png" /></figure><p>And that’s it!</p><p>Accessing logs from the authorizer you will give a prompt like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j9MgQuI3l-ImuiGBFtmO2Q.png" /></figure><p>And your resource will receive the trace id, remote ip, token, api id, and client id from Krakend.</p><p>In this authorizer, I’ve been concerned about the salt security with the 128bits encryption key, API ID using ulid, and client id using uuid, which request a Redis database with a time range, and provides a PostgreSQL alternative to scale up these requests.</p><p>And now, your private APIs will be more safety, and you can block public access from the entire internet and give access by only your Krakend API Gateway requesting to a VPC or inside the network of your cluster APIs.</p><h3>Conclusion</h3><p>Krakend is a great alternative for controlling the security, load balancer, tracing, and rating limits and you can create your own rules as long as you need.</p><p>Enjoy it!</p><p>For further information access my github: https://www.github.com/castmetal</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffb484e2e75" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>