<?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 Himanshu Pratap on Medium]]></title>
        <description><![CDATA[Stories by Himanshu Pratap on Medium]]></description>
        <link>https://medium.com/@hpratap?source=rss-d79db9a9737a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zgsHz7TS3gymqaU5zxv7FA.jpeg</url>
            <title>Stories by Himanshu Pratap on Medium</title>
            <link>https://medium.com/@hpratap?source=rss-d79db9a9737a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:50:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hpratap/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[Deploy a python web application to production offline server]]></title>
            <link>https://hpratap.medium.com/deploy-a-python-web-application-to-production-offline-server-a0665baad6b9?source=rss-d79db9a9737a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0665baad6b9</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[production-deployment]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Himanshu Pratap]]></dc:creator>
            <pubDate>Mon, 27 Jan 2025 06:13:39 GMT</pubDate>
            <atom:updated>2025-01-27T08:00:33.351Z</atom:updated>
            <content:encoded><![CDATA[<p>The python application is hosted using Gunicorn webserver. Since the production server does not have internet, so along with python application we also need to export python pip dependencies from dev server. Ensure that OS version on dev server (having internet connectivity) and production server (offline) are having same OS version and python version installed.</p><p>Here, we are having RHEL 8.10 on production server (offline) and RHEL 8.10 on development server (online).</p><p>Steps are as follows.</p><p><strong>i) Generate the list of dependencies of your application on dev server</strong></p><p>$ cd &lt;your project folder&gt;<br>$ pip freeze &gt; /tmp/requirements.txt</p><p><strong>ii) Create local pip repo for the list of dependencies dev server</strong></p><p>$ mkdir /tmp/myrepo<br>$ cd /tmp/myrepo <br>$ pip download -r /tmp/requirements.txt</p><p><strong>iii) Copy the application folder, repo folder and requirements.txt from dev server to production server</strong></p><p><strong>4. Deployment of Application</strong></p><p>Execute following commands on production server:</p><p><strong>i) Create a separate user and group for the application</strong></p><p># useradd -m -s /bin/bash appuser<br># groupadd appgroup<br># usermod -aG appgroup appuser</p><p><strong>ii) Copy the application folder to /var/www folder</strong></p><p># mkdir -p /var/www/myapp<br># cp -r /tmp/&lt;application folder&gt;/* /var/www/myapp<br># chown -R appuser:appgroup /var/www/myapp</p><p><strong>iii) create a new directory for the logs</strong></p><p># mkdir -p /var/log/myapp</p><p><strong>iv) Install the dependencies</strong></p><p>login using application user ie appuser and install the dependencies.</p><p>$ pip install — no-index — find-links=/path/to/packages *.whl</p><p><strong>Note: Ensue gunicorn dependency is installed using root user since it will be used to host the Application</strong></p><p><strong>v) Create a systemd Service File</strong></p><p># vim /etc/systemd/system/myapp.service</p><p>[Unit]<br>Description=myapp<br>After=network.target<br>[Service]<br>User=appuser<br>Group=appgroup<br>WorkingDirectory=/var/www/myapp<br>ExecStart=/usr/bin/gunicorn -w 8 -b 192.168.1.10:5000 app:app<br>Restart=always<br>[Install]<br>WantedBy=multi-user.target</p><p><strong>vi) Reload systemd and start the service</strong></p><p># systemctl daemon-reload<br># systemctl start myapp<br># systemctl status myapp<br># systemctl enable myapp</p><p><strong>vii) Allow incoming traffic on port 5000</strong></p><p># firewall-cmd — zone=public — add-port=5000/tcp — permanent<br># firewall-cmd — reload</p><p><strong>viii) Test the application</strong></p><p><a href="http://192.168.1.10:5000/">http://192.168.1.10:5000</a></p><p>Thats it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0665baad6b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create production build (executable) of a Python application]]></title>
            <link>https://hpratap.medium.com/create-production-build-executable-of-a-python-application-61fec32549ad?source=rss-d79db9a9737a------2</link>
            <guid isPermaLink="false">https://medium.com/p/61fec32549ad</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[pyinstaller]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Himanshu Pratap]]></dc:creator>
            <pubDate>Sun, 23 Jun 2024 06:09:36 GMT</pubDate>
            <atom:updated>2024-06-23T06:09:36.645Z</atom:updated>
            <content:encoded><![CDATA[<p>PyInstaller is used to package Python code into standalone executable applications for various operating systems. PyInstaller analyzes your code to discover every other module and library your script needs in order to execute. Then it collects copies of all those files — including the active Python interpreter. This allows for easy distribution and deployment of Python applications, as the user does not need to have Python and any required modules installed on their system in order to run the application.</p><p>Note: PyInstaller generates Windows executable if it is run in windows environment. It generates linux executable if it is run in linux environment.</p><p>1. install pyinstaller<br>pip install pyinstaller</p><p>2. To check if pyinstaller is installed successfully,<br>pyinstaller --version</p><p>3. create executable. the execuatble will be unser dist directory<br>pyinstaller main.py</p><p>4. create single file executable<br>pyinstaller main.py --onefile</p><p>5. Changing executable name<br>pyinstaller main.py --onefile --name MyExecutable</p><p>6. If you want to hide the console window when running the executable file, you can use the — noconsole option:<br>pyinstaller --noconsole --onefile hello.py --name MyExecutable</p><p>Note: You might encounter some issues if You want to add underscores to executable file name.</p><p><strong>There is another application auto-py-to-exe that is based on PyInstaller but provides GUI.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61fec32549ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configure NTP server using Chrony on RHEL 8]]></title>
            <link>https://hpratap.medium.com/configure-ntp-server-using-chrony-on-rhel-8-b0cf02f8440d?source=rss-d79db9a9737a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0cf02f8440d</guid>
            <category><![CDATA[rhel]]></category>
            <category><![CDATA[rhel-8]]></category>
            <category><![CDATA[ntp-server]]></category>
            <category><![CDATA[chrony]]></category>
            <category><![CDATA[system-administration]]></category>
            <dc:creator><![CDATA[Himanshu Pratap]]></dc:creator>
            <pubDate>Wed, 12 Jun 2024 09:23:35 GMT</pubDate>
            <atom:updated>2024-06-12T09:24:04.323Z</atom:updated>
            <content:encoded><![CDATA[<ol><li><strong>Install Chrony</strong> (if not already installed):</li></ol><p>You can install Chrony using the package manager dnf. Run the following command in your terminal:</p><p>#sudo dnf install chrony</p><p><strong>2. Edit the Chrony Configuration File</strong>:</p><p>Open the Chrony configuration file /etc/chrony.conf in a text editor with root privileges. You can use nano, vim, or any other editor you prefer.</p><p>#sudo vim /etc/chrony.conf</p><p><strong>3. Configure NTP Servers</strong>:</p><p>In the chrony.conf file, you’ll find a section where you can specify NTP servers. Locate the server directive and add your NTP server(s) to it. You can comment out existing servers or add new ones. For example: Replace ntp.example.com with the address of the NTP server you want to use.</p><p>server time.nplindia.org iburst</p><p><strong>4. Restart Chrony</strong>:</p><p>After making changes to the configuration file, restart the Chrony service to apply the changes:</p><p>#sudo systemctl restart chronyd</p><p><strong>5. Verify Configuration</strong>:</p><p>You can verify that Chrony is synchronizing with the new NTP server(s) by checking its status:</p><p>#chronyc sources -v</p><p>This command will display information about the currently configured NTP sources and their synchronization status.</p><p>That’s it! You have now set a new NTP server using Chrony on RHEL 8. Make sure to choose reliable NTP servers for accurate time synchronization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0cf02f8440d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enable gnome classic on RHEL8]]></title>
            <link>https://hpratap.medium.com/enable-gnome-classic-on-rhel8-b43610fca6de?source=rss-d79db9a9737a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b43610fca6de</guid>
            <category><![CDATA[gnome]]></category>
            <category><![CDATA[gnome-3]]></category>
            <category><![CDATA[rhel-8]]></category>
            <category><![CDATA[system-administration]]></category>
            <dc:creator><![CDATA[Himanshu Pratap]]></dc:creator>
            <pubDate>Wed, 27 Apr 2022 09:54:23 GMT</pubDate>
            <atom:updated>2022-04-27T10:12:39.832Z</atom:updated>
            <content:encoded><![CDATA[<ol><li>Update the system to RHEL8.5 or higher.</li><li>Ensure that the system has gdm-40.0–11.el8(or higher), accountsservice-0.6.55–2.el8(or higher)</li></ol><pre>#rpm -qa gdm <br>#rpm -qa accountsservice</pre><p>3. copy the /usr/share/accountsservice/user-templates/standard file to /etc/accountsservice/user-templates/standard</p><pre># cp /usr/share/accountsservice/user-templates/standard /etc/accountsservice/user-templates/standard</pre><p>4. Change the value of Session=gnome with Session=gnome-classic in the /etc/accountsservice/user-templates/standard file</p><pre># vim /etc/accountsservice/user-templates/standard<br>[Template]<br>EnvironmentFiles=/etc/os-release;</pre><pre>[com.redhat.AccountsServiceUser.System]<br>id=&#39;${ID}&#39;<br>version-id=&#39;${VERSION_ID}&#39;</pre><pre>[User]<br>Session=gnome-classic<br>Icon=${HOME}/.face</pre><p>5. Switch the runlevel</p><pre># init 3<br># init 5</pre><p>6. Install gnome-tweaks application</p><pre># dnf install gnome-tweaks</pre><p>7. Open the Tweaks application. Select Extensions.</p><pre>Enable Application menu<br>Enable Desktop icons<br>Enable Places status indicator<br>Enable Window list</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*ymhI5oeJTunolYDLnY6Z9A.png" /><figcaption>tweaks</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b43610fca6de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Install Postgresql 13 on RHEL 8. Configure scram-sha-256 password authentication.]]></title>
            <link>https://hpratap.medium.com/install-postgresql-13-on-rhel-8-configure-scram-sha-256-password-authentication-f819f523b1b6?source=rss-d79db9a9737a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f819f523b1b6</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[postgresql-tutorials]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[postgresql13]]></category>
            <dc:creator><![CDATA[Himanshu Pratap]]></dc:creator>
            <pubDate>Wed, 13 Apr 2022 10:55:24 GMT</pubDate>
            <atom:updated>2023-05-18T07:17:27.392Z</atom:updated>
            <content:encoded><![CDATA[<ol><li>Steps Summary <br>a. install postgresql-server<br>b. initialize database<br>c. set password for postgres os user<br>d. enable and run postgresql service<br>e. modify postgresql.conf file ( listen_address and password_encryption)<br>f. login to postgresql database using peer authentication and modify postgres db user password<br>g. modify pg_hba.conf file to set authnetication to scram-sha-256<br>h. restart postgresql service.</li><li>Install postgresql 13</li></ol><pre># dnf module list | grep postgres<br># dnf module install postgresql:13</pre><p>2. Initialize database</p><pre># which postgresql-setup<br># postgresql-setup --initdb</pre><p>3. Change password for os user postgres auto created after installing postgresql</p><pre># passwd postgres</pre><p>4. Enable and start postgresql service</p><pre># systemctl enable postgresql<br># systemctl start postgresql<br># systemctl status postgresql</pre><p>5. Modify postgresql.conf file</p><pre>#vim /var/lib/pgsql/data/postgresql.conf</pre><pre>listen_addresses = &#39;*&#39;<br>password_encryption = scram-sha-256</pre><p>6. login to postgres database using peer authentication.</p><pre># su - postgres<br># psql<br>postgres=# \conninfo</pre><p>7. Change postgres database user password and password encryption method</p><pre>postgres=# \password<br>postgres=# set password_encryption TO &#39;scram-sha-256&#39;;</pre><p>8. Change authentication type to scram-sha-256 in pg_hba.conf file</p><pre># cd /var/lib/pgsql/data<br># vim pg_hba.conf</pre><pre># TYPE  DATABASE        USER            ADDRESS                 METHOD</pre><pre># &quot;local&quot; is for Unix domain socket connections only<br>local   all   all                              scram-sha-256<br># IPv4 local connections:<br>host    all   all     127.0.0.1/32             scram-sha-256<br># IPv6 local connections:<br>host    all   all      ::1/128                 scram-sha-256<br># Allow replication connections from localhost, by a user with the<br># replication privilege.<br>local   replication     all                     scram-sha-256<br>host    replication     all    127.0.0.1/32     scram-sha-256<br>host    replication     all    ::1/128          scram-sha-256</pre><p>9. Restart postgresql service and login using password authentication</p><pre># systemctl restart postgresql<br>$ psql -U postgres -d postgres</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f819f523b1b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[git — beginners guide]]></title>
            <link>https://hpratap.medium.com/git-beginners-guide-e034b44a5f10?source=rss-d79db9a9737a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e034b44a5f10</guid>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Himanshu Pratap]]></dc:creator>
            <pubDate>Fri, 04 Mar 2022 09:54:52 GMT</pubDate>
            <atom:updated>2022-03-04T09:54:52.282Z</atom:updated>
            <content:encoded><![CDATA[<h3>git — beginners guide</h3><p>Git was originally authored by Linus Torvalds for development of the Linux kernel, with other kernel developers contributing to its initial development.</p><p>It is an opensource software for tracking changes in any set of files, usually used for collaboratively developing source code during software development.</p><p>Some useful git command</p><ol><li>Check git version</li></ol><pre>$ git --version</pre><p>2. GIT global configuration</p><pre>$ git config --global user.name &quot;Himanshu Pratap&quot;<br>$ git config --global user.email <a href="/service/mailto:himanshupratap@gmail.com">himanshupratap@gmail.com</a><br>$ git config --list<br>$ git config --global core.editor &quot;code --wait&quot;</pre><p>3. Initialize a directory as git repository</p><pre>$ mkdir git_test<br>$ cd git_test<br>$ git init<br>$ git status</pre><p>4. Add files to the staging area</p><pre>$ git add .</pre><p>5. Commit the changes to git repository</p><pre>$ git commit -m &quot;first commit&quot;</pre><p>6. view all git commit</p><pre>$ git log --oneline<br>$ git log</pre><p>7. checkout the file from an older commit</p><pre>$git checkout &lt;commit&gt; &lt;file&gt;</pre><p>8. Add <strong>online remote git repository</strong></p><pre>$ git remote add origin &lt;repository url&gt;<br>$ git push -u origin master</pre><p>9. Clone an online repository</p><pre>$ git clone &lt;repository url&gt;</pre><p>10. Reset to previous commit</p><pre>$ git reset --hard &lt;SOME-COMMIT&gt; t</pre><p>11. Overwrite local files with git pull from remote repository</p><pre>git fetch --all<br>git reset --hard origin/master</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e034b44a5f10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prevent serial column in postgresql from generating duplicate value.]]></title>
            <link>https://hpratap.medium.com/prevent-serial-column-in-postgresql-from-generating-duplicate-value-76e9b06989f0?source=rss-d79db9a9737a------2</link>
            <guid isPermaLink="false">https://medium.com/p/76e9b06989f0</guid>
            <category><![CDATA[sequence-generation]]></category>
            <category><![CDATA[primary-keys]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Himanshu Pratap]]></dc:creator>
            <pubDate>Sat, 26 Feb 2022 07:32:20 GMT</pubDate>
            <atom:updated>2022-02-26T07:32:20.137Z</atom:updated>
            <content:encoded><![CDATA[<p>When you use liquibase’s instruction autoIncrement =”true”, for generation of primary key id, it generates <strong>serial column</strong> for PostgreSQL.</p><p>For serial column PostgreSQL will create a <strong>sequence</strong> with a name like tablename_colname_seq. Default column values will be assigned from this sequence. But <strong>when you explicitly insert a value into serial column, it doesn’t affect sequence generator</strong>, and its next value will not change. So it can generate a duplicate value.</p><p>To prevent this after you inserted explicit values you need to change the current value of a sequence generator either with ALTER SEQUENCE statement or with setval() function, e.g.:</p><pre>ALTER SEQUENCE tablename_colname_seq RESTART WITH 52;<br>SELECT setval(&#39;tablename_colname_seq&#39;, (SELECT max(colname) FROM tablename));</pre><p>Resources:</p><p><a href="https://stackoverflow.com/questions/44744365/liquibase-postgresql-spring-jpa-id-auto-increment-issue"><strong>https://stackoverflow.com/questions/44744365/liquibase-postgresql-spring-jpa-id-auto-increment-issue</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76e9b06989f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configure Amazon linux workspace for web development]]></title>
            <link>https://hpratap.medium.com/configure-amazon-linux-workspace-for-web-development-1f6d208c7c22?source=rss-d79db9a9737a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f6d208c7c22</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[system-administration]]></category>
            <category><![CDATA[amazon-workspaces]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Himanshu Pratap]]></dc:creator>
            <pubDate>Sun, 23 Jan 2022 10:12:55 GMT</pubDate>
            <atom:updated>2022-01-23T10:12:55.976Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Amazon WorkSpaces </strong>are easily provision cloud-based desktops that allow end-users to access applications and resources. <strong>Amazon EC2</strong> is Scalable, pay-as-you-go compute capacity in the cloud.</p><p>Amazon EC2 can be classified as a tool in the “Cloud Hosting” category, while Amazon WorkSpaces is grouped under “Virtual Desktop”.</p><p>Amazon workspace can be of windows type or linux type. This article is about configuring your amazon linux workspace so that it is ready for full stack web development.</p><ol><li>Login in to your workspace using Amazon workspace client application. The application can be download from link - <a href="https://clients.amazonworkspaces.com/">https://clients.amazonworkspaces.com/</a></li></ol><p>2. Check logged in user and os details</p><pre>$ whoami<br>$ uname -a</pre><p>For web development i require following tools to be installed:<br><strong> java, postgresql, node, vs code and eclipse.</strong></p><p>Steps to install &amp; configure these tools are as follows.</p><p><strong>3. Install/Configure Java 11</strong></p><p>By default , two version of java comes on the linux workspace.<br>java-1.8.0-openjdk 1.8<br>java-11-amazon-corretto</p><p>You can check out difference between openjdk and amazon-corretto version at this stackoverflow post-<br><a href="https://stackoverflow.com/questions/53305934/differences-amazon-corretto-and-openjdk">https://stackoverflow.com/questions/53305934/differences-amazon-corretto-and-openjdk</a></p><pre>$ sudo amazon-linux-extras install java-openjdk11<br>$ sudo alternatives --config java</pre><p><strong>4. Install Postgresql 13 server</strong></p><pre><strong> Add PostgreSQL Yum Repository</strong></pre><pre>$ sudo tee /etc/yum.repos.d/pgdg.repo&lt;&lt;EOF<br>[pgdg13]<br>name=PostgreSQL 13 for RHEL/CentOS 7 - x86_64<br>baseurl=<a href="https://download.postgresql.org/pub/repos/yum/13/redhat/rhel-7-x86_64">https://download.postgresql.org/pub/repos/yum/13/redhat/rhel-7-x86_64</a><br>enabled=1<br>gpgcheck=0<br>EOF</pre><pre><strong>Run system update</strong><br>$ sudo yum update</pre><pre><strong>Install PostgreSQL</strong><br>$ sudo yum install postgresql13 postgresql13-server</pre><pre><strong>Initialize the PostgreSQL Database</strong><br>$ sudo /usr/pgsql-13/bin/postgresql-13-setup initdb</pre><pre><strong>Enable and Start PostgreSQL Service</strong><br>$ sudo systemctl start postgresql-13<br>$ sudo systemctl enable postgresql-13<br>$ sudo systemctl status postgresql-13</pre><pre><strong>Change os user postgres password</strong><br>$ sudo passwd postgres</pre><pre><strong>change the Admin database password</strong><br>$ sudo su - postgres<br>$ psql -c &quot;ALTER USER postgres WITH PASSWORD &#39;your-password&#39;;&quot;</pre><pre><strong>Permit login to database through username and password instead of peer. (Optional)</strong><br>$ sudo vim /var/lib/pgsql/13/data/pg_hba.conf<br># TYPE  DATABASE        USER            ADDRESS                 METHOD<br># &quot;local&quot; is for Unix domain socket connections only<br>local   all             all                                  scram-sha-256<br># IPv4 local connections:<br>host    all             all             0.0.0.0/0            scram-sha-256<br># IPv6 local connections:<br>host    all             all             ::1/128                 scram-sha-256<br># Allow replication connections from localhost, by a user with the<br># replication privilege.<br>local   replication     all                                     peer<br>host    replication     all             127.0.0.1/32            scram-sha-256<br>host    replication     all             ::1/128                 scram-sha-256</pre><pre><strong>Allow postgresql-server to listen all ip address (Optional)</strong><br>$sudo vim /var/lib/pgsql/13/data/postgresql.conf <br>listen_address=&#39;*&#39;</pre><pre><strong>Restart services and check the version</strong><br>$ sudo systemctl restart postgresql-13<br>$ psql -V</pre><p><strong>5. Install Nodejs 16</strong></p><pre>$ curl -sL <a href="https://rpm.nodesource.com/setup_16.x">https://rpm.nodesource.com/setup_16.x</a> | sudo -E bash -<br>$ sudo yum install -y nodejs <br>$ node -v</pre><p><strong>6. Install Microsoft visual studio code</strong></p><pre>$ sudo rpm --import <a href="https://packages.microsoft.com/keys/microsoft.asc">https://packages.microsoft.com/keys/microsoft.asc</a><br>$ sudo sh -c &#39;echo -e &quot;[code]\nname=Visual Studio Code\nbaseurl=<a href="https://packages.microsoft.com/yumrepos/vscode/nenabled=1/ngpgcheck=1/ngpgkey=https://packages.microsoft.com/keys/microsoft.asc">https://packages.microsoft.com/yumrepos/vscode\nenabled=1\ngpgcheck=1\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc</a>&quot; &gt; /etc/yum.repos.d/vscode.repo&#39;<br>$ sudo yum update<br>$ sudo yum install code<br>$ code -v</pre><p><strong>7. Install Eclipse IDE</strong></p><pre>$ cd ~/Download<br>$ wget <a href="https://www.eclipse.org/downloads/download.php?file=/oomph/epp/2021-12/R/eclipse-inst-jre-linux64.tar.gz">https://www.eclipse.org/downloads/download.php?file=/oomph/epp/2021-12/R/eclipse-inst-jre-linux64.tar.gz</a><br>$ tar -xvf eclipse-inst-jre-linux64.tar.gz<br>$ chmod -R eclipse-installer<br>$ cd eclipse-installer/<br>$ ./eclipse-inst</pre><p>Thats’s it.</p><p>Resources:<br><a href="https://www.how2shout.com/linux/install-postgresql-13-on-aws-ec2-amazon-linux-2/">https://www.how2shout.com/linux/install-postgresql-13-on-aws-ec2-amazon-linux-2/</a><br><a href="https://aws.amazon.com/premiumsupport/knowledge-center/ec2-install-extras-library-software/">https://aws.amazon.com/premiumsupport/knowledge-center/ec2-install-extras-library-software/</a><br><a href="https://hpratap.medium.com/install-postgresql13-on-rhel7-202b1d03cd94">https://hpratap.medium.com/install-postgresql13-on-rhel7-202b1d03cd94</a><br><a href="https://tecadmin.net/install-java-on-amazon-linux/">https://tecadmin.net/install-java-on-amazon-linux/</a><br><a href="https://code.visualstudio.com/docs/setup/linux">https://code.visualstudio.com/docs/setup/linux</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f6d208c7c22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing React Router v6 with code splitting in a React Typescript project.]]></title>
            <link>https://blog.devgenius.io/implementing-react-router-v6-with-code-splitting-in-a-react-typescript-project-14d98e2cab79?source=rss-d79db9a9737a------2</link>
            <guid isPermaLink="false">https://medium.com/p/14d98e2cab79</guid>
            <category><![CDATA[react-router-6]]></category>
            <category><![CDATA[code-splitting]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Himanshu Pratap]]></dc:creator>
            <pubDate>Fri, 14 Jan 2022 07:48:51 GMT</pubDate>
            <atom:updated>2022-01-15T09:05:14.987Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>React Router</strong> is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL.</p><p><strong>React Router v5 vs v6</strong><br>React Router version 6 introduces a few breaking changes from version 5. React Router v6 makes heavy use of <a href="https://reactjs.org/docs/hooks-intro.html">React hooks</a>, so you’ll need to be on React 16.8 or greater before attempting the upgrade to React Router v6.</p><p>There are some changes like <strong>Switch</strong>, <strong>exact</strong>, <strong>component</strong> keywords are removed.</p><pre>//v5<br>&lt;Switch&gt;<br>      &lt;Route exact path=&quot;/&quot; component={Home} /&gt;<br>      &lt;Route path=&quot;/about&quot; component={About} /&gt;<br>&lt;/Switch&gt;</pre><pre>//v6<br>&lt;Routes&gt;<br>      &lt;Route path=&quot;/&quot; element={&lt;Home /&gt;} /&gt;<br>      &lt;Route path=&quot;/about&quot; element={&lt;About /&gt;} /&gt;<br>&lt;/Routes&gt;</pre><p><strong>Lets dive into the code.</strong></p><ol><li>Create a react project with typescript template</li></ol><pre>$ npx create-react-app react-router-typescript --template typescript</pre><p>2. Install react-router-dom dependencies</p><pre>$ cd react-router-typescript<br>$ npm install react-router-dom</pre><p>3. Edit index.tsx file. Enclose App component with BrowserRouter</p><blockquote>BrowserRouter is a router implementation that uses the HTML5 history API(pushState, replaceState and the popstate event) to keep your UI in sync with the URL. It is the parent component that is used to store all of the other components.</blockquote><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import &#39;./index.css&#39;;<br>import App from &#39;./App&#39;;<br>import reportWebVitals from &#39;./reportWebVitals&#39;;<br>import { BrowserRouter } from &quot;react-router-dom&quot;;</pre><pre>ReactDOM.render(<br>  &lt;React.StrictMode&gt;<br><strong>   &lt;BrowserRouter&gt;<br>    &lt;App /&gt;<br>  &lt;/BrowserRouter&gt;</strong><br>  &lt;/React.StrictMode&gt;,<br>  document.getElementById(&#39;root&#39;)<br>);</pre><pre>// If you want to start measuring performance in your app, pass a function<br>// to log results (for example: reportWebVitals(console.log))<br>// or send to an analytics endpoint. Learn more: <a href="https://bit.ly/CRA-vitals">https://bit.ly/CRA-vitals</a><br>reportWebVitals();</pre><p>4. Create three components, Home, Topics, Settings, which will map to our three routes, /, /topics, and /settings.</p><pre><strong>// src/components/Home.tsx</strong><br>const Home = () =&gt; {<br>    return &lt;p&gt;Home&lt;/p&gt;;<br>}<br>export default Home;</pre><pre><strong>// src/components/Settings.tsx<br></strong>const Settings = () =&gt; {<br>    return &lt;p&gt;Settings&lt;/p&gt;;<br>}<br>export default Settings;</pre><pre><strong>// src/components/Topics.tsx</strong><br>const Topics = () =&gt; {<br>    return &lt;p&gt;Topics&lt;/p&gt;;<br>}<br>export default Topics;</pre><p>5. Create a component Main.tsx which contains a routing path for our components.</p><pre>import { Routes, Route } from &#39;react-router-dom&#39;;</pre><pre>import Home from &#39;./components/Home&#39;;<br>import Topics from &#39;./components/Topics&#39;;<br>import Settings from &#39;./components/Settings&#39;;</pre><pre>const Main = () =&gt; {<br>return (         <br>    &lt;Routes&gt;<br>    &lt;Route path=&#39;/&#39; element={&lt;Home/&gt;} /&gt;<br>    &lt;Route path=&#39;/topics&#39; element={&lt;Topics/&gt;} /&gt;<br>    &lt;Route path=&#39;/settings&#39; element={&lt;Settings/&gt;} /&gt;<br>  &lt;/Routes&gt;<br>);<br>}<br>export default Main;</pre><p>6. Edit App.tsx</p><pre>import * as React from &#39;react&#39;;<br>import { Link} from &#39;react-router-dom&#39;;<br>import Main from &#39;./Main&#39;;</pre><pre>export default function App() {<br>  return (<br>    &lt;&gt;  <br>      &lt;div&gt;<br>        &lt;ul&gt;<br>          &lt;li&gt;&lt;Link to=&#39;/&#39;&gt;Home&lt;/Link&gt;&lt;/li&gt;<br>          &lt;li&gt;&lt;Link to=&#39;/topics&#39;&gt;Topics&lt;/Link&gt;&lt;/li&gt;<br>          &lt;li&gt;&lt;Link to=&#39;/settings&#39;&gt;Settings&lt;/Link&gt;&lt;/li&gt;<br>        &lt;/ul&gt;<br>        &lt;hr /&gt;<br>        &lt;Main /&gt;       <br>      &lt;/div&gt;   <br>    &lt;/&gt;<br>  )<br>}</pre><p>That’s the simple implementation of react-router v6. Run the app.</p><pre>$ npm start</pre><p><strong>Code splitting </strong>is one of the most compelling features of webpack. This feature allows you to split your code into various bundles which can then be loaded on demand or in parallel. It can be used to achieve smaller bundles and control resource load prioritization which, if used correctly, can have a major impact on load time.</p><p>Now, Build the above-created code to see the generated code. We will compare the build js files with the build files after implementing code-splitting.</p><pre>$ npm run build<br>$ ls build/static/js</pre><pre>//output <br><strong>main.1faed537.js<br>787.672c193d.chunk.js</strong><br>main.1faed537.js.map<br>787.672c193d.chunk.js.map<br>main.1faed537.js.LICENSE.txt</pre><p>For implementing code-splitting we will use React.lazy and React.Suspense component.</p><p><strong>React.lazy </strong>takes in a single argument, a function that invokes a dynamic import, and returns a regular React Component.</p><pre>const LazyHomeComponent = React.lazy(() =&gt; import(‘./Home’));</pre><p>What’s special about LazyHomeComponent is React won’t load it until it’s needed, when it’s rendered. That means, if we combine React.lazy with React Router, we can hold off on loading any component until a user visits a certain path.</p><p><strong>React.Suspense<br></strong>Since dynamic imports are asynchronous, there’s an unspecified amount of time the user needs to wait before the component is loaded, rendered, and the UI is displayed. To tell React what to show, you can use <strong>React.Suspense </strong>component passing it a fallback element. What’s nice about React.Suspense is that Suspense can take in multiple, lazily loaded components while still only rendering one fallback element.</p><p>7. Create a component Main2.tsx which contains routing path for our components with lazily loaded components</p><pre>import * as React from &#39;react&#39;;<br>import {Routes,Route } from &#39;react-router-dom&#39;</pre><pre>const Home = React.lazy(() =&gt; import(&#39;./components/Home&#39;));<br>const Topics = React.lazy(() =&gt; import(&#39;./components/Topics&#39;));<br>const Settings = React.lazy(() =&gt; import(&#39;./components/Settings&#39;));</pre><pre>const Loading = () =&gt; &lt;p&gt;Loading ...&lt;/p&gt;;</pre><pre>const Main2 = () =&gt; {<br>return (<br>    &lt;React.Suspense fallback={&lt;Loading /&gt;}&gt;<br>    &lt;Routes&gt;<br>      &lt;Route path=&#39;/&#39; element={&lt;Home/&gt;} /&gt;<br>      &lt;Route path=&#39;/topics&#39; element={&lt;Topics/&gt;} /&gt;<br>      &lt;Route path=&#39;/settings&#39; element={&lt;Settings/&gt;} /&gt;<br>    &lt;/Routes&gt;<br>  &lt;/React.Suspense&gt;<br>);<br>}<br>export default Main2;</pre><p>8. Edit App.tsx . Replace Main component by Main2 componenet.</p><pre>import * as React from &#39;react&#39;;<br>import { Link} from &#39;react-router-dom&#39;;<br>import Main2 from &#39;./Main2&#39;;</pre><pre>export default function App() {<br>  return (<br>    &lt;&gt;  <br>      &lt;div&gt;<br>        &lt;ul&gt;<br>          &lt;li&gt;&lt;Link to=&#39;/&#39;&gt;Home&lt;/Link&gt;&lt;/li&gt;<br>          &lt;li&gt;&lt;Link to=&#39;/topics&#39;&gt;Topics&lt;/Link&gt;&lt;/li&gt;<br>          &lt;li&gt;&lt;Link to=&#39;/settings&#39;&gt;Settings&lt;/Link&gt;&lt;/li&gt;<br>        &lt;/ul&gt;<br>        &lt;hr /&gt;<br>        &lt;Main2 /&gt;       <br>      &lt;/div&gt;   <br>    &lt;/&gt;<br>  )<br>}</pre><p>That’s it. You can run the application.</p><p>Try building the application to compare the final build js files.</p><pre>$ npm run build<br>$ ls build/static/js</pre><pre>//output</pre><pre>main.9d908c9c.js<br>787.672c193d.chunk.js<br><strong>444.07cb29fe.chunk.js<br>428.54364591.chunk.js<br>419.fac5c1c4.chunk.js</strong><br>main.9d908c9c.js.map<br>main.9d908c9c.js.LICENSE.txt<br>787.672c193d.chunk.js.map<br>444.07cb29fe.chunk.js.map<br>428.54364591.chunk.js.map<br>419.fac5c1c4.chunk.js.map</pre><p>Resources:</p><p><a href="https://ui.dev/react-router-code-splitting/">https://ui.dev/react-router-code-splitting/</a><br><a href="https://webpack.js.org/guides/code-splitting/">https://webpack.js.org/guides/code-splitting/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14d98e2cab79" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/implementing-react-router-v6-with-code-splitting-in-a-react-typescript-project-14d98e2cab79">Implementing React Router v6 with code splitting in a React Typescript project.</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[Implement Windows AD Authentication, Local DB Authorization with JWT Response Token using Spring…]]></title>
            <link>https://hpratap.medium.com/implement-windows-ad-authentication-local-db-authorization-with-jwt-response-token-using-spring-fad0be48fc88?source=rss-d79db9a9737a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fad0be48fc88</guid>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[custom-authentication]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Himanshu Pratap]]></dc:creator>
            <pubDate>Wed, 06 Oct 2021 07:09:31 GMT</pubDate>
            <atom:updated>2022-01-17T06:20:14.372Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implement Windows AD Authentication, Local DB Authorization with JWT Response Token using Spring Security</h3><p>In the previous article <a href="https://hpratap.medium.com/spring-security-custom-authentication-provider-4e36eddb7a8e">here</a>, i have implemented custom authentication such that</p><ul><li>Check if the user exist in local database user table and if the user exist, then authenticate it to external windows AD server.</li><li>Upon successful call to login API, a session was created on server and session id was returned in response header.</li><li>Subsequent call to other APIs were done with session id token.</li></ul><p>One of the issue faced in above implementation was that frontend ajax tools like axios, fetch and super agent were not able to extract session id token from response header. Refer <a href="https://stackoverflow.com/questions/69176405/authenticate-and-access-spring-security-protected-api-from-a-react-js-applicatio">this</a>.</p><p>So, instead of session based authentication , I have tried to implement stateless authentication using jwt token.</p><p>Steps are as follows:</p><ol><li><strong>Add following dependencies to pom.xml file.</strong></li></ol><pre>  &lt;dependency&gt;<br>   &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>   &lt;artifactId&gt;jjwt&lt;/artifactId&gt;<br>   &lt;version&gt;0.9.1&lt;/version&gt;<br>  &lt;/dependency&gt;</pre><pre>  &lt;dependency&gt;<br>   &lt;groupId&gt;javax.xml.bind&lt;/groupId&gt;<br>   &lt;artifactId&gt;jaxb-api&lt;/artifactId&gt;<br>  &lt;/dependency&gt;</pre><pre>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>  &lt;/dependency&gt;</pre><pre>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-configuration-processor&lt;/artifactId&gt;<br>  &lt;/dependency&gt;</pre><pre>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;<br>  &lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-security-ldap&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>2. <strong>Edit application.properties file.</strong> Add jwt seceret key and database connectivity details</p><pre>jwt.secret=mysecretkey12345</pre><pre>spring.jpa.show-sql = true<br>spring.jpa.generate-ddl=false<br>spring.sql.init.mode=never</pre><pre>#DATABASE CONFIGURATION </pre><pre>spring.datasource.url=jdbc:postgresql://localhost/pgdb<br>spring.datasource.username=pguser<br>spring.datasource.password=pguser<br>spring.datasource.driver-class-name=org.postgresql.Driver</pre><p><strong>3. Create User’s entity class , repo interface and service class</strong></p><pre><a href="http://twitter.com/Entity">@Entity</a><br>public class Myuser {<br>  <a href="http://twitter.com/Id">@Id</a><br>  private String username;<br>  private String authority;<br>  // constructor, getter &amp; setter <br>}<br></pre><pre><a href="http://twitter.com/Repository">@Repository</a><br>public interface MyuserRepo extends JpaRepository&lt;Myuser, String&gt; {}<br></pre><pre><a href="http://twitter.com/Service">@Service</a><br><a href="http://twitter.com/Transactional">@Transactional</a><br>public class MyuserService {<br> <br> private final MyuserRepo myuserRepo;</pre><pre>public MyuserService(MyuserRepo myuserRepo) {<br>  this.myuserRepo = myuserRepo;<br> }</pre><pre>public boolean findOne(String username) {<br>  Optional&lt;Myuser&gt; myuser = myuserRepo.findById(username);<br>  return myuser.isPresent();<br> }<br> <br> public Myuser loadUserByUsername(String username) throws UsernameNotFoundException {<br> return  myuserRepo.findById(username).get();  <br> }</pre><pre>public List&lt;Myuser&gt; findAll() {<br>  return myuserRepo.findAll();<br> }</pre><pre>}</pre><p><strong>4. Create following jwt related files</strong></p><p><strong>a. Create class for Authentication Request and Authentication Response</strong></p><pre>public class AuthenticationRequest implements Serializable {<br>private String username;<br>    private String password;<br>    //constructors and getter setter methods</pre><pre>}</pre><pre>public class AuthenticationResponse implements Serializable {<br>private final String jwt;<br>     //constructors and getter setter methods  <br>}</pre><p><strong>b. Create jwt util class</strong></p><pre><a href="http://twitter.com/Service">@Service</a><br>public class JwtUtil {</pre><pre><a href="http://twitter.com/Value">@Value</a>(&quot;${jwt.secret}&quot;) // read key from application.properties file<br>private String SECRET_KEY;</pre><pre>public String extractUsername(String token) {<br>        return extractClaim(token, Claims::getSubject);<br>    }</pre><pre>public Date extractExpiration(String token) {<br>        return extractClaim(token, Claims::getExpiration);<br>    }</pre><pre>public &lt;T&gt; T extractClaim(String token, Function&lt;Claims, T&gt; claimsResolver) {<br>        final Claims claims = extractAllClaims(token);<br>        return claimsResolver.apply(claims);<br>    }<br>    private Claims extractAllClaims(String token) {<br>        return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();<br>    }</pre><pre>private Boolean isTokenExpired(String token) {<br>        return extractExpiration(token).before(new Date());<br>    }</pre><pre>public String generateToken(Myuser userDetails) {<br>        Map&lt;String, Object&gt; claims = new HashMap&lt;&gt;();<br>        return createToken(claims, userDetails.getUsername());<br>    }</pre><pre>private String createToken(Map&lt;String, Object&gt; claims, String subject) {</pre><pre>return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))<br>                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))<br>                .signWith(SignatureAlgorithm.HS256, SECRET_KEY).compact();<br>    }</pre><pre>public Boolean validateToken(String token, Myuser userDetails) {<br>        final String username = extractUsername(token);<br>        return (username.equals(userDetails.getUsername()) &amp;&amp; !isTokenExpired(token));<br>    }<br>    <br>}</pre><p><strong>c. Create jwt filter class</strong></p><pre><a href="http://twitter.com/Component">@Component</a><br>public class JwtRequestFilter extends OncePerRequestFilter {</pre><pre><a href="http://twitter.com/Autowired">@Autowired</a><br>private MyuserService userDetailsService;</pre><pre><a href="http://twitter.com/Autowired">@Autowired</a><br>private JwtUtil jwtUtil;</pre><pre><a href="http://twitter.com/Override">@Override</a><br> protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)<br>   throws ServletException, IOException {</pre><pre>final String authorizationHeader = request.getHeader(&quot;Authorization&quot;);</pre><pre>String username = null;<br>String jwt = null;<br>List&lt;GrantedAuthority&gt; grantedAuthorities = new ArrayList&lt;&gt;();</pre><pre>if (authorizationHeader != null &amp;&amp; authorizationHeader.startsWith(&quot;Bearer &quot;)) {<br>   jwt = authorizationHeader.substring(7);<br>   username = jwtUtil.extractUsername(jwt);<br>  }</pre><pre>if (username != null &amp; SecurityContextHolder.getContext().getAuthentication() == null) {<br>   Myuser userDetails = this.userDetailsService.loadUserByUsername(username);</pre><pre>if (jwtUtil.validateToken(jwt, userDetails)) {<br>    <br>// get user authority from local db<br>grantedAuthorities.add(new SimpleGrantedAuthority(&quot;ROLE_&quot;.concat(userDetails.getAuthority()))); <br>    <br>UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(<br>      userDetails, null, grantedAuthorities);<br>    <br>usernamePasswordAuthenticationToken<br>      .setDetails( new WebAuthenticationDetailsSource().buildDetails(request));<br>    <br>    SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);<br>   }<br>  }</pre><pre>filterChain.doFilter(request, response);<br> }</pre><pre>}</pre><p><strong>d. Create JwtAuthenticationEntryPoint class</strong></p><pre>@Component<br>public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable<br>{<br>    @Override<br>    public void commence(HttpServletRequest request,<br>                         HttpServletResponse response,<br>                         AuthenticationException authException) throws IOException<br>    {<br>        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, &quot;Unauthorized&quot;);<br>    }<br>}</pre><p><strong>5. Create following config classes</strong></p><p><strong>a. CustomAuthenticationProvider class </strong>that checks for existence of user in local db, if present, check for authentication.</p><pre><a href="http://twitter.com/Component">@Component</a><br>public class CustomAuthenticationProvider implements AuthenticationProvider {<br> <br> private final MyuserService myuserService;<br>  <br> public CustomAuthenticationProvider(MyuserService myuserService) {<br>  super();<br>  this.myuserService = myuserService;<br> }</pre><pre><a href="http://twitter.com/Bean">@Bean</a><br>public AuthenticationProvider activeDirectoryLdapAuthenticationProvider(){<br>  <br>ActiveDirectoryLdapAuthenticationProvider activeDirectoryLdapAuthenticationProvider = new ActiveDirectoryLdapAuthenticationProvider(<br>    &quot;example.examplegroup.co.in&quot;,&quot;ldap://192.168.1.25&quot;);<br>  <br>// to parse AD failed credentails error message due to account - expiry,lock, credentialis - expiry,lock<br>  activeDirectoryLdapAuthenticationProvider.setConvertSubErrorCodesToExceptions(true); <br>  return activeDirectoryLdapAuthenticationProvider;<br> }</pre><pre><a href="http://twitter.com/Override">@Override</a><br> public Authentication authenticate(Authentication authentication) throws AuthenticationException {<br>       <br>  String username = authentication.getName();<br>  boolean ifPresent = myuserService.findOne(username);<br>        <br>  if(ifPresent) {<br>     return activeDirectoryLdapAuthenticationProvider().authenticate(authentication);<br>        }<br>        else throw new UsernameNotFoundException(&quot;User not found.&quot;);<br>    }</pre><pre><a href="http://twitter.com/Override">@Override</a><br> public boolean supports(Class&lt;?&gt; authentication) {<br>   return authentication.equals(UsernamePasswordAuthenticationToken.class);<br> }</pre><pre>}</pre><p><strong>b. Web security Configuration class</strong></p><pre><a href="http://twitter.com/Configuration">@Configuration</a><br>public class WebSecurityConfig extends WebSecurityConfigurerAdapter{</pre><pre>private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;<br> private JwtRequestFilter jwtRequestFilter;<br> private CustomAuthenticationProvider customAuthenticationProvider;</pre><pre>public WebSecurityConfig(JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint, JwtRequestFilter jwtRequestFilter,<br>   CustomAuthenticationProvider customAuthenticationProvider) {<br>  super();<br>  this.jwtAuthenticationEntryPoint = jwtAuthenticationEntryPoint;<br>  this.jwtRequestFilter = jwtRequestFilter;<br>  this.customAuthenticationProvider = customAuthenticationProvider;<br> }<br> <br><a href="http://twitter.com/Override">@Override</a><br>protected void configure(AuthenticationManagerBuilder auth) throws Exception {<br>         auth.authenticationProvider(customAuthenticationProvider);<br>     }<br>    <br>    <br><a href="http://twitter.com/Override">@Override</a><br>protected void configure(HttpSecurity http) throws Exception {<br>   http<br>    .cors().and().csrf().disable()<br>    .headers().frameOptions().deny()<br>    .and()<br>    .authorizeRequests()<br>    .antMatchers(&quot;/api/authenticate&quot;).permitAll()<br>    .anyRequest().authenticated()<br>    .and()   .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)<br>    .and()<br>    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);<br>  <br>   http.addFilterBefore(jwtRequestFilter,UsernamePasswordAuthenticationFilter.class);<br>    <br>  }</pre><pre><a href="http://twitter.com/Bean">@Bean</a><br><a href="http://twitter.com/Override">@Override</a><br>public AuthenticationManager authenticationManagerBean() throws Exception {<br>   return super.authenticationManagerBean();<br>  }<br>   <br>}</pre><p><strong>c. Create cors configuration class</strong></p><pre><a href="http://twitter.com/Configuration">@Configuration</a><br>public class WebMvcConfig implements WebMvcConfigurer {</pre><pre>private final long MAX_AGE_SECS = 3600;</pre><pre><a href="http://twitter.com/Override">@Override</a><br>    public void addCorsMappings(CorsRegistry registry) {<br>        registry.addMapping(&quot;/**&quot;)<br>                .allowedOrigins(&quot;<a href="http://myserver2:3000/">http://myserver2:3000</a>&quot;, &quot;<a href="http://myserver3:3000/">http://myserver3:3000</a>&quot;)<br>                .allowedMethods(&quot;GET&quot;, &quot;POST&quot;)<br>                .maxAge(MAX_AGE_SECS)<br>                .allowCredentials(true);<br>    }<br>}</pre><p><strong>6. Controller class for following REST APIs</strong></p><ul><li>login api that performs authentication and responds with jwt token if successful.</li><li>API thats check returns “hello world” if the associated jwt token in payload is valid.</li></ul><pre><a href="http://twitter.com/RestController">@RestController</a><br><a href="http://twitter.com/RequestMapping">@RequestMapping</a>(&quot;/api&quot;)<br>public class AuthenticationResource {<br> <br> private final AuthenticationManager authenticationManager;<br> private final JwtUtil jwtTokenUtil;<br> private final MyuserService myuserService;<br> <br> public AuthenticationResource(AuthenticationManager authenticationManager, JwtUtil jwtTokenUtil,<br>   MyuserService myuserService) {<br>  super();<br>  this.authenticationManager = authenticationManager;<br>  this.jwtTokenUtil = jwtTokenUtil;<br>  this.myuserService = myuserService;<br> }</pre><pre><a href="http://twitter.com/PostMapping">@PostMapping</a>(&quot;/authenticate&quot;)<br>public ResponseEntity&lt;?&gt; createAuthenticationToken(<a href="http://twitter.com/RequestBody">@RequestBody</a> AuthenticationRequest authenticationRequest) throws Exception {</pre><pre>try {<br>   authenticationManager.authenticate(<br>     new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), authenticationRequest.getPassword())<br>   );<br>  }<br>  catch (BadCredentialsException e) {<br>   throw new Exception(&quot;Incorrect username or password&quot;, e);<br>  }</pre><pre>final Myuser userDetails = myuserService.loadUserByUsername(authenticationRequest.getUsername());</pre><pre>final String jwt = jwtTokenUtil.generateToken(userDetails);<br>return ResponseEntity.ok(new AuthenticationResponse(jwt));<br>}</pre><pre><a href="http://twitter.com/GetMapping">@GetMapping</a>(&quot;/hello&quot;)<br> public String sayHello(){<br>  return &quot;Hello World&quot;;<br>}</pre><p>Thats it on server side.</p><p>On React JS fronted side,</p><ul><li><strong>Make authentication call as follows</strong></li></ul><pre>const onLogin= () =&gt; {</pre><pre>onst AUTH_TOKEN_KEY = &#39;authenticationToken&#39;;<br>const loginUrl = &quot;http://myserver1:8080/api/authenticate&quot;;<br>axios.post(loginUrl, { username, password })<br>     .then(res =&gt; {<br>            const bearerToken = res.data.jwt;<br>            if (bearerToken) {<br>            localStorage.setItem(AUTH_TOKEN_KEY, bearerToken);<br>            setBearerId(bearerToken);<br>            setIsAuthenticated(true);<br>           } <br>         })<br>    .catch(err =&gt; console.log(err.message));<br>}</pre><ul><li><strong>Make endpoint api call with bearer id as follows</strong></li></ul><pre>const endpointUrl = &#39;http://myserver1:8080/api/hello&#39;;</pre><pre>const authHeader = &quot;Bearer &quot;+ localStorage.getItem(&#39;authenticationToken&#39;);</pre><pre>axios<br>  .get(endpointUrl,{ headers: { &#39;Authorization&#39;: authHeader } } )<br>  .then(res =&gt; console.log(res.data))<br>  .catch(err =&gt; console.log(err.message));</pre><pre>}</pre><p>Resources:</p><ul><li><a href="https://www.youtube.com/watch?v=X80nJ5T7YpE">JavaBrains tutorial vieo</a></li><li><a href="https://www.devcrutch.com/2020/09/15/how-to-create-jwt-token-using-ldap-and-spring-boot-part-1/">https://www.devcrutch.com/2020/09/15/how-to-create-jwt-token-using-ldap-and-spring-boot-part-1/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fad0be48fc88" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>