<?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 Cheruiyot Seasoned on Medium]]></title>
        <description><![CDATA[Stories by Cheruiyot Seasoned on Medium]]></description>
        <link>https://medium.com/@briancheruiyot00?source=rss-22796afa4d56------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Me2NlJwZFJkzRBC2BvVNxQ.jpeg</url>
            <title>Stories by Cheruiyot Seasoned on Medium</title>
            <link>https://medium.com/@briancheruiyot00?source=rss-22796afa4d56------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 13:41:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@briancheruiyot00/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[Fix “Bad Permissions” SSH Key Error on Windows (Step-by-Step PowerShell Guide)]]></title>
            <link>https://medium.com/@briancheruiyot00/fix-bad-permissions-ssh-key-error-on-windows-step-by-step-powershell-guide-5a35e0b8bde1?source=rss-22796afa4d56------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a35e0b8bde1</guid>
            <category><![CDATA[powershell]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[server-administration]]></category>
            <category><![CDATA[ssh]]></category>
            <dc:creator><![CDATA[Cheruiyot Seasoned]]></dc:creator>
            <pubDate>Mon, 27 Oct 2025 03:01:00 GMT</pubDate>
            <atom:updated>2025-10-27T03:01:00.756Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YBaTX2OOGyGqlNl7sqXgGw.png" /></figure><h3>If you’ve ever tried connecting to a Linux server from Windows using SSH and got this scary message:</h3><pre>@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@<br>@ WARNING: UNPROTECTED PRIVATE KEY FILE! @<br>@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@<br>Permissions for &#39;C:\Users\user\.ssh\keyname&#39; are too open</pre><p>…it means your private SSH key file can be read by other users — and <strong>SSH refuses to use insecure keys</strong>.</p><p>Here’s how to fix it properly using PowerShell.</p><h3>Step 1 — Open PowerShell as Administrator</h3><p>Click <strong>Start → type “PowerShell” → right-click → “Run as Administrator.”</strong></p><h3>Step 2 — Secure Your SSH Key</h3><p>Let’s assume your key file is called myserverkey and located in:</p><p>C:\Users\user\.ssh\myserverkey</p><p>Run the following commands <strong>exactly as shown</strong>:</p><p># Remove inherited permissions</p><pre>icacls &quot;C:\Users\user\.ssh\myserverkey&quot; /inheritance:r</pre><p># Remove access for everyone else</p><pre>icacls &quot;C:\Users\user\.ssh\myserverkey&quot; /remove &quot;NT</pre><p>AUTHORITY\SYSTEM” “BUILTIN\Administrators” “Everyone”</p><pre># Give only your Windows user read-only permission<br>icacls &quot;C:\Users\user\.ssh\myserverkey&quot; /grant &quot;${env:USERNAME}:(R)&quot;</pre><p><strong>This ensures only you can read the key file</strong>, which makes it secure and usable by SSH.</p><h3>Step 3 — Verify the Permissions</h3><p>Run:</p><pre>icacls &quot;C:\Users\user\.ssh\myserverkey&quot;</pre><p>You should see something like:</p><p><strong><em>C:\Users\user\.ssh\myserverkey user:(R)</em></strong></p><p>Successfully processed 1 files; Failed processing 0 files</p><p>That’s perfect. If you see other users listed (e.g. SYSTEM or Administrators), remove them again.</p><h3>Step 4 — Test SSH Access (and Make It Easier with a Host Shortcut)</h3><p>Now let’s test your SSH connection manually first:</p><pre>ssh -i C:\Users\user\.ssh\myserverkey root@211.71.248.31</pre><p>You should now connect <strong>without any “bad permissions” warnings.</strong></p><p>But typing that long command every time gets tiring.<br> Let’s simplify it by creating a <strong>shortcut configuration</strong>.</p><h3>Create an SSH Host Alias (e.g. test-server)</h3><ol><li>Open or create this file:</li></ol><ul><li>C:\Users\user\.ssh\config</li><li>If the file doesn’t exist, just create a new text file named config (no extension) inside the .ssh folder.</li></ul><ol><li>Add the following lines:</li></ol><pre>Host test-server    <br>     HostName 211.71.248.31     <br>     Port 22     <br>     User root     <br>     IdentityFile C:\Users\user\.ssh\myserverkey</pre><ul><li><strong>Host</strong> → your custom nickname for the server</li><li><strong>HostName</strong> → the server’s IP address</li><li><strong>User</strong> → the login user (e.g. root)</li><li><strong>IdentityFile</strong> → path to your private key</li></ul><ol><li>Save the file and close it.</li></ol><h3>Test the Shortcut</h3><p>Now you can connect using just:</p><pre>ssh test-server</pre><p>That’s it — no need to type the full command or specify the key path again.</p><h3>Step 5 — Apply the Same Fix to Other Keys</h3><p>If you have multiple private keys (for example, myserverkey-prod), just repeat the steps above — replacing the filename.</p><p>Example:</p><pre>icacls &quot;C:\Users\user\.ssh\myserverkey-prod&quot; /inheritance:r<br>icacls &quot;C:\Users\user\.ssh\myserverkey-prod&quot; /remove &quot;NT AUTHORITY\SYSTEM&quot; &quot;BUILTIN\Administrators&quot; &quot;Everyone&quot;<br>icacls &quot;C:\Users\user\.ssh\myserverkey-prod&quot; /grant &quot;${env:USERNAME}:(R)&quot;</pre><h3>Bonus: Fix All Keys in One Go</h3><p>If you want to secure <strong>all</strong> private keys in your .ssh folder automatically:</p><pre>Get-ChildItem &quot;$env:USERPROFILE\.ssh\&quot; -File | ForEach-Object {<br>icacls $_.FullName /inheritance:r<br>icacls $_.FullName /remove &quot;NT AUTHORITY\SYSTEM&quot; &quot;BUILTIN\Administrators&quot; &quot;Everyone&quot;<br>icacls $_.FullName /grant &quot;${env:USERNAME}:(R)&quot;<br>}</pre><h3>Why This Matters</h3><p>SSH strictly enforces permissions on private keys to prevent leaks.<br> If anyone else (even SYSTEM or Administrators) can read your key, SSH will reject it for safety.<br> These commands make sure your SSH setup is <strong>secure and compliant</strong>.</p><h3>Author’s Note</h3><p>If you found this helpful, save this script as fix-ssh-key.ps1 for quick reuse, or share this guide with your teammates.<br> It’ll save you hours of frustration when setting up servers or automating deployments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a35e0b8bde1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating M-Pesa B2C API with PHP: A Complete Guide]]></title>
            <link>https://medium.com/@briancheruiyot00/integrating-m-pesa-b2c-api-with-php-a-complete-guide-328bbb3c39c2?source=rss-22796afa4d56------2</link>
            <guid isPermaLink="false">https://medium.com/p/328bbb3c39c2</guid>
            <category><![CDATA[b2c]]></category>
            <category><![CDATA[mpesa-api]]></category>
            <category><![CDATA[mpesa-integration]]></category>
            <category><![CDATA[mpesab2c]]></category>
            <category><![CDATA[mpesa]]></category>
            <dc:creator><![CDATA[Cheruiyot Seasoned]]></dc:creator>
            <pubDate>Tue, 25 Feb 2025 08:59:04 GMT</pubDate>
            <atom:updated>2025-02-25T09:22:27.191Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Safaricom’s M-Pesa B2C API allows businesses to send payments directly to customers’ mobile wallets. This is essential for salary disbursements, refunds, and rewards. In this guide, we’ll cover everything from authentication to handling transaction callbacks securely using PHP.</p><h3>1. Understanding the M-Pesa B2C API</h3><h3>What is the B2C API?</h3><p>M-Pesa’s B2C (Business to Customer) API enables businesses to send payments directly to users. This is useful for:<br> ✔ Salary payments<br> ✔ Loan disbursements<br> ✔ Refunds<br> ✔ Promotional payouts</p><p>The API works by sending a request to Safaricom’s servers, which process the payment and return a response.</p><h3>2. Required Credentials &amp; Setup 🛠</h3><p>Before using the API, you need credentials from the <a href="https://developer.safaricom.co.ke/">Safaricom Developer Portal</a>.</p><h3>Required Credentials:</h3><ul><li><strong>Consumer Key</strong> &amp; <strong>Consumer Secret</strong>: Used to authenticate API requests.</li><li><strong>B2C Shortcode</strong>: Your Paybill or Till Number.</li><li><strong>Initiator Name</strong>: The M-Pesa account username authorized to make transactions. In Most cases you need to create an API operator on the mpesa portal. And set up a password for that operator by logging in as a business manager, if there isn’t any business manager then create one.</li><li><strong>Security Credential</strong>: A password encrypted using Safaricom’s public key. This will be the password that has been assigned to the operator by the business manager.</li><li><strong>API URLs</strong>:</li><li><strong>Sandbox</strong>: <a href="https://sandbox.safaricom.co.ke/mpesa/b2c/v1/paymentrequest">https://sandbox.safaricom.co.ke/mpesa/b2c/v1/paymentrequest</a></li><li><strong>Production</strong>: <a href="https://api.safaricom.co.ke/mpesa/b2c/v1/paymentrequest">https://api.safaricom.co.ke/mpesa/b2c/v1/paymentrequest</a></li></ul><h3>3. Authentication: Getting the Access Token 🔑</h3><p>Before making API requests, you need an access token:</p><pre>function get_accesstoken() {<br>    $credentials = base64_encode(CONSUMER_KEY . &#39;:&#39; . CONSUMER_SECRET);<br>    $ch = curl_init();<br>    curl_setopt($ch, CURLOPT_URL, &#39;https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials&#39;);<br>    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);<br>    curl_setopt($ch, CURLOPT_HTTPHEADER, array(&#39;Authorization: Basic &#39; . $credentials, &#39;Content-Type: application/json&#39;));<br>    $response = curl_exec($ch);<br>    curl_close($ch);<br>    return json_decode($response)-&gt;access_token;<br>}</pre><h3>4. Encrypting Security Credentials 🔐</h3><p>To secure transactions, encrypt your <strong>Initiator Password</strong> using Safaricom’s public key. Here’s how to do it using OpenSSL in PHP:</p><pre>function encrypt_security_credential($plaintext) {<br>    $publicKey = file_get_contents(&#39;cert/safaricom_public.crt&#39;); // Ensure you have the public key<br>    openssl_public_encrypt($plaintext, $encrypted, $publicKey, OPENSSL_PKCS1_PADDING);<br>    return base64_encode($encrypted);<br>}</pre><h3>5. Making a B2C Payment Request 💰</h3><p>Once authenticated, you can send a payment request:</p><pre>function b2c_request($amount, $msisdn, $remarks) {<br>    $data = array(<br>        &#39;InitiatorName&#39; =&gt; &#39;your_initiator_name&#39;,<br>        &#39;SecurityCredential&#39; =&gt; encrypt_security_credential(&#39;your_plaintext_password&#39;),<br>        &#39;CommandID&#39; =&gt; &#39;BusinessPayment&#39;,<br>        &#39;Amount&#39; =&gt; $amount,<br>        &#39;PartyA&#39; =&gt; &#39;600000&#39;, // Your shortcode<br>        &#39;PartyB&#39; =&gt; $msisdn,<br>        &#39;Remarks&#39; =&gt; $remarks,<br>        &#39;QueueTimeOutURL&#39; =&gt; &#39;https://yourdomain.com/mpesa/b2c_callback.php&#39;,<br>        &#39;ResultURL&#39; =&gt; &#39;https://yourdomain.com/mpesa/b2c_callback.php&#39;,<br>        &#39;Occasion&#39; =&gt; &#39;&#39;<br>    );</pre><pre>    $accessToken = get_accesstoken();<br>    $ch = curl_init(&#39;https://api.safaricom.co.ke/mpesa/b2c/v1/paymentrequest&#39;);<br>    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);<br>    curl_setopt($ch, CURLOPT_HTTPHEADER, array(<br>        &#39;Authorization: Bearer &#39; . $accessToken,<br>        &#39;Content-Type: application/json&#39;<br>    ));<br>    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));<br>    $response = curl_exec($ch);<br>    curl_close($ch);</pre><pre>    return json_decode($response);<br>}</pre><h3>6. Handling M-Pesa B2C Callbacks 🔄</h3><p>M-Pesa will send a callback response to the URL provided in the request (ResultURL). You need to process this response and store it in your database.</p><h3>Callback Response Processing</h3><pre>$callbackJSONData = file_get_contents(&#39;php://input&#39;);<br>$data = json_decode($callbackJSONData, true);</pre><pre>if ($data &amp;&amp; isset($data[&#39;Result&#39;])) {<br>    $resultCode = $data[&#39;Result&#39;][&#39;ResultCode&#39;];<br>    $transactionId = $data[&#39;Result&#39;][&#39;TransactionID&#39;] ?? null;<br>    $conversationId = $data[&#39;Result&#39;][&#39;ConversationID&#39;] ?? null;<br>    $originatorConversationId = $data[&#39;Result&#39;][&#39;OriginatorConversationID&#39;] ?? null;<br>    $resultDesc = $data[&#39;Result&#39;][&#39;ResultDesc&#39;];</pre><pre>    // Extract transaction details<br>    $params = [];<br>    if (isset($data[&#39;Result&#39;][&#39;ResultParameters&#39;][&#39;ResultParameter&#39;])) {<br>        foreach ($data[&#39;Result&#39;][&#39;ResultParameters&#39;][&#39;ResultParameter&#39;] as $param) {<br>            $params[$param[&#39;Key&#39;]] = $param[&#39;Value&#39;];<br>        }<br>    }</pre><pre>    if ($resultCode == 0) {<br>        $transactionReceipt = $params[&#39;TransactionReceipt&#39;] ?? &#39;N/A&#39;;<br>        $transactionAmount = $params[&#39;TransactionAmount&#39;] ?? 0;<br>        $receiverParty = $params[&#39;ReceiverPartyPublicName&#39;] ?? &#39;Unknown&#39;;<br>        $completedTime = $params[&#39;TransactionCompletedDateTime&#39;] ?? &#39;N/A&#39;;</pre><pre>        // Store transaction in database<br>        $mysqli = new mysqli(&quot;localhost&quot;, &quot;username&quot;, &quot;password&quot;, &quot;database&quot;);<br>        if ($mysqli-&gt;connect_error) {<br>            die(&quot;Database connection failed: &quot; . $mysqli-&gt;connect_error);<br>        }<br>        $stmt = $mysqli-&gt;prepare(&quot;INSERT INTO mpesa_b2c_transactions <br>            (transaction_id, conversation_id, originator_conversation_id, transaction_receipt, amount, receiver_party, completed_time, result_desc) <br>            VALUES (?, ?, ?, ?, ?, ?, ?, ?)&quot;);</pre><pre>        $stmt-&gt;bind_param(&quot;ssssisss&quot;, $transactionId, $conversationId, $originatorConversationId, $transactionReceipt, $transactionAmount, $receiverParty, $completedTime, $resultDesc);<br>        $stmt-&gt;execute();<br>        $stmt-&gt;close();<br>        $mysqli-&gt;close();<br>    }<br>}</pre><h3>7. Creating the Database Table 🗄</h3><p>Run this SQL query to create the transactions table:</p><pre>CREATE TABLE mpesa_b2c_transactions (<br>    id INT AUTO_INCREMENT PRIMARY KEY,<br>    transaction_id VARCHAR(50) UNIQUE NOT NULL,<br>    conversation_id VARCHAR(50) NOT NULL,<br>    originator_conversation_id VARCHAR(50) NOT NULL,<br>    transaction_receipt VARCHAR(50) NOT NULL,<br>    amount DECIMAL(10,2) NOT NULL,<br>    receiver_party VARCHAR(100) NOT NULL,<br>    completed_time DATETIME NOT NULL,<br>    result_desc TEXT NOT NULL,<br>    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP<br>);</pre><h3>Conclusion 🎉</h3><p>You’ve successfully integrated the Safaricom M-Pesa B2C API! 🚀 Now, your system can:<br> ✅ Authenticate API requests<br> ✅ Encrypt credentials for security<br> ✅ Send payments via B2C API<br> ✅ Handle M-Pesa callback responses<br> ✅ Store transactions in a MySQL database</p><p>This implementation ensures a <strong>secure, automated, and efficient</strong> payment flow for your business.</p><p>💡 <strong>Next Steps:</strong></p><ul><li>Set up a <strong>CRON job</strong> to monitor failed transactions.</li><li>Implement <strong>error handling</strong> for failed requests.</li><li>Use <strong>logging</strong> to track API requests and responses.</li></ul><p>Have any questions or feedback? Drop them in the comments! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=328bbb3c39c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplify API Calls with Spring Boot Reactive Programming]]></title>
            <link>https://medium.com/@briancheruiyot00/simplify-api-calls-with-spring-boot-reactive-programming-2146899c77ee?source=rss-22796afa4d56------2</link>
            <guid isPermaLink="false">https://medium.com/p/2146899c77ee</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Cheruiyot Seasoned]]></dc:creator>
            <pubDate>Tue, 19 Nov 2024 06:47:11 GMT</pubDate>
            <atom:updated>2024-11-19T06:52:03.600Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Springboot webflux reactive programming" src="https://cdn-images-1.medium.com/max/407/1*qlzhr10QMoTzIOA3a-sL-g.png" /></figure><p>Reactive programming is transforming how we build scalable and responsive applications. With Spring WebFlux, you can create non-blocking, asynchronous systems that efficiently handle large volumes of requests. In this article, we’ll demonstrate how to build a reactive web client for interacting with external APIs using a hypothetical example.</p><p><strong>Why Use Reactive Programming?</strong></p><p>Traditional applications block threads while waiting for operations like I/O, resulting in inefficiencies under heavy loads. Reactive programming enables:</p><ul><li><strong>Non-blocking execution</strong>: Operations proceed without waiting for others to complete.</li><li><strong>Scalability</strong>: Handles high concurrency with minimal resources.</li><li><strong>Better user experience</strong>: Reduced response times.</li></ul><h3>Setting Up a Reactive Web Client</h3><p>Let’s walk through a Spring Boot WebFlux client that interacts with an external API. The client fetches an authentication token and uses it to make various API calls, such as fetching user data and retrieving reports.</p><h3>Sample Reactive Web Client Code</h3><p>Below is the core implementation of a WebFlux client:</p><pre>package com.example.api.client;<br><br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.stereotype.Component;<br>import org.springframework.web.reactive.function.BodyInserters;<br>import org.springframework.web.reactive.function.client.ExchangeStrategies;<br>import org.springframework.web.reactive.function.client.WebClient;<br>import reactor.core.publisher.Mono;<br><br>import java.time.Instant;<br>import java.util.HashMap;<br>import java.util.Map;<br>import java.util.concurrent.atomic.AtomicReference;<br><br>@Component<br>public class ReactiveApiClient {<br><br>    @Value(&quot;${api.client.key}&quot;)<br>    private String apiKey;<br><br>    @Value(&quot;${api.client.secret}&quot;)<br>    private String apiSecret;<br><br>    @Value(&quot;${api.base.url}&quot;)<br>    private String apiBaseUrl;<br><br>    private final WebClient webClient;<br>    private final AtomicReference&lt;String&gt; accessToken = new AtomicReference&lt;&gt;();<br>    private final AtomicReference&lt;Instant&gt; tokenExpiration = new AtomicReference&lt;&gt;();<br><br>    public ReactiveApiClient(WebClient.Builder webClientBuilder) {<br>        int bufferSize = 16 * 1024 * 1024; // 16MB buffer size<br>        ExchangeStrategies strategies = ExchangeStrategies.builder()<br>                .codecs(configurer -&gt; configurer.defaultCodecs().maxInMemorySize(bufferSize))<br>                .build();<br><br>        this.webClient = webClientBuilder.exchangeStrategies(strategies).build();<br>    }<br><br>    // Retrieve or refresh the authentication token<br>    private Mono&lt;String&gt; getToken() {<br>        if (accessToken.get() != null &amp;&amp; Instant.now().isBefore(tokenExpiration.get())) {<br>            return Mono.just(accessToken.get());<br>        } else {<br>            return fetchAccessToken();<br>        }<br>    }<br><br>    private Mono&lt;String&gt; fetchAccessToken() {<br>        Map&lt;String, String&gt; requestBody = new HashMap&lt;&gt;();<br>        requestBody.put(&quot;key&quot;, apiKey);<br>        requestBody.put(&quot;secret&quot;, apiSecret);<br><br>        return webClient.post()<br>                .uri(apiBaseUrl + &quot;/auth/token&quot;)<br>                .body(BodyInserters.fromValue(requestBody))<br>                .retrieve()<br>                .bodyToMono(TokenResponse.class)<br>                .doOnNext(tokenResponse -&gt; {<br>                    accessToken.set(tokenResponse.getAccessToken());<br>                    Instant expirationTime = Instant.now().plusSeconds(tokenResponse.getExpiresIn());<br>                    tokenExpiration.set(expirationTime);<br>                })<br>                .map(TokenResponse::getAccessToken);<br>    }<br><br>    // Example API call to fetch user data<br>    public Mono&lt;UserDataResponse&gt; getUserData(String userId) {<br>        return getToken()<br>                .flatMap(token -&gt; webClient.get()<br>                        .uri(apiBaseUrl + &quot;/users/&quot; + userId)<br>                        .header(&quot;Authorization&quot;, &quot;Bearer &quot; + token)<br>                        .retrieve()<br>                        .bodyToMono(UserDataResponse.class)<br>                );<br>    }<br><br>    // Example API call to fetch report data<br>    public Mono&lt;ReportDataResponse&gt; getReportData(String reportId, String startDate, String endDate) {<br>        Map&lt;String, String&gt; requestBody = new HashMap&lt;&gt;();<br>        requestBody.put(&quot;reportId&quot;, reportId);<br>        requestBody.put(&quot;startDate&quot;, startDate);<br>        requestBody.put(&quot;endDate&quot;, endDate);<br><br>        return getToken()<br>                .flatMap(token -&gt; webClient.post()<br>                        .uri(apiBaseUrl + &quot;/reports&quot;)<br>                        .header(&quot;Authorization&quot;, &quot;Bearer &quot; + token)<br>                        .header(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>                        .body(BodyInserters.fromValue(requestBody))<br>                        .retrieve()<br>                        .bodyToMono(ReportDataResponse.class)<br>                );<br>    }<br><br>    // Token Response DTO<br>    private static class TokenResponse {<br>        private String accessToken;<br>        private int expiresIn;<br><br>        public String getAccessToken() {<br>            return accessToken;<br>        }<br><br>        public int getExpiresIn() {<br>            return expiresIn;<br>        }<br>    }<br>}</pre><h3>How It Works</h3><ol><li><strong>Token Management</strong>:</li></ol><ul><li>The getToken() method checks if the current token is valid.</li><li>If expired, it retrieves a new token via fetchAccessToken().</li></ul><p><strong>2. Making API Calls</strong>:</p><ul><li>Calls like getUserData() or getReportData() use the token fetched by getToken() to authenticate.</li><li>HTTP requests are made asynchronously using WebFlux’s WebClient.</li></ul><p><strong>3. Efficient Resource Usage</strong>:</p><ul><li>The client handles I/O operations without blocking threads, ensuring high scalability.</li></ul><h3>Benefits of Using Reactive WebFlux</h3><ul><li><strong>Effortless Concurrency</strong>: Built-in support for asynchronous data streams.</li><li><strong>Enhanced Performance</strong>: Non-blocking I/O for better throughput.</li><li><strong>Simplified API Consumption</strong>: Fluent and declarative APIs for handling requests and responses.</li></ul><h3>Conclusion</h3><p>Spring WebFlux makes building reactive applications straightforward. The ReactiveApiClient demonstrated how you can implement token management and make API calls seamlessly in a non-blocking manner. Whether you&#39;re integrating with external APIs or building scalable microservices, reactive programming with WebFlux is a powerful tool for modern software development.</p><p>Ready to make your applications reactive? Give it a try with Spring Boot!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2146899c77ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Swagger UI with Basic Authentication(Login popup) in Spring Boot]]></title>
            <link>https://medium.com/@briancheruiyot00/securing-swagger-ui-with-basic-authentication-login-popup-in-spring-boot-8b8bdd9ca931?source=rss-22796afa4d56------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b8bdd9ca931</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[swagger-ui]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[api-security]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Cheruiyot Seasoned]]></dc:creator>
            <pubDate>Mon, 29 Jan 2024 07:37:40 GMT</pubDate>
            <atom:updated>2024-01-29T07:37:40.851Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*i2VrpzKt221HOVIjLZLuxw.png" /><figcaption>swager security</figcaption></figure><p><strong>Introduction</strong></p><p>Swagger UI is a powerful tool for visualizing and interacting with APIs. However, exposing it publicly can pose security risks. In this article, we’ll explore how to enhance the security of Swagger UI in a Spring Boot application by implementing Basic Authentication with the help of a login popup just before the UI is visible.</p><p><strong>Setting Up Basic Authentication:</strong></p><p>To implement Basic Authentication for Swagger UI, we’ll create a custom filter in our Spring Boot application.Copy this code to your application main file.</p><pre>@Bean<br>public FilterRegistrationBean&lt;SwaggerBasicAuthFilter&gt; swaggerBasicAuthFilterRegistration() {<br>    FilterRegistrationBean&lt;SwaggerBasicAuthFilter&gt; registrationBean = new FilterRegistrationBean&lt;&gt;();<br>    registrationBean.setFilter(new SwaggerBasicAuthFilter());<br>    registrationBean.addUrlPatterns(&quot;/swagger/*&quot;, &quot;/v2/api-docs&quot;, &quot;/swagger-ui.html&quot;);<br>    registrationBean.setName(&quot;SwaggerBasicAuthFilter&quot;);<br>    return registrationBean;<br>}</pre><p>This code configures a filter that intercepts requests to Swagger UI endpoints and applies Basic Authentication.</p><pre><br>import jakarta.servlet.FilterChain;<br>import jakarta.servlet.ServletException;<br>import jakarta.servlet.http.HttpServletRequest;<br>import jakarta.servlet.http.HttpServletResponse;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.stereotype.Component;<br>import org.springframework.web.filter.OncePerRequestFilter;<br><br>import java.io.IOException;<br>import java.nio.charset.StandardCharsets;<br>import java.util.Base64;<br>@Component<br>public class SwaggerBasicAuthFilter extends OncePerRequestFilter {<br>    /** Save your credentials on application.properties @value anotation will fetch<br>the credentials**/<br>    @Value(&quot;${swagger.username}&quot;)<br>    private String swaggerUsername;<br>    @Value(&quot;${swagger.password}&quot;)<br>    private String swaggerPassword;<br>    Logger logger= LoggerFactory.getLogger(this.getClass());<br>    @Override<br>    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)<br>            throws ServletException, IOException {<br><br>        String requestUri = request.getRequestURI();<br><br>        if (isRestrictedUrl(requestUri)) {<br>            String authHeader = request.getHeader(&quot;Authorization&quot;);<br><br>            if (authHeader != null &amp;&amp; authHeader.startsWith(&quot;Basic &quot;)) {<br>                String[] credentials = extractAndDecodeHeader(authHeader);<br><br>                if (isAuthorized(credentials[0], credentials[1])) {<br>                    chain.doFilter(request, response);<br>                    return;<br>                }<br>            }<br><br>            response.setHeader(&quot;WWW-Authenticate&quot;, &quot;Basic realm=\&quot;Swagger\&quot;&quot;);<br>            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);<br>            return;<br>        }<br><br>        chain.doFilter(request, response);<br>    }<br><br>    private boolean isRestrictedUrl(String requestUri) {<br>        return requestUri.startsWith(&quot;/swagger&quot;) || requestUri.startsWith(&quot;/api-docs&quot;) || requestUri.startsWith(&quot;/swagger-ui.html&quot;);<br>    }<br><br>    private boolean isAuthorized(String username, String password) {<br>        logger.info(swaggerUsername+&quot;:&quot;+swaggerPassword);<br>        return username.equals(swaggerUsername) &amp;&amp; password.equals(swaggerPassword);<br>    }<br><br>    private String[] extractAndDecodeHeader(String header) throws IOException {<br>        byte[] base64Token = header.substring(6).getBytes(StandardCharsets.UTF_8);<br>        byte[] decoded;<br>        try {<br>            decoded = Base64.getDecoder().decode(base64Token);<br>        } catch (IllegalArgumentException e) {<br>            throw new RuntimeException(&quot;Failed to decode basic authentication token&quot;);<br>        }<br><br>        String token = new String(decoded, StandardCharsets.UTF_8);<br><br>        int delim = token.indexOf(&quot;:&quot;);<br><br>        if (delim == -1) {<br>            throw new RuntimeException(&quot;Invalid basic authentication token&quot;);<br>        }<br><br>        return new String[]{token.substring(0, delim), token.substring(delim + 1)};<br>    }<br>}</pre><p>This class defines a filter that checks for Basic Authentication credentials before allowing access to Swagger UI endpoints. It reads the username and password from environment variables.</p><p>Explanation:</p><ul><li>The SwaggerBasicAuthFilter extends OncePerRequestFilter, ensuring it&#39;s executed only once per request.</li><li>In the doFilterInternal method, it intercepts requests to Swagger UI endpoints.</li><li>It checks if the request is for a restricted URL and if it contains Basic Authentication credentials.</li><li>If the credentials are valid, the request is allowed to proceed; otherwise, a 401 Unauthorized response is sent.</li><li>Basic Authentication credentials are compared against the values stored in environment variables.</li><li>The extractAndDecodeHeader method decodes the Basic Authentication token.</li></ul><p>Conclusion: By implementing Basic Authentication with a custom filter, we’ve enhanced the security of Swagger UI in our Spring Boot application. This ensures that only authorized users can access the API documentation, reducing the risk of unauthorized access.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b8bdd9ca931" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>