<?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 Surangi Kanchana on Medium]]></title>
        <description><![CDATA[Stories by Surangi Kanchana on Medium]]></description>
        <link>https://medium.com/@rangika123.kanchana?source=rss-7e25ecd9e014------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*j8GnRmORe3BZKqR1-WJAxg.png</url>
            <title>Stories by Surangi Kanchana on Medium</title>
            <link>https://medium.com/@rangika123.kanchana?source=rss-7e25ecd9e014------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 19:48:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rangika123.kanchana/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Configure PostgreSQL 17 on Amazon Linux 2023]]></title>
            <link>https://medium.com/@rangika123.kanchana/how-to-configure-postgresql-17-on-amazon-linux-2023-da9426261620?source=rss-7e25ecd9e014------2</link>
            <guid isPermaLink="false">https://medium.com/p/da9426261620</guid>
            <category><![CDATA[postgresql-database]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[amazon-linux-2023]]></category>
            <category><![CDATA[amazon-linux]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Surangi Kanchana]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 07:42:27 GMT</pubDate>
            <atom:updated>2025-08-13T07:42:27.160Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DHe0TNFJjVHObIackINfJA.png" /></figure><p>Configuring PostgreSQL on Amazon Linux 2023 is a critical step for developers and system administrators looking to build scalable, secure, and high-performance applications. PostgreSQL, known for its reliability and feature richness, pairs well with Amazon Linux 2023 — a stable, security-focused operating system optimized for the cloud. Whether you’re setting up a production-grade database or a development environment, understanding the configuration process ensures smooth integration, better performance, and easier maintenance. This guide will walk you through the essentials of installing and configuring PostgreSQL 17 on Amazon Linux 2023, explaining not only how to perform each step but also why it’s important.</p><h3><strong>Step 1: Update System Packages</strong></h3><p>Before installing any software, it’s a good idea to update your system packages.</p><pre>sudo dnf update</pre><p><strong>Why?</strong><br> Keeping packages up to date ensures you have the latest security patches and compatibility for new software like PostgreSQL 17.</p><h3><strong>Step 2: Upgrade Amazon Linux Version (if needed)</strong></h3><p>PostgreSQL 17 is supported on <strong>Amazon Linux 2023.7 and above</strong>. If you are on <strong>2023.6 or older</strong>, you must upgrade: Here I’m upgrading to latest version</p><pre>sudo dnf upgrade --releasever=2023.8.20250804</pre><p><strong>Why?</strong><br> Older versions of AL2023 might not support PostgreSQL 17 due to dependency and package availability issues.</p><p>or else when you install Postgres, you will get an error by saying</p><pre>Error: Unable to find a match: postgresql17.x86_64 postgresql17-server</pre><h3><strong>Step 3: Install PostgreSQL 17</strong></h3><p>You can find a complete list of available packages in the Amazon Linux 2023 repositories by referring to: <a href="https://docs.aws.amazon.com/linux/al2023/release-notes/all-packages-AL2023.8.html">Amazon Linux 2023 release note</a></p><pre>sudo dnf install postgresql17.x86_64 postgresql17-server -y</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*AYosooHKInUiuwZP1jrNZw.png" /></figure><p><strong>Why?</strong><br> Installs both the PostgreSQL client and server:</p><p>postgresql17 – Installs the PostgreSQL client tools (like psql) that let you connect to and interact with a PostgreSQL server.</p><p>postgresql17-server – Installs the server-side binaries and services required to run the PostgreSQL database engine itself.</p><p>The -y flag automatically answers &quot;yes&quot; to any installation prompts.</p><p>Version 17 is the latest release with enhanced performance and security features.</p><h3><strong>Step 4: Initialize the PostgreSQL Database</strong></h3><pre>sudo postgresql-setup --initdb</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*--E6oey8r8WMA7leWJvrHQ.png" /></figure><p><strong>Why?</strong></p><p>It initializes the PostgreSQL data directory (usually /var/lib/pgsql/data) with the required structure and default configuration files. <a href="https://www.postgresql.org/docs/current/app-initdb.html">Refere this link</a></p><p>It creates system tables and default roles and sets up the database cluster.</p><p>This step is required before starting the PostgreSQL service for the first time.</p><p>In short, it prepares PostgreSQL to run by setting up the internal database files. Without this, the server can’t start.</p><h3><strong>Step 5: Start and Enable PostgreSQL Service</strong></h3><pre>sudo systemctl start postgresql</pre><p><strong>Why?</strong></p><p>Starts the <strong>PostgreSQL database server</strong> service. The server process (postgres) begins running in the background. PostgreSQL starts listening for connections on the configured port (default: <strong>5432</strong>).</p><p>This step is necessary to make the database accessible for use after initialization.</p><pre>sudo systemctl enable postgresql</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*C7cAM2MFAwIVWaTnT1-_LA.png" /></figure><p><strong>Why?</strong></p><p>Configures <strong>PostgreSQL to start automatically</strong> at system boot. Creates necessary symbolic links so the service launches on startup.</p><p>This ensures the PostgreSQL server starts every time the system reboots, without needing to start it manually.</p><h3><strong>Step 6: Check if PostgreSQL is Running</strong></h3><pre>sudo systemctl status postgresql</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ut56KoW43qKeslTGq8nhdg.png" /></figure><p><strong>Why?</strong><br> Verifies that the service is up and running correctly.</p><h3><strong>Step 7: Set PostgreSQL User and Admin Passwords</strong></h3><ol><li><strong>Set password for the Postgres system user (Optional):</strong></li></ol><p>On production servers, avoid setting a password for the postgres system user unless there’s a very specific need.</p><pre>sudo passwd postgres</pre><p><strong>Why?</strong></p><p>This command will change the <strong>system account password</strong> for the postgres user — the OS-level account that owns the PostgreSQL server process and its files.</p><p><strong>Security Risk !</strong></p><p>If this password is weak or leaked, someone can log in directly as the postgres OS user and have full control over the database. The postgres system account has <strong>full filesystem access</strong> to PostgreSQL data — compromising it compromises the entire DB. Most admin tasks can be done using sudo -u postgres &lt;command&gt; without ever setting a password.</p><p>Use sudo -u postgres for administrative commands and change the DB password from within PostgreSQL instead.</p><p>2. <strong>Switch to the </strong><strong>postgres user</strong></p><pre>sudo -u postgres psql</pre><p><strong>Why?</strong></p><p>Instead of logging in as postgres with a password, you can execute commands. This opens the PostgreSQL interactive shell as the database superuser.</p><p>3. <strong>Change the PostgreSQL DB superuser password (not OS password)</strong></p><pre>ALTER USER postgres WITH PASSWORD &#39;your-password&#39;;</pre><p><strong>Why?</strong></p><p>When PostgreSQL is first installed, the postgres superuser account is created without any password by default. You can log in as postgres locally using the operating system account, but for remote connections or password authentication, you must explicitly set a password. Refere document <a href="https://www.postgresql.org/docs/current/auth-password.html">20.5 password authentication</a> for more details. It explicitly says: <em>“If no password has been set up for a user, the stored password is null and password authentication will always fail.</em></p><p>Executes a SQL command to change the password for the PostgreSQL database user named postgres (not the system user).</p><p>&#39;your-password&#39; should be replaced with your desired database login password.</p><p>This sets or updates the password required to log in to PostgreSQL as the postgres database user, especially useful for remote or psql access with authentication.</p><p><strong>Note:</strong> You must run this command as the postgres Linux user or as a database superuser.</p><h3><strong>Step 8: Create a New User</strong></h3><pre>CREATE USER your-username WITH PASSWORD &#39;password&#39;;</pre><p>Creates a dedicated <strong>database role</strong> for your app or for a human user. We don’t want to use the built-in postgres superuser for applications — it has <strong>full, unrestricted power</strong>. By creating a dedicated user, we:</p><p><strong>Limit privileges</strong> to just what the app needs.</p><p><strong>Improve security — </strong>even if the app’s credentials leak, the attacker won’t have superuser access.</p><p><strong>Enable auditing</strong> — queries made by myuser are distinguishable from those by other users.</p><h3><strong>Step 9: Create a New Database</strong></h3><pre>CREATE DATABASE mydatabase;</pre><p>Switch to new database</p><pre>\c mydatabase </pre><h3><strong>Step 10: Grant Permissions</strong></h3><pre>GRANT ALL PRIVILEGES ON DATABASE mydatabase TO myuser;</pre><p><strong>Why?</strong><br> This gives your application user full access to the specific database without exposing the superuser account.</p><p><strong>Note: </strong>Starting with PostgreSQL 15, the default privileges on the public schema are more restrictive: CREATE privilege on the public schema is no longer granted to all users by default<strong>. </strong>This means that non-owner users cannot create tables or objects in the public schema unless explicitly granted permission.</p><p>This is a security improvement to limit accidental data manipulation in the shared public schema.</p><pre>GRANT CREATE ON SCHEMA public TO myuser;</pre><h3><strong>Step 11: Verify Setup</strong></h3><p>List Databases:</p><pre>\l</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4VSB4HGWG8IZzbTv6Um78w.png" /></figure><p>Exit PostgreSQL</p><pre>\q</pre><h3><strong>Step 12: Configure PostgreSQL Settings</strong></h3><p><strong>Allow Remote Connections</strong></p><p>Before modifying config files, create backups:</p><pre>sudo cp /var/lib/pgsql/data/postgresql.conf /var/lib/pgsql/data/postgresql.conf.bc</pre><p>Open the PostgreSQL configuration file:</p><pre>sudo nano /var/lib/pgsql/data/postgresql.conf</pre><p><strong>Why?</strong></p><p>Opens the PostgreSQL 17 main configuration file in the nano text editor with superuser (sudo) privileges.</p><p>Allows you to modify settings like: listen_addresses controls which IP addresses PostgreSQL listens on. port – sets the port PostgreSQL runs on. logging, memory, connections, and performance-related settings.</p><p>Look for:</p><pre>listen_addresses = &#39;localhost&#39; </pre><p>Change this only if you want to allow connections from other machines.</p><p><strong>Why?</strong></p><p>By default, PostgreSQL listens only on localhost for security. Use * to listen on all interfaces, but make sure firewall rules and security groups are properly set.</p><h3><strong>Step 13: Update Authentication</strong></h3><p>Before modifying config files, create backups:</p><pre>sudo cp /var/lib/pgsql/data/pg_hba.conf /var/lib/pgsql/data/pg_hba.conf.bc</pre><p>Open the configuration file:</p><pre>sudo nano /var/lib/pgsql/data/pg_hba.conf</pre><p><strong>Why?</strong></p><p>Opens the PostgreSQL client authentication configuration file in nano with superuser access.</p><p>This file controls who can connect, from where, and how they’re authenticated.</p><p>To allow password authentication from localhost:</p><pre>host    all     all     127.0.0.1/32    scram-sha-256</pre><p><strong>Why?</strong></p><p>scram-sha-256 is more secure than md5. Don’t use trust or ident in production systems.</p><p>Changing authentication type does not automatically migrate stored passwords.</p><p><strong><em>NOTE: </em></strong><em>To secure PostgreSQL, especially in production, follow the principle of least privilege:</em></p><ol><li><strong>Be specific in access rules</strong></li></ol><p>Instead Of:</p><pre>host    all     all     0.0.0.0/0       md5</pre><p>Use:</p><pre>host    mydb     myuser     192.168.1.100/32    scram-sha-256</pre><p>This ensures:</p><blockquote>Only myuser can connect,</blockquote><blockquote>Only to mydb,</blockquote><blockquote>Only from IP 192.168.1.100</blockquote><blockquote>Using secure password authentication</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*_ua6uPijkbKAGECjRLk9qQ.png" /></figure><p><strong>NOTE:</strong></p><p>PostgreSQL checks pg_hba.conf <strong>top to bottom</strong> and uses the <strong>first rule that matches</strong> the connection (type, client address, database, user). <strong>There’s no fall-through</strong>: if that rule is chosen and auth fails, PostgreSQL does <strong>not</strong> try later rules.</p><p>Postgres document state on <a href="https://www.postgresql.org/docs/current/auth-pg-hba-conf.html">20.1. The pg_hba.conf File:</a></p><p><em>Since the </em><em>pg_hba.conf records are examined sequentially for each connection attempt, the order of the records is significant. Typically, earlier records will have tight connection match parameters and weaker authentication methods, while later records will have looser match parameters and stronger authentication methods. For example, one might wish to use </em><em>trust authentication for local TCP/IP connections but require a password for remote TCP/IP connections. In this case a record specifying </em><em>trust authentication for connections from 127.0.0.1 would appear before a record specifying password authentication for a wider range of allowed client IP addresses.</em></p><p>2. <strong>Use </strong><strong>scram-sha-256 instead of </strong><strong>md5</strong></p><p>scram-sha-256 is more secure and resists common attacks better than md5.</p><p>3. <strong>Avoid allowing all IPs</strong></p><p>Do not use:</p><pre>host    all     all     0.0.0.0/0       scram-sha-256</pre><p>This opens your database to the entire internet.</p><p>Instead:</p><p>Use specific IPs or private ranges (e.g. 192.168.1.0/24) or only allow 127.0.0.1/32 if no remote access is needed</p><p>4. <strong>Disable trust and ident methods</strong></p><p>Avoid:</p><pre>host    all     all     127.0.0.1/32    trust<br>host    all     all     127.0.0.1/32    ident</pre><p>These bypass password checks or rely on system usernames, which is unsafe for production.</p><p>5. <strong>Combine with firewall rules</strong></p><p>Use OS-level firewalls (like iptables or AWS Security Groups) to limit access to PostgreSQL port 5432.</p><p>Example of a Secure Setup:</p><pre># Local access for superuser only<br>local   all             postgres                                peer<br><br># App user access from trusted internal IP<br>host    appdb           appuser        10.0.1.100/32            scram-sha-256<br><br># No access from outside<br># (omit 0.0.0.0/0 and public IPs)</pre><h3>Step 14: Restart or Reload PostgreSQL to apply HBA/Config changes</h3><pre>sudo systemctl reload postgresql.service </pre><p>Why?</p><p>Sends a <strong>SIGHUP</strong> to the PostgreSQL process. Causes PostgreSQL to <strong>reload configuration files</strong> without stopping the server. Existing client connections stay open; in-progress transactions continue. After changing settings that can be applied with a reload (e.g., pg_hba.conf, listen_addresses, log_* parameters) or when you want to apply authentication rule changes without interrupting users.</p><p><strong>NOTE:</strong></p><p>Not all config changes take effect (some require restart). After changing parameters in postgresql.conf that require a restart (e.g., port, max_connections, shared_buffers) or when the server is hung or in a bad state and needs a full reset.</p><pre>sudo systemctl restart postgresql.service</pre><p>It stops the PostgreSQL service completely, then starts it again. What it does is: It will close all the connections and abort the all transactions. PostgreSQL re-reads <em>all</em> configuration files, reinitializes shared memory, and reloads all background workers.</p><h3><strong>Step 15: Connect to Your Database</strong></h3><pre>psql -h localhost -U myuser -d mydatabase</pre><p>You will be prompted for the password for myuser. If authentication and privileges are correctly set up, you’ll be dropped into the psql prompt connected to mydatabase as myuser.</p><p><strong>Why?</strong><br> This confirms that the user can connect and interact with the PostgreSQL database as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*bQX5I2JiSNI9FovjeozMCA.png" /></figure><p>Setting up PostgreSQL 17 on Amazon Linux 2023 may seem like a complex task at first, but with the right steps and understanding, it becomes a straightforward and rewarding process. Whether you’re configuring it for development or production, following security best practices and understanding why each configuration matters will help you build a robust and scalable database environment.</p><p>By completing this guide, you now have a fully operational PostgreSQL server, ready to handle your applications’ data needs. Keep exploring PostgreSQL’s features, such as roles, schemas, replication, and performance tuning, to get the most out of your setup.</p><p>If you found this guide helpful, feel free to share it with others or leave a comment. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da9426261620" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step Guide to Configuring MongoDB on Amazon Linux 2023.]]></title>
            <link>https://blog.devgenius.io/step-by-step-guide-to-configuring-mongodb-on-amazon-linux-2023-519ba30cee72?source=rss-7e25ecd9e014------2</link>
            <guid isPermaLink="false">https://medium.com/p/519ba30cee72</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[amazon-linux]]></category>
            <category><![CDATA[mongodb-server]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Surangi Kanchana]]></dc:creator>
            <pubDate>Fri, 17 Jan 2025 14:19:49 GMT</pubDate>
            <atom:updated>2025-01-21T16:30:38.328Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HEK01zjLTL99GuXy4bg-yg.jpeg" /></figure><p>In this guide, we’ll walk through the steps to install, configure, and secure MongoDB on an Amazon Linux 2023 server. By the end of this tutorial, you’ll have a fully operational MongoDB instance ready to handle your application data securely, always cross-reference with the <a href="https://www.mongodb.com/docs/">official MongoDB documentation</a> to ensure you’re following the latest standards.</p><p>For this tutorial, I’m using Termius, a free SSH and SFTP client for macOS. Alternatively, you can use tools like PuTTY (Windows) or the native terminal (Linux/macOS) to connect to your server.</p><p>Once you have connected to the server, follow the below steps to install the required software and configure it:</p><p>MongoDB offers various versions of its database server, and the choice of which version to install on your Amazon Linux 2023 server should be based on your specific project requirements.</p><p>To install MongoDB on an Amazon Linux system, you should add the official MongoDB repository as part of the installation process.</p><p>Add the MongoDB Repository:</p><p>Adding the MongoDB repository ensures that your system fetches the MongoDB packages directly from the official source, ensuring the latest features and security updates.</p><pre>sudo tee /etc/yum.repos.d/mongodb-org-7.0.repo&lt;&lt;EOL<br>[mongodb-org-7.0]<br>name=MongoDB Repository<br>baseurl=https://repo.mongodb.org/yum/amazon/2023/mongodb-org/7.0/x86_64/<br>gpgcheck=1<br>enabled=1<br>gpgkey=https://www.mongodb.org/static/pgp/server-7.0.asc<br>EOL</pre><p>Once you’ve added the MongoDB repository to your Amazon Linux 2023 server, you can easily install MongoDB server and related packages such as MongoDB-org server, MongoDB-database-tools, Mongosh, and more using package manager.</p><pre>sudo dnf install mongodb-org</pre><p>By default, the MongoDB Database service (mongod) does not start automatically after installation on many Linux distributions, including Amazon Linux. You need to manually start the service and enable it to ensure that it starts automatically on system boot.</p><pre>sudo systemctl enable --now mongod</pre><p>Use mongosh to get the command interface of the Database</p><pre>mongosh</pre><p>If you encounter an OpenSSL configuration error while starting mongosh, it indicates a mismatch in the OpenSSL version used by MongoDB.</p><pre>(mongosh: OpenSSL configuration error:<br>001908B0DC7F0000:error:030000A9:digital envelope routines:alg_module_init:unknown option:../deps/openssl/openssl/crypto/evp/evp_cnf.c:61:name=rh-allow-sha1-signatures, value=yes)</pre><p>To resolve this issue, install the updated OpenSSL package with the following command:</p><pre>dnf install mongodb-mongosh-shared-openssl3</pre><p>After that, use the admin account and set a password. Use a secure password and store credentials safely.</p><pre>use admin</pre><pre>db.createUser({ user: &quot;admin&quot;, pwd: &quot;password&quot;, roles: [&quot;root&quot;] })</pre><p>Edit the MongoDB configuration file to require authentication.</p><p>Enabling authentication ensures that only authorized users can access and modify the database. This is a critical step to secure your MongoDB instance from unauthorized access.</p><pre>sudo nano /etc/mongod.conf</pre><p>Locate the security section and insert the following lines:</p><pre>security:<br>  authorization: enabled</pre><p>Once you’ve enabled security or authentication for MongoDB, you should restart the MongoDB service to apply the changes you’ve made.</p><pre>sudo systemctl restart mongod</pre><p>To connect to MongoDB with authentication, you can use the mongo command-line client. Here&#39;s the command you can use, replacing &lt;password&gt; with the actual admin password you&#39;ve set earlier:</p><pre>mongo -u admin -p password --authenticationDatabase admin</pre><p>You’ve accomplished the task of configuring MongoDB on your server. Periodically update your MongoDB instance for security patches.</p><p>To expand your knowledge, consider reading my other articles, which will guide you through the configuration processes for Nginx and Tomcat. Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=519ba30cee72" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/step-by-step-guide-to-configuring-mongodb-on-amazon-linux-2023-519ba30cee72">Step-by-Step Guide to Configuring MongoDB on Amazon Linux 2023.</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step Guide to Configuring Nginx on Amazon Linux 2023 Server]]></title>
            <link>https://medium.com/@rangika123.kanchana/step-by-step-guide-to-configuring-nginx-on-amazon-linux-2023-server-24785f167359?source=rss-7e25ecd9e014------2</link>
            <guid isPermaLink="false">https://medium.com/p/24785f167359</guid>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[nginx]]></category>
            <dc:creator><![CDATA[Surangi Kanchana]]></dc:creator>
            <pubDate>Mon, 30 Dec 2024 14:26:02 GMT</pubDate>
            <atom:updated>2024-12-30T14:26:02.775Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uI42ge9AFKH9PNZhSg3DHA.jpeg" /></figure><p>Configuring Amazon Linux 2023 with Nginx requires a series of steps. This article provides a high-level overview of configuring Nginx on Amazon Linux 2023. Note that specific details may change over time, so always refer to the official documentation. To ensure you have the latest instructions, always refer to the official documentation.</p><p>For this tutorial, I’m using Termius, a free SSH and SFTP client for macOS. Alternatively, you can use tools like PuTTY (Windows) or the native terminal (Linux/macOS) to connect to your server.</p><p>Once you have connected to the server, follow the below steps to install the required software and configure it:</p><p><strong>Install nginx.</strong></p><p>Install Nginx using the following command:</p><pre>sudo dnf install nginx -y</pre><p><strong>After successful installation, start the nginx</strong></p><pre>sudo systemctl start nginx</pre><p><strong>Then enable the nginx</strong></p><pre>sudo systemctl enable nginx</pre><p><strong>Edit </strong><strong>nginx.conf file</strong></p><pre>nano /etc/nginx/nginx.conf</pre><p>The nginx.conf file is the main configuration file for the Nginx web server. It contains global settings, server blocks (also known as virtual hosts), and various directives that define how Nginx should behave. Below, I’ll provide an overview of the structure of the default nginx.conf file.</p><pre>server {<br>  listen 80;<br>  listen [::]:80;<br>  server_name youservername.com;<br>  root /usr/share/nginx/html;<br><br>  # Load configuration files for the default server block.<br>  include /etc/nginx/default.d/*.conf;<br><br>  error_page 404 /404.html;<br>  location /404.html { <br>  }<br><br>  error_page 500 502 503 504 /50x.html;<br>  location /50x.html {<br>  }<br>  <br>}</pre><p>The provided code is an Nginx server block configuration for handling HTTP requests on port 80 for the domain “youservername.com.” Let’s break down the configuration:</p><p>listen 80; and listen [::]:80; specify that this server block will listen on port 80 for both IPv4 and IPv6 connections.</p><p>server_name youservername.com; sets the server name, indicating that this configuration will be used when requests come in for &quot;youservername.com.&quot;</p><p>root : this directive defines the root directory for serving files. When a request is made to this server block, Nginx will look for files to serve from the “/usr/share/nginx/html” directory.</p><p>include : This line includes additional configuration files located in the “/etc/nginx/default.d/” directory that are meant to supplement this server block’s configuration. These files can contain additional settings, location blocks, or other configurations.</p><p>This configuration is intended to fulfill multiple purposes, including serving a web application, forwarding API requests to a backend server and managing URI rewriting. Additionally, it includes provisions for handling common HTTP error codes by displaying custom error pages. It’s important to ensure that these settings align with the specific needs and characteristics of your application and adhere to your unique requirements.</p><p>You’ve accomplished the task of configuring Nginx on your server. To deepen your understanding, check out my other articles on configuring Tomcat and MongoDB. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24785f167359" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step Guide to Configuring Tomcat on Amazon Linux 2023.]]></title>
            <link>https://medium.com/@rangika123.kanchana/step-by-step-guide-to-configuring-tomcat-on-amazon-linux-2023-4222aca9886a?source=rss-7e25ecd9e014------2</link>
            <guid isPermaLink="false">https://medium.com/p/4222aca9886a</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[tomcat-server]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[tomcat]]></category>
            <dc:creator><![CDATA[Surangi Kanchana]]></dc:creator>
            <pubDate>Tue, 17 Dec 2024 14:26:38 GMT</pubDate>
            <atom:updated>2024-12-17T14:26:38.126Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g34VR2SUDRgVjCImg3AD-A.jpeg" /></figure><p>Configuring Amazon Linux 2023 with Nginx requires a series of steps. This guide provides a high-level overview, but please be aware that specific details could change over time. To ensure you have the latest instructions, always refer to the official documentation.</p><p>This guide will walk you through the essential steps to configure Nginx on Amazon Linux 2023, with practical tips to ensure a smooth setup.</p><p>Here, I am using Termius for server configurations. It is a free cross-platform SSH and SFTP client. You can choose any SSH client for server configurations.</p><p>Once you have connected to the server, follow the below steps to install the required software and configure it:</p><h3><strong>Tomcat setup</strong></h3><p>Tomcat, an open-source application server by Apache, executes Java Servlets and JSP for hosting Java-based web apps.</p><p>To ensure a successful installation of Tomcat on a Linux system, it’s important to have Java installed. If Java is not already present on your system, you can install OpenJDK, which is the default package for Java development.</p><p>Here I installed OpenJDK 17</p><pre>sudo dnf install java-17-amazon-corretto-devel.x86_64 </pre><p>Running Tomcat under the root account is not recommended. Therefore, it’s advisable to create a new user specifically for running the Tomcat server on your system. You can create this new user using the following command:</p><pre>sudo useradd -r -m -U -d /opt/tomcat -s /bin/false tomcat</pre><p>Having created a new user for our Tomcat server and switched to that user, the next step is to obtain the Tomcat package for installation on Linux. To do this, we can utilize thewget command to fetch the Tomcat package directly from the official Tomcat website.</p><pre>wget -c https://downloads.apache.org/tomcat/tomcat-9/v9.0.80/bin/apache-tomcat-9.0.80.tar.gz</pre><p>After successfully downloading the tar archive to our system, the next step is to extract its contents. To achieve this, we can employ the tar command as demonstrated below.</p><pre>sudo tar xf apache-tomcat-9.0.80.tar.gz -C /opt/tomcat</pre><p>With the provided command, we’ve successfully extracted the contents of the tar package into the /opt/Tomcat directory. To simplify the process of updating Tomcat in the future, we can create a symbolic link that points to the Tomcat installation directory.</p><pre>sudo ln -s /opt/tomcat/apache-tomcat-9.0.80 /opt/tomcat/updated</pre><p>To provide the user running Tomcat with access to the Tomcat installation directory, you can use the chown command to change the ownership of the directory and its contents. Here&#39;s how you can do it:</p><pre>sudo chown -R tomcat:tomcat /opt/tomcat/*</pre><p>To provide executable (execute) permissions to all scripts within the bin directory of your Tomcat installation, you can use the chmod command with the +x option.</p><pre>sh -c &#39;chmod +x /opt/tomcat/updated/bin/*.sh&#39;</pre><p>After installing Tomcat on Linux, the next step is to configure it for use. To run Tomcat as a service, you’ll need to create a systemd unit file. To do this, you can open a new file called “tomcat.service” in the “/etc/systemd/system” directory.</p><pre>nano /etc/systemd/system/tomcat.service</pre><pre>[Unit]<br>Description=Apache Tomcat Web Application Container<br>After=network.target<br><br>[Service]<br>Type=forking<br><br>Environment=&quot;JAVA_HOME=/usr/lib/jvm/java-17-amazon-corretto.x86_64&quot;<br>Environment=&quot;CATALINA_PID=/opt/tomcat/updated/temp/tomcat.pid&quot;<br>Environment=&quot;CATALINA_HOME=/opt/tomcat/updated/&quot;<br>Environment=&quot;CATALINA_BASE=/opt/tomcat/updated/&quot;<br>Environment=&quot;CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.util.concurrent=ALL-UNNAMED --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED&quot;<br>Environment=&quot;JAVA_OPTS=-Djava.awt.headless=true -Djava.security.egd=file:/dev/./urandom&quot;<br><br>ExecStart=/opt/tomcat/updated/bin/startup.sh<br>ExecStop=/opt/tomcat/updated/bin/shutdown.sh<br><br>User=tomcat<br>Group=tomcat<br>UMask=0007<br>RestartSec=10<br>Restart=always<br><br>[Install]<br>WantedBy=multi-user.target</pre><p>Environment: Sets environment variables required for Tomcat, including JAVA_HOME, CATALINA_PID, CATALINA_HOME, CATALINA_BASE, CATALINA_OPTS, and JAVA_OPTS.</p><p>ExecStart: Specifies the command to start Tomcat using the /opt/tomcat/updated/bin/startup.sh script.</p><p>ExecStop: Specifies the command to stop Tomcat using the /opt/tomcat/updated/bin/shutdown.sh script.</p><p>Start the tomcat</p><pre>systemctl start tomcat</pre><p>To enable the Tomcat service to run on startup, you can use the systemctl enable command.</p><pre>systemctl enable tomcat</pre><p>To check the service status, you can use systemctl status command</p><pre>systemctl status tomcat</pre><p>To confirm successful installation, access the Tomcat default page at http://&lt;your-server-ip&gt;:8080</p><p>Configuring Tomcat is a key step in setting up your application stack. Stay tuned for upcoming articles on Nginx and MongoDB configurations to complete your setup!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4222aca9886a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Seamless Square Payment Gateway Integration with Spring Boot: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@rangika123.kanchana/seamless-square-payment-gateway-integration-with-spring-boot-a-step-by-step-guide-6b0d93f68306?source=rss-7e25ecd9e014------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b0d93f68306</guid>
            <category><![CDATA[payment-gateway]]></category>
            <category><![CDATA[square]]></category>
            <category><![CDATA[square-payment]]></category>
            <dc:creator><![CDATA[Surangi Kanchana]]></dc:creator>
            <pubDate>Mon, 09 Dec 2024 10:16:13 GMT</pubDate>
            <atom:updated>2024-12-09T10:16:13.828Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iDHYu4OUGsJ_7CailwHyrg.jpeg" /></figure><p><strong>Square Overview</strong></p><p>Square is a comprehensive financial services platform developed by Block, Inc. It enables businesses to accept various forms of payments, both in-person and online, through a suite of hardware and software solutions. Designed to cater to businesses of all sizes, Square offers tools for payment processing, point-of-sale (POS) systems, e-commerce, and financial management.</p><p>To integrate Square’s payment gateway into a Spring Boot application, you need to follow a series of steps, including creating a Square developer account, configuring your Spring Boot project, and setting up both backend and frontend components to process payments securely. Here’s a detailed guide to help you through the Spring Boot integration process:</p><p><strong>high-level process of handling payments with Square Payment Gateway.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ilGC9TMPW4b2USY0nfJ-A.png" /></figure><p>This flowchart illustrates the high-level process of handling payments with Square Payment Gateway. It showcases the interaction between the <strong>Frontend</strong>, <strong>Backend</strong>, and <strong>Square</strong> services. Here’s an explanation of each component:</p><p>Frontend:</p><p><strong>Pass the payment token and idempotency key from the client side</strong>:</p><ul><li>The frontend (e.g., a web or mobile application) collects payment details (like card information) using Square’s client-side SDKs.For more details visit <a href="https://developer.squareup.com/docs/in-app-payments-sdk/what-it-does">In-App Payment SDK</a> and <a href="https://developer.squareup.com/docs/web-payments/overview">Web Payment SDK</a>.</li><li>It generates a <strong>payment token</strong> (a secure representation of the payment details) and an <strong>idempotency key</strong> (a unique identifier to prevent duplicate processing of the same payment).</li><li>These values are then sent to the backend securely for further processing.</li></ul><p>Backend:</p><p><strong>Create payment request object</strong>:</p><ul><li>The backend receives the payment token and idempotency key from the frontend.</li><li>It uses these values to construct a <strong>CreatePaymentRequest</strong> object with additional details, such as the payment amount, currency, customer ID, and location ID.</li><li>This request encapsulates all necessary information to initiate a payment with Square.</li></ul><p><strong>Send the request to Square</strong>:</p><ul><li>The backend interacts with Square’s API by sending the constructed payment request using methods like createPaymentAsync.</li><li>This step transfers control to the Square Payment Gateway for processing.</li></ul><p>Square:</p><p><strong>Create payment</strong>:</p><ul><li>Square processes the payment request.</li><li>It validates the token, checks for sufficient funds, verifies customer details, and executes the payment.</li></ul><p>For more details visit the In-App payment sdk <a href="https://developer.squareup.com/docs/in-app-payments-sdk/how-it-works">How It Works</a> documentation.</p><ol><li><strong>Create Square Developer Account</strong></li></ol><p>To begin developing with Square’s APIs, follow these steps to create a Square developer account and register your first application:</p><ul><li>Visit the <a href="https://app.squareup.com/signup/us?lang_code=en-us&amp;return_to=https%3A%2F%2Fdeveloper.squareup.com%2Fapps&amp;v=developers">Square Developer sign-up page</a>.</li><li>Provide your personal information, including your name, email address, and country.</li><li>Agree to Square’s Terms of Service, Privacy Policy, and E-Sign Consent.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vdVEwmJ_sof9EgGQ7i-bdQ.png" /></figure><ul><li>After signing in, access the <a href="https://developer.squareup.com/console/en/apps">Developer Dashboard</a>.</li><li>Click on <strong>“+ New Application”</strong> to create a new app.</li><li>Enter a name for your application. This name is for your reference and doesn’t need to match your app’s branding.</li><li>Optionally, provide additional details such as your use case, preferred coding language, and target audience. This information helps Square tailor resources to your needs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1FLt8kedwUPMDTHBWpZQ-Q.png" /></figure><ul><li>Once your application is created, navigate to the <strong>Credentials</strong> section within your app’s settings.</li><li>Here, you’ll find your <strong>Application ID</strong> and <strong>Access Token</strong> for both Sandbox (testing) and Production environments.</li><li>These credentials authenticate your API requests and should be kept secure.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tG_WkmeFAxDAZt_zyEMC3w.png" /></figure><ul><li>To process real transactions, activate your Square account by visiting <a href="https://app.squareup.com/signup/business-information/world?country_code=lk&amp;v=verify-your-identity">squareup.com/activation</a>.</li><li>Complete the required information, which may include business details and verification documents, depending on your region’s regulations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bT7VxBw0Ut5B2jXQKmJklQ.png" /></figure><p>By completing these steps, you’ll have a Square developer account and a registered application, enabling you to explore and integrate Square’s APIs into your projects. For more detailed information, refer to Square’s official documentation on <a href="https://developer.squareup.com/docs/get-started/create-account-and-application">creating an account and application</a>.</p><p>2.<strong> Configure Your Spring Boot Project:</strong></p><p><strong>Add Dependencies:</strong></p><p>Latest SDK Version: 42.0.0.20241120</p><p><a href="https://developer.squareup.com/docs/changelog/connect">Release Notes </a>- Learn more about the latest SDK feature releases.</p><p>Include the Square SDK in your pom.xml file or build.gradle file:</p><p>pom.xml:</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;com.squareup&lt;/groupId&gt;<br>  &lt;artifactId&gt;square&lt;/artifactId&gt;<br>  &lt;version&gt;42.0.0.20241120&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>build.gradle:</p><pre>implementation &#39;com.squareup:square:42.0.0.20241120&#39;</pre><p>Each SDK version is tied to a specific Square API version. Square regularly releases new API and SDK versions to introduce new features. To utilize these features, you need to update the SDK version in your application. A major version update in the SDK signifies a breaking change, so it’s essential to test your application thoroughly before deploying it to production. Keeping your SDK updated ensures that your application remains compatible, avoids deprecated or retired features, and minimizes the risk of production issues.</p><p>If using an older version of Spring Boot, you may face compatibility issues. Upgrade to the latest version to use the latest Square SDK.</p><p>But in my case I had to use an older version because I was using Spring Boot 2.2.4, and I got the below error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s8MYkc-6yzAPgtK8Id4LuA.png" /></figure><p>The project used Jackson Databind version 2.10, while the Square SDK required version 2.14. A compatible version of Jackson Databind that satisfied both dependencies could not be found. To address the incompatibility, an older version of the Square SDK (20.1.0.20220616) was used. However, this led to another issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mvrZxYC6wNnWgAWhQN7Mcg.png" /></figure><p>Why Does This Error Occur?</p><p>Version Mismatch:</p><p>The error is caused by a version conflict with the OkHttp library in the project. The project had a specific OkHttp version dependency, while the Square SDK required a different version. To resolve the OkHttp conflict, version 4.9.1 of OkHttp was manually included in the project:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.squareup.okhttp3&lt;/groupId&gt;<br>    &lt;artifactId&gt;okhttp&lt;/artifactId&gt;<br>    &lt;version&gt;4.9.1&lt;/version&gt;<br>&lt;/dependency&gt;</pre><pre>implementation &#39;com.squareup.okhttp3:okhttp:4.9.1&#39;</pre><p>Upgrading the project’s Java version to 2.7.18 resolved the errors. This ensured compatibility with the required libraries and eliminated the dependency conflicts.</p><p>By aligning the dependencies and upgrading Java, the issues were resolved, allowing the project to function without further errors.</p><p><strong>Implement Backend Services:</strong></p><pre>package com.soff.soffcricketweb.model.model;<br><br>import com.fasterxml.jackson.annotation.JsonIgnoreProperties;<br>import com.squareup.square.models.Error;<br>import lombok.AllArgsConstructor;<br>import lombok.Data;<br>import lombok.NoArgsConstructor;<br><br>import java.util.List;<br><br>@Data<br>@JsonIgnoreProperties(ignoreUnknown = true)<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class PaymentResult {<br>    private String title;<br>    private List&lt;Error&gt; errors;<br><br>}</pre><pre>package com.soff.soffcricketweb.service.impl;<br><br>import com.soff.soffcricketweb.model.model.PaymentModel;<br>import com.soff.soffcricketweb.model.model.PaymentResult;<br>import com.soff.soffcricketweb.service.SquarePaymentGatewayService;<br>import com.squareup.square.Environment;<br>import com.squareup.square.SquareClient;<br>import com.squareup.square.api.PaymentsApi;<br>import com.squareup.square.exceptions.ApiException;<br>import com.squareup.square.models.CreatePaymentRequest;<br>import com.squareup.square.models.Error;<br>import com.squareup.square.models.Money;<br>import com.squareup.square.models.RetrieveLocationResponse;<br>import org.apache.logging.log4j.LogManager;<br>import org.apache.logging.log4j.Logger;<br>import org.springframework.stereotype.Service;<br><br>import java.util.Collections;<br>import java.util.UUID;<br>import java.util.concurrent.CompletableFuture;<br>import java.util.concurrent.ExecutionException;<br><br><br>@Service<br>public class SquarePaymentGatewayServiceImpl implements SquarePaymentGatewayService {<br>    private static final String SQUARE_ACCESS_TOKEN = &quot;your_access_token&quot;;<br>    private static final String SQUARE_LOCATION_ID = &quot;your_location_id&quot;;<br><br>    private static final Logger LOGGER = LogManager.getLogger(SponsorController.class);<br><br>    @Override<br>    public PaymentResult createPayments(PaymentModel paymentModel) throws ExecutionException, InterruptedException {<br><br>        SquareClient squareClient = new SquareClient.Builder()<br>                .accessToken(SQUARE_ACCESS_TOKEN)<br>                .environment(Environment.SANDBOX)<br>                .build();<br><br>        RetrieveLocationResponse locationResponse = getLocationInformation(squareClient).get();<br>        String currency = locationResponse.getLocation().getCurrency();<br><br>        if (paymentModel == null) {<br>            LOGGER.error(&quot;PAYMENT MODEL CANNOT BE EMPTY&quot;);<br>            return new PaymentResult(&quot;FAILURE&quot;, Collections.singletonList(new Error.Builder(&quot;PAYMENT MODEL CANNOT BE EMPTY&quot;, &quot;PAYMENT MODEL CANNOT BE EMPTY&quot;)<br>                    .build()));<br>        } else if (paymentModel.getCustomerId() == null) {<br>            LOGGER.error(&quot;CUSTOMER ID CANNOT BE NULL&quot;);<br>            return new PaymentResult(&quot;FAILURE&quot;, Collections.singletonList(new Error.Builder(&quot;CUSTOMER ID CANNOT BE NULL&quot;, &quot;CUSTOMER ID CANNOT BE NULL&quot;)<br>                    .build()));<br>        } else {<br><br>            Money amountMoney = new Money.Builder()<br>                    .amount(paymentModel.getAmountMoney())<br>                    .currency(currency)<br>                    .build();<br><br>            CreatePaymentRequest createPaymentRequest = new CreatePaymentRequest.Builder(paymentModel.getPaymentToken(), paymentModel.getIdempotencyKey())<br>                    .amountMoney(amountMoney)<br>                    .autocomplete(true)<br>                    .customerId(paymentModel.getCustomerId())<br>                    .locationId(SQUARE_LOCATION_ID)<br>                    .referenceId(paymentModel.getReference())<br>                    .idempotencyKey(UUID.randomUUID().toString())<br>                    .build();<br><br>            PaymentsApi paymentsApi = squareClient.getPaymentsApi();<br><br>            PaymentResult join = paymentsApi.createPaymentAsync(createPaymentRequest).thenApply(result -&gt; {<br><br>                LOGGER.error(&quot;SUCCESS&quot;);<br>                return new PaymentResult(&quot;SUCCESS&quot;, null);<br>            }).exceptionally(exception -&gt; {<br><br>                Throwable cause = exception.getCause();<br>                if (cause instanceof ApiException) {<br>                    ApiException apiException = (ApiException) cause;<br>                    LOGGER.error(&quot;API Exception occurred&quot;);<br>                    for (Error err : apiException.getErrors()) {<br>                        LOGGER.error(err.getCategory());<br>                        LOGGER.error(err.getCode());<br>                        LOGGER.error(err.getDetail());<br>                    }<br>                    return new PaymentResult(&quot;FAILURE&quot;, apiException.getErrors());<br>                } else {<br><br>                    cause.printStackTrace();<br>                    return new PaymentResult(&quot;FAILURE&quot;, Collections.singletonList(new Error.Builder(&quot;API_ERROR&quot;, &quot;LOCATION_NOT_FOUND&quot;)<br>                            .category(&quot;UNKNOWN_ERROR&quot;)<br>                            .code(&quot;UNKNOWN_EXCEPTION&quot;)<br>                            .detail(cause.getMessage())<br>                            .build()));<br>                }<br>            }).join();<br>            return join;<br>        }<br><br>    }<br><br>    private CompletableFuture&lt;RetrieveLocationResponse&gt; getLocationInformation(<br>            SquareClient squareClient) {<br>        return squareClient.getLocationsApi().retrieveLocationAsync(SQUARE_LOCATION_ID)<br>                .thenApply(result -&gt; result)<br>                .exceptionally(exception -&gt; {<br>                    LOGGER.error(&quot;Failed to make the request&quot;);<br>                    LOGGER.error(&quot;Exception: %s%n&quot;, exception.getMessage());<br>                    return null;<br>                });<br>    }<br><br>}<br><br></pre><p>Note: If you are using an older square version (e.g: 20.1.0.20220616) you have to pass amountMoney to CreatePaymentRequest.Builder().</p><pre>CreatePaymentRequest createPaymentRequest = new CreatePaymentRequest.Builder(paymentModel.getPaymentToken(), paymentModel.getIdempotencyKey(),amountMoney)<br>                    .amountMoney(amountMoney)<br>                    .autocomplete(true)<br>                    .customerId(paymentModel.getCustomerId())<br>                    .locationId(SQUARE_LOCATION_ID)<br>                    .referenceId(paymentModel.getReference())<br>                    .idempotencyKey(UUID.randomUUID().toString())<br>                    .build();</pre><p>Note : This Java code includes the Square Sandbox access token directly within the file. To enhance security and maintainability, avoid hardcoding credentials by storing them in a separate configuration file.</p><p><strong>Steps:</strong></p><ol><li><strong>Initialize Square Client</strong></li></ol><p>The SquareClient acts as the main interface to interact with Square&#39;s APIs, enabling you to call endpoints like createPaymentAsync and retrieveLocationAsync.</p><pre>SquareClient squareClient = new SquareClient.Builder()<br>                .accessToken(SQUARE_ACCESS_TOKEN)<br>                .environment(Environment.SANDBOX)<br>                .build();</pre><p>2. <strong>Retrieve Location Information</strong></p><p>Currency is essential for creating a payment request, ensuring the transaction amount is in the correct format.</p><p>The getLocationInformation method is called to retrieve details about the specified Square location. It fetches metadata such as the currency used at the location.</p><p>This is an asynchronous operation using CompletableFuture.</p><p>Calls retrieveLocationAsync on LocationsApi using the SquareClient</p><p>If successful:</p><p>Returns RetrieveLocationResponse⁣containing location details.</p><p>If failed:</p><p>Logs the error and returns null</p><p>3. <strong>Validate the Payment Model</strong></p><p>Validation prevents unnecessary API calls and ensures only properly structured data reaches Square.</p><p>The input PaymentModel passed is validated:</p><ul><li>Ensures the model itself is not null.</li><li>Verifies that mandatory fields, such as customerId, are present.</li></ul><p>4. <strong>Construct Money Object</strong></p><p>Square’s API requires a Money object to define the amount and currency in a standardized way.</p><p>Payments and refunds are individual monetary transactions. Square represents these transactions using a Money object, which includes a specific currency in ISO 4217 format and a positive or negative value to indicate the transaction amount.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0KglB2aoGXz2dm6ayUrwkw.png" /></figure><p>The minimum payment amount allowed in CreatePayment or UpdatePayment requests depends on the payment source. For detailed information, refer to the <a href="https://developer.squareup.com/docs/payments-api/take-payments#monetary-amount-limits">Monetary Amount Limits documentation</a>.</p><p>When using the Money object, an EXPECTED_INTEGER error may occur if the specified amount is invalid. This error indicates that Square expected the amount as an integer but received a different format (e.g., a string or float). To resolve this issue:</p><ul><li>Ensure the amount is specified in the smallest denomination of the currency used (e.g., cents for USD).</li><li>Verify that the amount is a positive integer.</li><li>Confirm that the amount meets or exceeds the valid minimum for the specified currency. Minimum amounts are determined by the Location.country associated with the account. For more details, refer to <a href="https://developer.squareup.com/docs/payment-minimums">Payment Minimums</a>.</li></ul><p>5. <strong>Create Payment Request</strong></p><p>This request encapsulates all required payment information in a single object that is sent to Square.</p><p>paymentModel.getPaymentToken():</p><ul><li>Represents a secure payment token generated by Square’s client-side SDK (e.g., Web Payments SDK).</li><li>Contains customer payment details (e.g., card information).</li></ul><p>paymentModel.getIdempotencyKey():</p><ul><li>A unique string to ensure the request is not processed more than once. Prevents duplicate payments.</li><li>It can be generated dynamically (e.g., using UUID.randomUUID().toString()).</li></ul><p>autocomplete(true)</p><ul><li>If set to true, the payment will automatically be completed upon creation if there are no issues.</li><li>If set to false, the payment remains in an authorized state and requires manual completion later (useful for delayed capture scenarios).</li></ul><p>locationId(SQUARE_LOCATION_ID)</p><ul><li>paymentModel.getReference() is a custom identifier for the transaction (e.g., an order ID).</li><li>Useful for reconciling Square payments with your internal system.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TvLSDgSuGaXT__GH1BNt-g.png" /></figure><p>After setting all required and optional parameters, the build() method creates an immutable CreatePaymentRequest.</p><p>The CreatePaymentRequest in Square&#39;s API is highly flexible, allowing you to customize it by passing various parameters based on your application&#39;s needs. <a href="https://developer.squareup.com/reference/square/payments-api/create-payment">Read more</a>.</p><p>6. <strong>Call Payments API</strong></p><p>Processes payments asynchronously to avoid blocking the application thread and to handle potential errors gracefully.</p><ul><li>The SquareClient initialized earlier provides access to the PaymentsApi.</li><li>The PaymentsApi is used to handle operations related to payments, such as creating, retrieving, or canceling payments.</li><li>The createPaymentAsync method sends a CreatePaymentRequest to Square&#39;s servers.</li><li>This is an <strong>asynchronous operation</strong>, meaning the application does not block while waiting for a response.</li><li>Returns a CompletableFuture that completes when the response is available.</li></ul><p>Why Asynchronous?</p><p>Non-blocking calls improve application scalability by freeing up resources for other tasks while waiting for a response.</p><ul><li>If the payment is processed successfully, the thenApply callback is executed.</li><li><strong>result</strong> contains the response from Square, such as transaction details or confirmation of success.</li><li>A new PaymentResult object is created with the status &quot;SUCCESS&quot;.</li><li>Logs a success message for debugging and tracking.</li><li>If an error occurs during the API call, the exceptionally block handles it.</li></ul><p>Error Scenarios:</p><p>ApiException:</p><ul><li>Raised when Square’s server returns an error (e.g., invalid request, insufficient funds).</li></ul><p>Logs details of the error, including:</p><ul><li>Category (e.g., AUTHENTICATION_ERROR, PAYMENT_METHOD_ERROR).</li><li>Code (specific error code, like BAD_REQUEST).</li><li>Detail (human-readable explanation).</li></ul><p>Returns a PaymentResult with the status &quot;FAILURE&quot; and a list of errors.</p><p>Other Exceptions:</p><ul><li>Captures any non-API-related issues (e.g., network errors).</li><li>Logs the stack trace and returns a PaymentResult with a generic error.</li></ul><p>As you implement your integration, remember to:</p><ul><li>Keep your dependencies updated to ensure compatibility with the latest features.</li><li>Follow best practices for security, such as storing sensitive information in secure configurations.</li><li>Test your application thoroughly in the Sandbox environment before moving to production.</li></ul><p>With Square’s versatile platform and Spring Boot’s efficiency, you can focus on scaling your business and enhancing customer satisfaction without worrying about payment processing complexities. Explore further possibilities by diving into Square’s comprehensive developer documentation and keep pushing the boundaries of what your application can achieve.</p><p>Happy coding, and may your integration journey be seamless and rewarding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b0d93f68306" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Web sockets Authentication with Spring Security and Keycloak]]></title>
            <link>https://medium.com/@rangika123.kanchana/spring-web-sockets-authentication-with-spring-security-and-keycloak-8fc589746a4d?source=rss-7e25ecd9e014------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fc589746a4d</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[websocket-api]]></category>
            <dc:creator><![CDATA[Surangi Kanchana]]></dc:creator>
            <pubDate>Wed, 20 Nov 2024 16:39:41 GMT</pubDate>
            <atom:updated>2024-12-10T18:09:32.934Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring WebSocket Authentication with Spring Security and Keycloak</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SCK9dPJrz-vs9d055XHphw.jpeg" /></figure><p><strong>WebSocket overview</strong></p><p>The Spring Framework offers comprehensive WebSocket communication capabilities, enabling a persistent, two-way, full-duplex connection between clients and servers. This connection remains active until explicitly terminated by either the client or the server. With Spring’s WebSocket support, you can build applications that demand instantaneous data exchange, such as chat systems, real-time notifications, or live data feeds, fostering real-time interactions.</p><p>By integrating Spring Security with Keycloak, an open-source identity and access management solution, you can enhance the authentication and authorization mechanisms for your WebSocket application. This integration ensures secure communication by leveraging Keycloak for user authentication and access control.</p><p>In this guide, you’ll learn how to implement Spring WebSocket authentication with Spring Security and Keycloak.</p><ol><li><strong>Configure WebSocket Security</strong></li></ol><p>Start by customizing WebSocket security rules. Extend WebSocketMessageBrokerConfigurer and override the necessary methods. which is part of Spring’s WebSocket support and allows you to define security rules for WebSocket endpoints and messages.</p><pre>import org.springframework.context.annotation.Configuration;<br>import org.springframework.security.config.annotation.web.messaging.MessageSecurityMetadataSourceRegistry;<br>import org.springframework.security.config.annotation.web.socket.AbstractSecurityWebSocketMessageBrokerConfigurer;<br><br>@Configuration<br>public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {<br>    @Override<br>    protected void configureInbound(MessageSecurityMetadataSourceRegistry messageSecurityMetadataSourceRegistry) {<br>        messageSecurityMetadataSourceRegistry<br>                // Allow unauthenticated users to connect to the WebSocket server.<br>                .nullDestMatcher().permitAll()<br>                // Grant access to the specific destination for notifications.<br>                .simpSubscribeDestMatchers(&quot;/user/queue/call-notification&quot;).permitAll()<br>                // Deny access to any other messages.<br>                .anyMessage().denyAll();<br>    }<br><br>    @Override<br>    protected boolean sameOriginDisabled() {<br>        return true;<br>    }<br>}</pre><p>@Configuration: This annotation designates the class as a Spring configuration class, indicating that it contains definitions and settings for beans and configuration within the Spring application context.</p><p>WebSocketSecurityConfigextendsAbstractSecurityWebSocketMessageBrokerConfigurer: By extending this class, you are customizing the security configuration specifically tailored for WebSocket communication.</p><p>configureInbound(MessageSecurityMetadataSourceRegistry messageSecurityMetadataSourceRegistry): This method is an overridden configuration method inherited from AbstractSecurityWebSocketMessageBrokerConfigurer. It allows you to define security rules for handling incoming WebSocket messages and their destinations.</p><p>messageSecurityMetadataSourceRegistry.nullDestMatcher().permitAll(): This line permits all messages with a null destination, effectively allowing unauthenticated users to establish connections to the WebSocket server. Typically, this is used for initial connection requests.</p><p>messageSecurityMetadataSourceRegistry.simpSubscribeDestMatchers(&quot;/user/queue/call-notification&quot;).permitAll(): This line grants permission to anyone, whether authenticated or unauthenticated, to subscribe to the /user/queue/call-notification destination. This destination is often used for broadcasting notifications to users.</p><p>messageSecurityMetadataSourceRegistry.anyMessage().denyAll(): This line denies all other types of WebSocket messages. In essence, it rejects any messages that do not adhere to the previously defined rules. This ensures that any messages not explicitly permitted are disallowed.</p><p>sameOriginDisabled(): This method, also inherited from AbstractSecurityWebSocketMessageBrokerConfigurer, determines whether the same-origin policy for WebSocket connections should be disabled. In this case, when return true; is specified, it means that the same-origin policy is turned off, thereby permitting WebSocket connections from any origin.</p><p>2. <strong>Configure WebSocket Broker:</strong></p><p>Next, configure the WebSocket broker and implement a custom handshake handler for authentication.</p><pre>@Configuration<br>@EnableWebSocketMessageBroker<br>@Slf4j<br>public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {<br><br>    @Autowired<br>    AuthenticationManager authenticationManager;<br><br>    @Autowired<br>    AdapterDeploymentContext adapterDeploymentContext;<br><br>    @Autowired<br>    KeycloakDeployment keycloakDeployment;<br><br>    @Override<br>    public void configureMessageBroker(MessageBrokerRegistry config) {<br>        config.enableSimpleBroker(&quot;/queue&quot;);<br>        config.setApplicationDestinationPrefixes(&quot;/app&quot;);<br>        config.setUserDestinationPrefix(&quot;/user&quot;);<br>    }<br><br>    @Override<br>    public void registerStompEndpoints(StompEndpointRegistry registry) {<br>        registry.addEndpoint(&quot;/ws&quot;).setAllowedOrigins(&quot;*&quot;).setHandshakeHandler(new DefaultHandshakeHandler() {<br><br>            @Override<br>            protected Principal determineUser(<br>                    ServerHttpRequest request, WebSocketHandler wsHandler, Map&lt;String, Object&gt; attributes) {<br>                WebSocketHttpHeaders headers = new WebSocketHttpHeaders(request.getHeaders());<br>                if (!headers.getSecWebSocketProtocol().isEmpty() &amp;&amp; headers.getSecWebSocketProtocol().get(0).startsWith(&quot;Bearer_&quot;)) {<br>                    String token = headers.getSecWebSocketProtocol().get(0).replace(&quot;Bearer_&quot;, &quot;&quot;);<br>                    AccessToken accessToken;<br>                    try {<br>                        accessToken = AdapterTokenVerifier.verifyToken(token, keycloakDeployment);<br>                        if (accessToken.getResourceAccess().containsKey(&quot;keycloak_client&quot;) &amp;&amp; accessToken.getResourceAccess().get(&quot;keycloak_client&quot;).getRoles().contains(&quot;ADMIN&quot;)) {<br>                            return new WebSocketUser(accessToken.getEmail());<br>                        }<br>                    } catch (VerificationException e) {<br>                        throw new BadCredentialsException(&quot;Invalid token&quot;, e);<br>                    }<br>                }<br>                throw new BadCredentialsException(&quot;Unauthorized&quot;);<br>            }<br>        });<br>    }<br><br>    @AllArgsConstructor<br>    @Getter<br>    private static class WebSocketUser implements Principal {<br>        private String name;<br>    }<br><br>}</pre><p>This code is a configuration class for Spring WebSocket support using Spring WebSocket and Spring Security. It also includes authentication using Keycloak tokens sent via the WebSocket handshake.</p><p>@EnableWebSocketMessageBroker: This annotation enables WebSocket message handling with a message broker. It’s typically used in combination with Spring’s WebSocket support.</p><p>Autowired Dependencies:</p><p>AuthenticationManager: This bean is part of Spring Security and is used for authenticating WebSocket connections.</p><p>AdapterDeploymentContext: A bean related to Keycloak integration, used for managing Keycloak adapter deployments.</p><p>KeycloakDeployment: Represents the configuration of the Keycloak client, including the Keycloak server’s URL and other settings.</p><p>configureMessageBroker Method: This method is used to configure the message broker for WebSocket communication.</p><p>config.enableSimpleBroker(&quot;/queue&quot;): Enables a simple message broker that allows sending messages to clients subscribed to destinations starting with &quot;/queue,&quot; which can be used for broadcasting messages to multiple clients.</p><p>config.setApplicationDestinationPrefixes(&quot;/app&quot;): Sets a prefix for destinations where messages from the client to the server are sent. Messages sent from the client should start with &quot;/app.&quot;</p><p>registerStompEndpoints Method: This method registers the WebSocket endpoint and defines the handshake handler for WebSocket connections.</p><p>registry.addEndpoint(&quot;/ws&quot;): Registers a WebSocket endpoint at the path &quot;/ws.&quot;</p><p>setAllowedOrigins(&quot;*&quot;): Allows connections from any origin (though this should be restricted in a production environment).</p><p>setHandshakeHandler(...): Sets a custom handshake handler for performing authentication during the WebSocket handshake.</p><p>Custom Handshake Handler (DefaultHandshakeHandler): This is where custom WebSocket handshake handling logic is implemented.</p><p>The determineUser method is overridden to extract the Keycloak token from the WebSocket handshake headers and verify it using the Keycloak adapter.</p><p>It checks the SecWebSocketProtocol header to find the token, which is expected to start with &quot;Bearer_&quot;.</p><p>If the token is found, it’s verified using AdapterTokenVerifier.verifyToken with the provided Keycloak deployment configuration.</p><p>If the token is valid and the user has the “ADMIN” role for the “keycloak_client” resource in Keycloak, a WebSocketUser object is created with the user&#39;s email as the name and returned as the authenticated principal.</p><p>If the token is not valid or the user doesn’t have the required role, a BadCredentialsException is thrown, indicating unauthorized access.</p><p>WebSocketUser Class: This is a simple class that implements the Principal interface, providing a way to represent the authenticated user. The WebSocketUser class likely contains user information such as the user&#39;s email and possibly other attributes that are relevant to the WebSocket application&#39;s needs.</p><p>By integrating Spring WebSocket with Keycloak, you’ve established a secure, real-time communication channel. While this setup works for many scenarios, consider additional layers like token refresh mechanisms or role-based message filtering for advanced requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fc589746a4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Various EC2 Instance Types And How To Create an EC2 Instance]]></title>
            <link>https://medium.com/@rangika123.kanchana/various-ec2-instance-types-and-how-to-create-an-ec2-instance-357769302873?source=rss-7e25ecd9e014------2</link>
            <guid isPermaLink="false">https://medium.com/p/357769302873</guid>
            <category><![CDATA[create-aws-ec2]]></category>
            <category><![CDATA[aws-instance]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[ec2-instance-type]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Surangi Kanchana]]></dc:creator>
            <pubDate>Tue, 11 Jul 2023 13:01:33 GMT</pubDate>
            <atom:updated>2023-07-11T13:01:33.702Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zc_iqXYh7y4oJP0E6lYTTQ.png" /></figure><p><strong>EC2 instance types: Overview</strong></p><p>EC2 (Elastic Compute Cloud) instances on Amazon Web Services (AWS) come in various types, each designed to cater to different use cases and workloads. Each instance type comes with different specifications for CPU, memory, storage, and networking capabilities. It’s important to choose the appropriate instance type based on your specific workload requirements, performance needs, and budget considerations.</p><p>AWS has the following naming convention for instances:</p><p>Ex: <strong>m5.xlarge</strong></p><p><strong>m:</strong> instance class ( in this case, this is a general purpose type of instance )</p><p><strong>5:</strong> generation ( As AWS continues to enhance its hardware offerings, it periodically releases new generations of instance classes. For example, if there are improvements to the m series of instances after m5, the next generation could be designated as m6. )</p><p><strong>xlarge:</strong> size within the instance class ( The size of EC2 instances typically follows a pattern, starting with small sizes and progressively increasing to medium, large, xlarge, 2xlarge, and so on. As the instance size increases, there is a corresponding increase in the available memory and CPU resources. In other words, larger instances offer greater memory capacity and more powerful CPUs compared to smaller instances. This scaling allows users to choose the instance size that aligns with their specific requirements, ensuring sufficient resources to handle their workloads effectively. )</p><p>Here are some of the commonly used EC2 instance types:</p><ol><li>General Purpose:</li></ol><p>General-purpose instances are well-suited for a wide range of workloads, including web servers and code repositories. These instances provide an excellent balance between compute, memory, and networking resources. With general-purpose instances, users can expect optimal performance and efficiency, as they are designed to handle diverse workloads effectively. Whether you need to run web applications or store and manage code repositories, these instances offer the necessary compute power, memory capacity, and networking capabilities to ensure smooth operations.</p><p>2. Compute Optimized:</p><p>Compute optimized instances are specifically designed to handle compute-intensive tasks that demand high-performance processors. These tasks include batch processing workloads, media transcoding, high-performance web servers, high-performance computing, scientific modeling, and machine learning, as well as dedicated gaming servers. These workloads necessitate a robust and capable CPU to ensure fast and efficient processing, making compute optimized instances the ideal choice for these demanding tasks.</p><p>3. Memory Optimized:</p><p>Memory optimized instances are specifically designed to deliver fast performance for workloads that involve processing large datasets in memory. These instances are well-suited for various high-performance use cases, including relational and non-relational databases, distributed web-scale cache stores, and in-memory databases optimized for business intelligence (BI). Additionally, memory optimized instances excel in applications that require real-time processing of big unstructured data, enabling efficient and speedy data analysis and operations. By leveraging their optimized memory capacity, these instances enable superior performance and responsiveness for memory-intensive workloads.</p><p>4. Storage Optimized:</p><p>Storage optimized instances are well-suited for tasks that demand extensive, sequential read and write access to large data sets stored locally. These instances are particularly advantageous for high-frequency online transaction processing (OLTP) systems, relational and NoSQL databases that require fast caching, in-memory databases, data warehousing applications, and distributed file systems. By leveraging the high storage capacity and optimized storage performance of these instances, organizations can efficiently handle data-intensive workloads and achieve optimal performance for their storage-centric applications.</p><p><strong>How do I create an EC2 instance?</strong></p><p>To create an EC2 (Elastic Compute Cloud) instance on Amazon Web Services (AWS), you can follow these general steps:</p><ol><li>Sign in to the AWS Management Console.</li><li>Open the EC2 service.</li><li>Click on the Instances.</li><li>Click on “Launch Instance” to start the instance creation process.</li><li>Give it a proper name.</li><li>Select an Amazon Machine Image (AMI) that contains the OS and software configuration you want for your instance.</li></ol><p>To select the OS type for an Amazon Machine Image (AMI), it is important to consider various factors. Start by identifying the specific requirements of your application or project, such as programming language compatibility and necessary software dependencies. Then, evaluate the different operating system options available, including popular Linux distributions like Ubuntu, MacOS, CentOS, Amazon Linux, or Windows Server for Windows-based applications. Take into account the availability of community support and resources for the chosen OS, as this can be invaluable when troubleshooting or seeking guidance. Additionally, review the security track record, stability, cloud compatibility, performance characteristics, and cost considerations of each OS. By carefully considering these factors, you can make an informed decision on the OS type that best aligns with your application’s needs.</p><p>Here, I have selected Ubuntu as my OS type. Ubuntu is indeed a commonly used OS type for various applications, including running EC2 instances. Its popularity stems from its wide support, extensive package availability, and cloud readiness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*vUJp_bpI-qZCl46EFU0Q6A.png" /></figure><p>7. Choose an instance type that aligns with your requirements in terms of CPU, memory, storage, and networking capacity.</p><p>Here, I have used t2.small because t2.micro is not enough for my build and ram is not enough for building my projects. But t2.micro is a free tier (up to 750 hours per month for the first year).</p><p>8. Choose an existing key pair or create a new key pair if you are using the SSH utility to access the instance.</p><p>If you are creating a key pair, give it a proper name, select the key pair type as RSA, If you have Mac, Linux or Windows 10, then you can select the .pem format. If you have Windows less than version 10, then you can directly use a PPK, which is going to be used for PuTTY, and create the key pair. After creating a key pair, you can select which one you created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*ZuaKa2bmjyi5rAKdbcitIw.png" /></figure><p>9. Configure the instance details, such as network settings, security groups, and other advanced options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*NI_B3nyttkZQUX4Xor0eRg.png" /></figure><p>10. Optionally, add storage volumes or modify the storage configurations as needed.</p><p>Free-tier eligible customers can get up to 30 GB of EBS General Purpose (SSD) or Magnetic storage</p><p>11. Configure any additional settings required for your specific use case, such as user data, metadata, or instance tags. In my case, I don&#39;t need to change any additional settings.</p><p>User data refers to the capability of passing a script to an EC2 instance, which will be executed during the initial launch of the instance. This feature enables us to conveniently provide and execute custom scripts or commands on our EC2 instances, allowing for seamless configuration and setup during the instance’s first launch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*A1ccXKmq7Vlmi32F9VUb9w.png" /></figure><p>12. Review the instance details and configurations to ensure they are correct. then you can launch the instance.</p><p>13. Once the instance is running, you can connect to it using SSH or other remote access methods.</p><p>Now your instance is running.</p><p>Thanks for reading……….!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=357769302873" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keycloak Integration For Flutter Web Using openid_client with Authorization Code Flow]]></title>
            <link>https://medium.com/@rangika123.kanchana/keycloak-integration-for-flutter-web-using-openid-client-with-authorization-code-flow-489afeac6e9f?source=rss-7e25ecd9e014------2</link>
            <guid isPermaLink="false">https://medium.com/p/489afeac6e9f</guid>
            <category><![CDATA[authorization-code]]></category>
            <category><![CDATA[keycloack-with-flutter]]></category>
            <category><![CDATA[flutter-web]]></category>
            <category><![CDATA[pkce]]></category>
            <category><![CDATA[openid]]></category>
            <dc:creator><![CDATA[Surangi Kanchana]]></dc:creator>
            <pubDate>Thu, 06 Jul 2023 16:37:48 GMT</pubDate>
            <atom:updated>2023-07-06T16:37:48.681Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xhic7oK1sWfDCPhvOktpRQ.png" /></figure><p>The Authorization Code Flow with Proof Key for Code Exchange (PKCE) provides an enhanced security mechanism for public clients (such as web or mobile applications) when requesting access tokens from an authorization server.</p><p><strong>Lets look how PKCE works in a flow chart</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*D0XUy5RnGdX709AOL-eavA.png" /></figure><p>Sure! Here’s an explanation of the steps involved in the PKCE flow:</p><p>1. The user clicks Login within the application.<br>The user initiates the authentication process by clicking the login button in the application.</p><p>2. The application creates a cryptographically-random code_verifier and generates a code_challenge.<br>The application generates a random code_verifier and derives a code_challenge from it using a hash function, typically SHA256.</p><p>3. The application redirects the user to the Keycloak server along with the code_challenge.<br>The application constructs a request to the Keycloak server’s authentication endpoint, including the `code_challenge` as a parameter.</p><p>4. Keycloak server redirects the user to the login and authorization prompt.<br> Keycloak server receives the request from the application and redirects the user to its login and authorization prompt page.</p><p>5. The user authenticates using one of the configured login options.<br>The user provides their credentials and goes through the authentication process using one of the available login options provided by Keycloak.</p><p>6. Keycloak server stores the code_challenge and redirects the user back to the application with an authorization code, which is valid for one use.<br>Upon successful authentication, Keycloak server associates the code_challenge with the generated authorization code and redirects the user back to the application’s specified redirect URI, including the authorization code.</p><p>7. The application sends this authorization code and the code_verifier (created in step 2) to the Keycloak server.<br>The application exchanges the received authorization code with the original code_verifier it generated and sends them to the Keycloak server’s token endpoint.</p><p>8. Keycloak server verifies the code_challenge and code_verifier.<br> Keycloak server verifies the code_challenge and code_verifier received from the application to ensure their integrity and match.</p><p>9. Keycloak server responds with an ID token and access token (and optionally, a refresh token).<br> If the code_challenge and code_verifier are successfully verified, Keycloak server responds with an ID token and access token, which can be used to authenticate the user and access protected resources.</p><p>10. Your application can use the access token to call an API and access information about the user.<br>The application can include the access token in API requests to authenticate and authorize the user, enabling access to protected resources or retrieving user-specific data.</p><p>11. The API responds with the requested data.<br> The API server validates the access token sent by the application and responds with the requested data if the token is valid and the user has the necessary permissions.</p><p>By following this PKCE flow, applications can ensure secure authentication and authorization, protecting against potential threats such as interception of the authorization code during transmission.</p><p><strong>Implementation</strong></p><p><em>Before starting the Flutter implementation, you have to configure your keycloak server. If you are not familiar with keycloack configuration, I recommend visiting the official </em><a href="https://www.keycloak.org/getting-started/getting-started-zip"><em>keycloack document</em></a><em>.</em></p><p>To ensure secure authentication, it is recommended to use the Authorization Code flow rather than the Implicit flow when working with OpenID Connect. However, the openid_client library, specifically the browser version, only supports the Implicit flow. If you are using <strong>Implicit</strong> as the flow type, you can use below code:</p><p><a href="https://pub.dev/packages/openid_client">openid_client | Dart Package</a></p><pre>// import the browser version<br>import &#39;package:openid_client/openid_client_browser.dart&#39;;<br><br>authenticate(Uri uri, String clientId, List&lt;String&gt; scopes) async {   <br>    <br>    // create the client<br>    var issuer = await Issuer.discover(uri);<br>    var client = new Client(issuer, clientId);<br>    <br>    // create an authenticator<br>    var authenticator = new Authenticator(client, scopes: scopes);<br>    <br>    // get the credential<br>    var c = await authenticator.credential;<br>    <br>    if (c==null) {<br>      // starts the authentication<br>      authenticator.authorize(); // this will redirect the browser<br>    } else {<br>      // return the user info<br>      return await c.getUserInfo();<br>    }<br>}</pre><p>Implicit flow type is considered less secure. To overcome this limitation, you can switch to using the openid_client library with slight modifications to the code. With openid_client, you will need to create a code verifier and store it securely in the window.sessionStorage or a similar storage mechanism. This code verifier will be used in the <strong>Authorization Code flow</strong> for enhanced security. Instead of relying on the openid_client library to handle the code verifier, you need to create and manage it yourself.</p><p>Once you have the code verifier stored, you can pass it as a parameter to the authorizationCodeWithPKCE method of openid_client. This method will internally generate the code challenge using the provided code verifier and perform the Authorization Code flow with PKCE.</p><p>By making these modifications, you can ensure that the more secure Authorization Code flow is used, with the code verifier being generated and managed by your application rather than relying on the openid_client library to handle it.</p><pre>static String _randomString(int length) {<br>    var r = math.Random.secure();<br>    var chars =<br>        &#39;0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&#39;;<br>    return Iterable.generate(length, (_) =&gt; chars[r.nextInt(chars.length)])<br>        .join();<br>  }<br><br>  static Future&lt;Credential&gt; authenticateWeb() async {<br>    var Uri discoveryUri = Uri.https(&quot;your discover uri&quot;);<br>    var clientId = &quot;your client id&quot;;<br>    var scopes = [&#39;openid&#39;, &#39;profile&#39;, &#39;email&#39;, &#39;offline_access&#39;];<br>    var issuer = await Issuer.discover(discoveryUri);<br>    var client = Client(issuer, clientId);<br><br>    var codeVerifier =<br>        window.sessionStorage[&quot;auth_code_verifier&quot;] ?? _randomString(50);<br>    var state = window.sessionStorage[&quot;auth_state&quot;] ?? _randomString(20);<br>    var responseUrl = window.sessionStorage[&quot;auth_callback_response_url&quot;];<br>    var flow = authorizationCodeWithPKCE(<br>      client,<br>      scopes: scopes,<br>      codeVerifier: codeVerifier,<br>      state: state,<br>    );<br><br>    flow.redirectUri =<br>        Uri.parse(<br>            &#39;${window.location.protocol}//${window.location.host}${window.location.pathname}&#39;);<br><br>    if (responseUrl != null) {<br>      // handle callback<br>      try {<br>        var responseUri = Uri.parse(responseUrl);<br>        var credentials = await flow.callback(responseUri.queryParameters);<br>        return credentials;<br>      } finally {<br>        window.sessionStorage.remove(&quot;auth_code_verifier&quot;);<br>        window.sessionStorage.remove(&quot;auth_callback_response_url&quot;);<br>        window.sessionStorage.remove(&quot;auth_state&quot;);<br>      }<br>    } else {<br>      // redirect to auth server<br>      window.sessionStorage[&quot;auth_code_verifier&quot;] = codeVerifier;<br>      window.sessionStorage[&quot;auth_state&quot;] = state;<br>      var authorizationUrl = flow.authenticationUri;<br>      window.location.href = authorizationUrl.toString();<br>      throw &quot;Authenticating...&quot;;<br>    }<br>  }</pre><p><strong>Let’s go through the code step by step:</strong></p><p>1. The _randomString function generates a random string of the specified length using alphanumeric characters.</p><p>2. The authenticateWeb function is an asynchronous function that performs web-based authentication. It starts by discovering the OpenID Connect issuer (authorization server) using the discoveryUri.</p><p>3. A client is created using the discovered issuer and clientId.</p><p>4. The codeVerifier, state, and responseUrl are obtained from window.sessionStorage or randomly generated if not present. The codeVerifier is a random string used in the PKCE (Proof Key for Code Exchange) flow for enhanced security.</p><p>5. An authorization flow is initialized using the OpenID Connect Flow.authorizationCodeWithPKCE method. The client, scopes, code verifier, and state are provided as parameters.</p><p>6. The redirectUri is set for the flow. It is derived from the current window’s location, preserving the protocol, host, and path.</p><p>7. If a responseUrl is present, it means a callback has occurred after authentication. The response URL is parsed, and the flow’s callback method is invoked to obtain the credentials. The credentials are returned.</p><p>8. If there is no responseUrl, it means authentication needs to be initiated. The codeVerifier and state are stored in window.sessionStorage, and the authentication URL is obtained from the flow’s authenticationUri. The browser is then redirected to the authentication URL for the user to authenticate.</p><p>9. In the event of an exception, the window.sessionStorage is cleared of temporary data related to authentication.</p><p>Overall, this code implements the authentication process using OpenID Connect, including the PKCE flow for enhanced security, handling callbacks, and redirecting the user for authentication.</p><p>and change your index.html file</p><pre>&lt;script&gt;<br>    window.addEventListener(&#39;load&#39;, function(ev) {<br>      // include this part to your index.html page<br>      if(window.location.href.includes(&#39;?code=&#39;) || window.location.href.includes(&#39;&amp;code=&#39;)) {      <br>        sessionStorage.setItem(&quot;auth_callback_response_url&quot;, window.location.href);<br>        location.assign(&quot;/&quot;);<br>      }<br>      // -----------------------------------<br>      _flutter.loader.loadEntrypoint({<br>        serviceWorker: {<br>          serviceWorkerVersion: serviceWorkerVersion,<br>        },<br>        onEntrypointLoaded: function(engineInitializer) {<br>          engineInitializer.initializeEngine().then(function(appRunner) {<br>            appRunner.runApp();<br>          });<br>        }<br>      });<br>    });<br>  &lt;/script&gt;</pre><p>I hope you learned how to integrate keycloack with Flutter Web using openid_client with Authorization code.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=489afeac6e9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>