<?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 Ken Foss on Medium]]></title>
        <description><![CDATA[Stories by Ken Foss on Medium]]></description>
        <link>https://medium.com/@kenfoss0715?source=rss-6d784533b7e8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*T33fO1BuE0NUD23gdTNSVQ@2x.jpeg</url>
            <title>Stories by Ken Foss on Medium</title>
            <link>https://medium.com/@kenfoss0715?source=rss-6d784533b7e8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:46:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kenfoss0715/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[Keeping Your Microservices in Sync with Apache Kafka and Friends]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://levelup.gitconnected.com/keeping-your-microservices-in-sync-with-apache-kafka-and-friends-82c502575828?source=rss-6d784533b7e8------2"><img src="https://cdn-images-1.medium.com/max/1024/1*cu4DAyQ7N8l1_bUEY67dNQ.jpeg" width="1024"></a></p><p class="medium-feed-snippet">A Comprehensive Solution to Kafka Topic Producers and Consumers with a Unified Avro Schema Repository</p><p class="medium-feed-link"><a href="https://levelup.gitconnected.com/keeping-your-microservices-in-sync-with-apache-kafka-and-friends-82c502575828?source=rss-6d784533b7e8------2">Continue reading on Level Up Coding »</a></p></div>]]></description>
            <link>https://levelup.gitconnected.com/keeping-your-microservices-in-sync-with-apache-kafka-and-friends-82c502575828?source=rss-6d784533b7e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/82c502575828</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Ken Foss]]></dc:creator>
            <pubDate>Thu, 22 Aug 2024 01:56:41 GMT</pubDate>
            <atom:updated>2024-08-22T01:56:41.332Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Docker Compose Setup for a MicroServices Architecture]]></title>
            <link>https://levelup.gitconnected.com/docker-compose-setup-for-a-microservices-architecture-f47902dadcae?source=rss-6d784533b7e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f47902dadcae</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Ken Foss]]></dc:creator>
            <pubDate>Tue, 09 Jul 2024 13:21:35 GMT</pubDate>
            <atom:updated>2024-07-09T15:34:19.005Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deploy and Integrate Multiple Services on a Single Host in One Click</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LNxg0VVB42pDr16RfMsniQ.jpeg" /></figure><p>So, you have a complex application architecture past the simple React app front-end. Perhaps a back-end or even a microservices architecture with multiple back-end services. To test such a system locally can become a challenge, these services are likely deployed in a Kubernetes cluster or the like in production. With docker we can create a local setup to simulate such a distribution. This solution aims to provide a “one-click” setup that will use a docker-compose configuration to create a complex local testing infrastructure. With the use of an nginx proxy, this could even be used to host multiple services on the same server and serve them via port 80 (the port that is typically used for HTTP protocol), deploying a complex website on a single node.</p><h4>Setting Up to Follow Along</h4><p>To exemplify the use of docker compose in hosting a full-stack application on a single port I will be implementing a google sign-in application from a <a href="https://medium.com/javarevisited/lets-get-authenticated-google-sign-in-d4f4d7606ba3"><strong>previous post</strong></a>. The code for this application can be found in the given git repository, but for more on the composition of this application refer to the <a href="https://medium.com/javarevisited/lets-get-authenticated-google-sign-in-d4f4d7606ba3"><strong>original post</strong></a>.</p><p>Now, please clone this repository to follow along. You will need Node.js and Java installed on your system to properly implement it. Note a SQL install is not necessary as the docker-compose will take care of this.</p><p><a href="https://github.com/KenFoss/nginx-proxy-docker-demo">GitHub - KenFoss/nginx-proxy-docker-demo</a></p><p>If you just wish for a simple demo and do not wish for a fully functional application, please skip to the <a href="#2614"><strong>next section</strong></a>. You will still be able to reach the front-end React application via localhost:8080 and the back-end Spring Boot application via localhost:8080/api, but they won’t interact as intended.</p><p>There is a bit more setup for this application to work in its entirety. We need to configure a google OAuth consent screen, the process for which is better outlined in <a href="https://medium.com/javarevisited/lets-get-authenticated-google-sign-in-d4f4d7606ba3"><strong>my article on google OAuth</strong>.</a> In short, we can use this same consent screen configuration. But since we are now hosting the application on port 8080, the authorized JavaScript origin and redirect URI need to be updated like so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LRM-cxLhvDFKagEZtDP_Mw.png" /></figure><h3>The Bits and Pieces</h3><p>The application in question will require a myriad of support configurations, from an internal docker network to an instance of MySQL. The beauty of using docker here is the setup can be spun up with a single command, and we will ensure data resistance through mounted volumes. Once the application is first spun up, you can restart from docker desktop and never need to open a terminal.</p><h4>Networking and Supporting Cast</h4><p>The first component of this docker-compose configuration we will explore is perhaps the most important. This is the docker network, simply referred to as my-network in this implementation. This will be used by connected services to allow communication within the docker infrastructure. You can see it configured here and you will see it referenced in all the services of this docker-compose.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf0aebe92f8b9aee666c58793ff2cc2f/href">https://medium.com/media/cf0aebe92f8b9aee666c58793ff2cc2f/href</a></iframe><p>We use a bridge network driver, which is used to connect containers on the same host. Now, this will allow us to proxy requests with nginx via the given names of the services</p><p>We will also need a SQL instance to support our applications data. We can create a SQL service using the default MySQL image to this effect.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6c2230c1ca550c5853d59a0b6527d9d/href">https://medium.com/media/c6c2230c1ca550c5853d59a0b6527d9d/href</a></iframe><p>You will note we are also setting the root password here, and hosting on the SQL default port of 3306. I want to draw special attention to the “volumes” here. This is using the directory ./docker-conf/mysql_data to persist data locally, ensuring data remains intact even when the container is restarted or remade (in the same directory).</p><p>Once this container has been started, you can connect to the SQL instance with a tool like DBeaver (as pictured below) with the following configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*Yd4q1ripOiXBbXF2ZTfKSA.png" /></figure><p>Now, to support the application you will need a GoogleOauth database with a google_user table that should contain two columns of varchar(255) named as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*85PYeCVi4qrdJCmQv9prKQ.png" /></figure><p>Every great production needs a supporting cast! With ours in step, let’s move on to the real stars of the show.</p><h4>The Applications</h4><p>To serve these applications seen in the demo_backend and demo_frontend folders, we will need to create base images. We can do this with dockerfiles built directly into the docker-compose. My goal is to press a button and serve this application, I don’t want to build images to feed into this docker-compose configuration. Let’s demonstrate this with the back-end service first:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfc2d57372400b4fe81664aade25bae7/href">https://medium.com/media/dfc2d57372400b4fe81664aade25bae7/href</a></iframe><p>There are a few important aspects of this configuration. You will notice a callback to the previous section, the network. The applications need to be thrown on the network, then the container_name can be used to reference the applications in the context of the network, but we will touch on this more later. Then, there is the build and volumes sections. We mount the SPRING_DOCKERFILE so it can then be used by the build configuration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99041a133346db7af55330c898d02b4f/href">https://medium.com/media/99041a133346db7af55330c898d02b4f/href</a></iframe><p>Here we will build the application for use in the docker-compose configuration. Any time we rebuild this container it will reference this dockerfile as a framework to build the image it will serve.</p><p>The React application configuration will look almost identical to this Spring service. The only difference is the port referenced for serving the application (3000) and the use of the REACT_DOCKERFILE.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5c66b1bf8bd8ac786d2dcc611db71a3/href">https://medium.com/media/b5c66b1bf8bd8ac786d2dcc611db71a3/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1784c9d04f4b272e3238329b3e2bcc0/href">https://medium.com/media/d1784c9d04f4b272e3238329b3e2bcc0/href</a></iframe><h4>The Glue — nginx Proxy</h4><p>To tie this all together we will configure an nginx service that will proxy traffic on port 8080 to the two applications via port 3000 and 8090. The service configuration is relatively simple.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf225f52e0f590548ed188f977679447/href">https://medium.com/media/cf225f52e0f590548ed188f977679447/href</a></iframe><p>We are configuring the server to use port 8080, and we will link ./nginx.conf (the server configuration file) to the container so it can be used as the default.conf file. Now, we refer to the configuration file to proxy traffic to our services.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49db84d0ef8568fb67e10835877bfaa9/href">https://medium.com/media/49db84d0ef8568fb67e10835877bfaa9/href</a></iframe><p>You will notice the container names can be used here to reference our services as we have configured them to use the same docker network. Should there be more apps on the network we would proxy traffic around to various ports in the same way. Here nginx is listening on 8080 for local testing, but this could be used to deploy a full stack application on a single server to port 80.</p><h3>The Application in Action</h3><p>Let’s start this server up! Navigate to the project and run the following command:</p><p>docker-compose up</p><p>Now, should the application be configured correctly we will see a full-stack sign in application hosted to port 8080. This application will make calls to the back-end without specifying a domain (such as http://localhost) as it on the same domain. See this method which calls to the /api/hello endpoint in the Dash.js component as an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/688d35051f4bacecfb89328ffe3f7960/href">https://medium.com/media/688d35051f4bacecfb89328ffe3f7960/href</a></iframe><p>Now we can demonstrate this application as fully functional by simply navigating to http://localhost:8080 and see we are routed to the react application that is originally hosted on port 3000!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YXX5j0KuX7iUtNJSasQREQ.png" /></figure><p>We will also see successful requests to the back-end should you have taken the proper steps given in <a href="#ab2a"><strong>the setup</strong></a><strong>.</strong> If not, open up a tool such as postman and make requests to the back-end. You may receive a 403 unauthorized response, but this is expected. If you have reached the back-end the setup is working.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.loom.com%2Fembed%2Fe11885cf8e3a453b87a21dd3ba6eae96&amp;display_name=Loom&amp;url=https%3A%2F%2Fwww.loom.com%2Fshare%2Fe11885cf8e3a453b87a21dd3ba6eae96%3Fsid%3De65d59a2-be25-49ee-86b7-cd4e010bc22f&amp;image=https%3A%2F%2Fcdn.loom.com%2Fsessions%2Fthumbnails%2Fe11885cf8e3a453b87a21dd3ba6eae96-00001.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=loom" width="1280" height="960" frameborder="0" scrolling="no"><a href="https://medium.com/media/b984985bddccb990922dea53a691308a/href">https://medium.com/media/b984985bddccb990922dea53a691308a/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f47902dadcae" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/docker-compose-setup-for-a-microservices-architecture-f47902dadcae">Docker Compose Setup for a MicroServices Architecture</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Committing Your Images to Git!]]></title>
            <link>https://levelup.gitconnected.com/stop-committing-your-images-to-git-4f5148416c55?source=rss-6d784533b7e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f5148416c55</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Ken Foss]]></dc:creator>
            <pubDate>Thu, 13 Jun 2024 20:25:52 GMT</pubDate>
            <atom:updated>2024-06-13T20:25:52.592Z</atom:updated>
            <content:encoded><![CDATA[<p>Hosting Static Documents on AWS S3 behind a CloudFront Distribution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zsWUwl_GXYHv4FQjN39t7Q.jpeg" /></figure><p>Static file storage was one of the first trials I faced in web development. With no professional experience I was actually committing images to my git repositories! I quickly learned this was malpractice, and I still went through phases on the “proper” setup. I began storing images in an S3 bucket, certainly an improvement and often enough with my local following (we’re still growing). Now, if your audience starts to span out and even become multi-national this distribution will become extremely slow the farther clients are from the data center where the S3 bucket lives. My solution to this is CloudFront, a content delivery network (CDN) service provided by AWS. It’s primary function to deliver content, such as web pages, videos, images and other assets to global users with low latency and high data transfer speeds.</p><h3>Configuring Your AWS Console</h3><p>I like to imagine many readers are new to development, so we’re going to assume you don’t have AWS CLI configured locally. If you do skip this section.</p><h4>Play-By-Play</h4><p>We need to configure the console to associate with an AWS user. Navigate to the Identity and Access Management portal in AWS (IAM) and create a user. You will be prompted to <strong>set permissions</strong>, ensure this user has at least full S3 access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fpBYLXfIVxz8gKucpneqaw.png" /><figcaption>AWS Console, User configuration</figcaption></figure><p>You now need an AWS access key, go to your user and select <strong>security credentials &gt; Access keys &gt; Create access key. </strong>In the following menu give the access key a use case for interacting with AWS via your CLI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CejTU5-PBtO9Sk3unup3Vg.png" /><figcaption>Create IAM User Access Key</figcaption></figure><p>You now have a key and secret to configure the user locally. Make sure to download the .csv or save this information in some other manner before you close this page. Once it is closed this secret access key will never be accessible again. Now we are ready to configure a profile as such:</p><p>To create a default profile:</p><p>aws configure</p><p>To set an additional profile:</p><p>aws configure --profile PROFILE_NAME</p><p>To set the profile:</p><p>export AWS_PROFILE = default</p><p>or</p><p>export AWS_PROFILE=PROFILE_NAME</p><p>At any time you can see all profiles you have configured with the command:</p><p>aws configure list-profiles</p><p>Our console is configured! Now the fun starts, and a world of AWS CLI opens up to you.</p><h3>The Image Server</h3><p>If you want fast access to your images and other static content wherever your users may be, you will want to configure a CloudFront distribution to throw up in front of this S3 instance. We want our data to be cached at edge locations, the less distance between the data and the user, the smoother their reaction.</p><h4>Creating the S3 Bucket</h4><p>CloudFront will request a origin domain, any configured S3 buckets will be available here. So this is where we will start. Navigate to S3 in the AWS developer console and select the yellow <strong>Create bucket</strong> button. For now, we will leave the default settings and name the bucket.</p><p>Upload a test image to the bucket by moving it to your directory of choice (the current directory in the following example) with the following command:</p><p>aws s3 cp ./demo.jpg s3://demo-bucket-624</p><h4>Creating the CloudFront Instance</h4><p>Navigate to the CloudFront page in the AWS console and create a new distribution. We will be given the domain of our S3 bucket as an optional origin domain, select it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*HnMgruLO5WK4KpumHaHmzw.png" /></figure><p>Then, we want to configure origin access control, this is a critical step in securing the content delivery setup. Once this is configured our s3 objects will only be available through our CloudFront Distribution. Configure <strong>origin access</strong> as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*GFHBjoJyxo4CVdroQtMMXg.png" /></figure><p>Now, select <strong>Create new OAC</strong> and configure the basic options for the OAC. On this next screen simply click <strong>Create</strong>. Later, we will need to configure the S3 bucket policy to allow for this control to take effect. But we will leave this alone for now.</p><p>We will also configure the Web Application Firewall (WAF). Leave monitor mode off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*lzeQvlRd65-rHvs3NxUpeQ.png" /></figure><p>And with that we are done! Scroll to the bottom and select <strong>Create distribution</strong> and our instance will be configured.</p><h4>Back to S3</h4><p>We now need to update the S3 policy to support allow the CloudFront distribution access to our bucket. Navigate to the S<strong>3 bucket</strong> <strong>&gt; permissions</strong> and edit the bucket policy. It will resemble this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ea88890ac1098dd4587c9b78b2bc9ce/href">https://medium.com/media/1ea88890ac1098dd4587c9b78b2bc9ce/href</a></iframe><p>However, the “Aws:SourceArn” needs to be configured for the specific CloudFront distribution. The ARN for the distribution can be found back in the CloudFront main view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xrDFQKjMSLLOjTeJCaS5hQ.jpeg" /></figure><h4>Admiring Your Work!</h4><p>It’s time to sit back and marvel at your work. Navigate to the CloudFront distribution domain name, you will find it next to the ARN. I have called my image demo.jpg, so I navigate to https://&lt;DISTRIBUTION_DOMAIN_NAME&gt;/demo.jpg.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VyKN6YdOUc0k5TdKgajhqw.png" /></figure><p>If your like me, just knowing that this configuration will save your images to edge locations world wide is pretty cool.</p><p>Now unfortunately the work is not exactly done, unless you want just about anyone to have access to this URL and potentially drive up your expenditures. Try navigating to this link on another device… yep. Assuming you want to restrict access to your public IP for testing, let’s keep this going. This can be set to the IP of your server when in production.</p><h4>Configuring a Web Application Firewall (WAF)</h4><p>Navigate to the AWS <strong>WAF &amp; Shield</strong> service and click the IP sets option in the left-hand menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05GSwhihFbNoZoBlDpU1pg.png" /></figure><p>Then create an IP set. This is in CIDR notation which requires a prefix length that specifies how many bits of the 32 bit IP address are used for the network portion. For simplicity sake, just know /32 is what we need here for a single IP address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*ae_fc1RQfet4m21DUqvYEA.png" /></figure><p>Now, since we elected to configure a WAF in <a href="#7374">the previous section</a> there is already a Web ACL for this distribution. The name of this ACL will begin with <strong>CreatedByCloudFront</strong>. Select this to begin. Once here navigate to the <strong>Rules</strong> tab and elect to <strong>Add my own rules and rule groups</strong>. We can use the IP set to allow access to this CloudFront instance from only the IPs in this list<strong>.</strong> Select the IP set you just created. Make sure to select the <strong>Allow</strong> action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*TEXcPe3u_MYziK8OBehDCA.png" /></figure><p>Now if you try to access this image again on your phone, you will notice it is still accessible. This is because the default action for requests that do not match rules is to <strong>allow them</strong>. We want more control, so we are going to set the default to blocking, navigate to the <strong>Rules</strong> tab of the Web ACL, and locate this section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9DQLcz9tmquUDjqz7dcuOg.png" /></figure><p>Click <strong>edit</strong> and change the action to deny. Now you are only allowing access from IP configured in the IP set <a href="#f4d7">above</a>. With this, turn off the WiFi on your phone (else your public IP will be no different then this device) and navigate to the test image you added to the S3 bucket. Make sure to clear your cache, otherwise your phone will not need to re-attempt the request. You will now be denied! However, on the given IP you will still be allowed access.</p><p>With this in your arsenal you are ready to create some quality simple front-ends. Images take up a lot of space, best to keep them off your web apps server or in version control. Have fun creating!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f5148416c55" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/stop-committing-your-images-to-git-4f5148416c55">Stop Committing Your Images to Git!</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Get Authenticated — Google Sign In]]></title>
            <link>https://medium.com/javarevisited/lets-get-authenticated-google-sign-in-d4f4d7606ba3?source=rss-6d784533b7e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4f4d7606ba3</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Ken Foss]]></dc:creator>
            <pubDate>Fri, 07 Jun 2024 15:42:59 GMT</pubDate>
            <atom:updated>2024-06-07T18:49:19.497Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s Get Authenticated — Google Sign In</h3><h4>A Full Stack Solution to Google Sign In with React.js and Spring Boot</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OxeKGQwJWShAhykk1qznlQ.jpeg" /></figure><p>As the web has integrated into every aspect of human existence, so have authentication and the all-too-familiar greeting of the sign-in screen. In recent years, a far more convenient sing-in method has surged in popularity for ease over storing or remembering a myriad of passwords. This would be OAuth and OpenID sign in. While OpenID sign was introduced as a simple way to get up and running with sign-in methods such as Google, OAuth provides much more functionality. OAuth will allow sharing of information across applications pending user agreement. Provided the extra functionality of OAuth, our focus will remain here.</p><p>A major obstacle to the start of any application is secure sign-on, with persistence across windows and even when browsers are closed and re-opened. This demo application uses a Spring Boot back-end, storing user information in a SQL database, to this effect. User “session” information is passed via JSON web tokens that will persist up to an hour in the client-side local storage.</p><h4>Following Along</h4><p>I highly recommend following along with the code, all can be found in the repository below. There will be a <a href="#98bc">demo</a> of the flow from the perspective of our React.js front-end provided, and some of the supporting code both front-end and back-end.</p><p>From the demo_backend folder in the git project below, run the following command to start the Spring Boot Application:</p><p>./mvnw clean install spring-boot:run</p><p>Then, from the demo_frontend directory, start the React.js appliction with the following command:</p><p>npm start</p><p>Note, you will need an instance of SQL running locally to connect to. If you do not have your own setup for this, I recommend referring to my post on starting <a href="https://medium.com/devops-dev/local-web-development-setup-with-docker-c666905223c3">a local testing instance with docker</a>.</p><p><a href="https://github.com/KenFoss/Oauth2_Google_Demo">GitHub - KenFoss/Oauth2_Google_Demo: Demo for blog post</a></p><h3>The Front-End</h3><p>It is standard for an application to be divided into (at least) two entities. These are the front-end or client-side application, and the back-end. This post is meant to help produce an authentication server that will support this architecture. The front-end is a user facing JavaScript application (made with the React.js in our case), making it the obvious choice to direct users to the google sign-in screen.</p><p>So this is where we will start, please view the demo_frontend folder in the <a href="#6329">given git repository</a> to follow along with this flow.</p><h4>Configuring Google APIs &amp; Services — The Consent Screen</h4><p>When creating the project, we must also create a consent screen for our app. We can do this from the <a href="https://console.cloud.google.com/">google development console,</a> if you have not already you must create a new project via the highlighted button of the image below. When you navigate to the “OAuth consent screen” tab you will be met with a prompt to generate said consent screen. First, we will be opening the user type to External (open to all google users), though we will have to configure test users before the app is launched. You will be met with a page of App information. This will customize various aspects of the consent screen users will be met with. It is not important for this demo, but customize it to adjust what your users are met with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vy70_Pxt_m0QE61_LTM6zw.png" /><figcaption>Google App Registration — OAuth Consent screen</figcaption></figure><p>Google OAuth allows you to any of a users information stored with google. However, we want to avoid saturation of the response with irrelevant information. So, we will configure only the scopes we need. These are userinfo.email, openid, and userinfo.profile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pu6ZPOaBRq8N-B0Jaf7z9Q.png" /><figcaption>Google App Registration — Scope Configuration</figcaption></figure><p>Lastly, we are met with an option to specify test users. I configured a personal/test email address specifically for this purpose. I recommend you do the same.</p><h4>Configuring Google APIs &amp; Services — The Credentials</h4><p>We will now be making an OAuth client ID to support the login functionality. Select the new project and Create the new client id from the “Credentials” tab of “APIs &amp; Services”, you will be asked for an Application Type which is “Web application” in our case. Name the project as you please.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*W4aJML0orpLHFuLE-I7-8Q.png" /><figcaption>Google App Registration — Credentials</figcaption></figure><p>The application will request an id token from the JavaScript Origin, and receive it via the authorized redirect URI. In our configuration the “Dashboard” page will receive this token and facilitate passing it to the back-end for verification and create an authenticated session within the context of our application. So, in our case the JavaScript origin will be <a href="http://127.0.0.1:3000/">http://127.0.0.1:3000</a>, and the redirect <a href="http://localhost:3000/dashboard">http://localhost:3000/dashboard,</a> as you can see pictured in the <a href="#50c6">next section</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i7ngdzVPPuquG4cg3LhzIQ.png" /><figcaption>Google OAuth Flow</figcaption></figure><h4>The JavaScript Front-End</h4><p>Now the fun part, no more configuration… for now. I recommend cloning the repository given in the <a href="#6329">following along </a>section, if you have not already. Here you will notice the entry page is the Login component, which can be found in src/pages/Login.js. Here we route the user to the google consent screen, to do this we will need the client id which can be found here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0kCdrDukS6TFeC-kyb84bg.png" /></figure><p>With this ID, the authorized redirect URI and scopes, we make the call to route our user to the google consent screen.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/709b106a4a840d3681f0e870456160d9/href">https://medium.com/media/709b106a4a840d3681f0e870456160d9/href</a></iframe><p>you will notice there is also a response_type. There are a few options here, the id_token is a JSON Web Token (JWT) that contains claims about the authenticated user. We will use it to get google information to generate our users on the back-end.</p><p>Now if you refer back to the flow given in the <a href="#9d33"><strong>credential configuration section</strong></a><strong>, </strong>you will see the token is returned to the /dashboard page of this site which is found in our /src/pages/Dash.js file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f00ff14296a699930d2a6cd06ced798/href">https://medium.com/media/4f00ff14296a699930d2a6cd06ced798/href</a></iframe><p>This useEffect() hook will run on page load. The id_token is actually returned to this page in the URL, you will see it parsed on lines 11–17 and stored in a JavaScript variable to later be passed to our Back-End sign-in/account creation endpoint.</p><p>Something of importance to note here is the use of the localStorage API to store the authentication JWT. This is a recommended practice from the <a href="https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html#the-localstorage-api">OWASP session management cheatsheet</a> which recommends localStorage for persisting sessions across windows or tabs. This will allow our users to login and be authenticated for the life of their JWT without needing to sign-in whenever they open our page (or re-open the browser).</p><p>There is also a isAuthenticated() endpoint that is not expanded upon. This is because this method reaches out to our back-end and passes along the DemoAuthToken to ensure it’s validity. Should this token be expired, authenticated will remain set to false and we will attempt to fetch a new token. To see exactly how it is implemented, I invite you to inspect the code yourself.</p><p>Now to the meat and potatoes, lets write some back-end code.</p><h3>The Back-End</h3><p>Our back-end will be configured in Spring Boot. To set up the project refer to the pom.xml in the demo_backend directory of the git repository found in the <a href="#6329">following along section</a>. We will be receiving the google id token to the /oauth/google endpoint. From here a user will be registered to a sql table, and a JSON web token built to represent the user in the context of our application.</p><h4>Creating Users in Application context</h4><p>The endpoint in our spring application will be a POST endpoint, and it will facilitate creating user credentials for our users. As long as the sign-in is attempted with a valid google ID token, a user will be signed in. In our implementation, if a user has not yet been created in the application context their user will be automatically generated. These users will be generated in the “google_user” SQL table. See the com.auth.demo.jpa package of the git project “demo_backend” folder for the configuration files to use this table as a JPA repository. The google_user table will have only and “email” and “google_id” column for now, but adding columns to store user information from payment status to application settings should be a simple addition.</p><p>Past the creation of a simple GoogleUser model and GoogleUserDTO (Data Transfer Object), we will need a JpaRepository for our GoogleUser model. This allows us to query based on naming convention, and we can create a query to find the user by their google ID. This will look like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9a4d02f367a84772cc7058b7a88c417/href">https://medium.com/media/f9a4d02f367a84772cc7058b7a88c417/href</a></iframe><p>Off naming conventions, we can now use the findByGoogleId(String googleId) to find users matching a specific google id in the google_user table.</p><p>We will need to configure the application to connect to our SQL repository, in my case I am running it locally. Use this configuration in your application.yml, the endpoint in the url should match your Database name, in this case “GoogleOauth”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc578073687bdd519cade66f8843e3e3/href">https://medium.com/media/cc578073687bdd519cade66f8843e3e3/href</a></iframe><h4>Signing In</h4><p>Users will sign in with google on the front-end, which will reach out to the /oauth2/google endpoint to register users in context of the application back-end. Here the GoogleIdTokenVerifier is used, which relies on access to the google Id we configured <a href="#50c6">earlier</a>. This will be configured in our application context with the GoogleConfig configuration property bean and the corresponding configuration in the application.yml.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ead53a901ce1ce589c43fb587a6c289/href">https://medium.com/media/0ead53a901ce1ce589c43fb587a6c289/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54a7816b6b3ea4fb9525da7b00015f13/href">https://medium.com/media/54a7816b6b3ea4fb9525da7b00015f13/href</a></iframe><p>With this, we can build a GoogleIdTokenVerifier and generate users in our google_user table when appropriate, or find pre-existing users. If the token is verified with the token verifier, it will return a GoogleIdToken and we can get the requested google account information from here (user id, email). With this we generate a JWT token to authenticate the user in the context of this application and send it back to the front-end to be used in future requests.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe7d943fed83a01594161443b83a6940/href">https://medium.com/media/fe7d943fed83a01594161443b83a6940/href</a></iframe><h4>Security Configuration</h4><p>The crux of our OAuth server revolves around the security filter settings. For our purposes we will disable CSRF for ease of testing, though this is not recommended in production. If you are going to implement CSRF with this setup I invite you to read my post on <a href="https://medium.com/devops-dev/dive-into-csrf-defense-real-attack-demonstrations-safeguards-with-spring-security-69c22b25c322">CSRF with Spring Security</a>, for a comprehensive view of the topic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17c982216db2508a610197d0cb856bcd/href">https://medium.com/media/17c982216db2508a610197d0cb856bcd/href</a></iframe><p>We want to ensure accessibility to the login endpoint before a user is authenticated. To do so we can use the permitAll() method on our request matcher on the endpoint. We will be requiring authentication for all other endpoints.</p><p>Note the jwtAuthenticationFilter, this filter will set the authentication status so that a user can clear the .authenticated() endpoints based on the validity of an authorization header they will pass with their request. This header consists of the JWT created on login to persist the user’s authentication status with the application.</p><h4>JSON Web Token Generation and Filter</h4><p>The gears that make the JWT based authentication system of this application run can be founr din the JwtGenrationService class. All authentication starts with a login request generating a token with the generateToken(String googleId) method. Here we will sign the token with a secret key that should not be stored publicly in production, a likely solution to this is use of an environment variable. With this key someone can decode the token and access whatever data is contained within, even generate their own tokens meant to infiltrate the application. This key can also authenticate the user <strong>across multiple micro-services</strong>. To achieve this, implement the same token filter in each micro-service and verify that incoming tokens are signed with the shared key. We will simply store the google id on these tokens to be used in identifying which user is signed in. The JWT_EXPIRY will set a timeout for this token, such that after this period it will no longer register as valid (in milliseconds).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1715e6bf8e22d8e05430dfd9babe711/href">https://medium.com/media/a1715e6bf8e22d8e05430dfd9babe711/href</a></iframe><p>After this we need a method to get the google id from a JWT, this will first verify the JWT is valid both in expiry and signed with the secret key. The google id is stored in the googleId claim. We will also provide a method to validate a token in any context.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/901fe5c637c5e7ad63e7abe83ed50206/href">https://medium.com/media/901fe5c637c5e7ad63e7abe83ed50206/href</a></iframe><p><strong>NOTE </strong>if an application uses google OAuth in a similar manner to this and gets a users permission in the google OAuth consent screen, they will have access to that users google id. Without the JWT secret key used to sign these tokens they will still be denied access to this application.</p><p>The JWT filter gets the token from the request header “Authorization”, and validates the token with the validateToken(String token) method in the generator service. Should the token be valid it will get the username and create a UsernamePasswordAuthenticationToken that will be attached to the authentication context. This allows the request to clear endpoints configured with authenticated() in the security configuration. Furthermore, we will see in the <a href="#ba57">next section</a> that this authentication context can be used to get the users information (google ID) later in the application flow.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ae0d69e0e0e4ea5df51265a59fea62a/href">https://medium.com/media/2ae0d69e0e0e4ea5df51265a59fea62a/href</a></iframe><h4>Getting User Details Throughout the Application</h4><p>We will be using the /hello endpoint to test authentication status and getting user information when a user is properly signed in. Recall the authentication token is set to the users authentication status. This can later be accessed by getting the authentication context with the SecurityContextHolder. The UserDetails are then ascertained, and we can get the “username” from here. Note we made our google id the username here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68e9818576da32276edbc88dea8c33ac/href">https://medium.com/media/68e9818576da32276edbc88dea8c33ac/href</a></iframe><p>We also need a way to simply return a boolean authentication status within the application. This is used to determine if the user already has a valid stored authentication JWT on the front-end before attempting a fresh sign in (and thusly limit load on the back-end authentication service). The user will not be able to access endpoints with the .authenticated() property assigned in the security configuration in this application without clearing the custom JWT filter. So if a user reaches this method at all we know they are authenticated.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d47a70eb32e2196e191f2598b278df6e/href">https://medium.com/media/d47a70eb32e2196e191f2598b278df6e/href</a></iframe><h3>Tying it Together — Demo</h3><p>Phew, that was a mouthful. All that work for a quick couple seconds of user experience on the client-side. But with this method you can safely authenticate your users and start storing their information! Let’s walk through the login from the user perspective to close this all out…</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.loom.com%2Fembed%2F6f2f8e41c3a34e88bd4bcedc28c3976e&amp;display_name=Loom&amp;url=https%3A%2F%2Fwww.loom.com%2Fshare%2F6f2f8e41c3a34e88bd4bcedc28c3976e%3Fsid%3D388fd680-9c5b-4473-ada2-5cf6a4834cf9&amp;image=https%3A%2F%2Fcdn.loom.com%2Fsessions%2Fthumbnails%2F6f2f8e41c3a34e88bd4bcedc28c3976e-00001.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=loom" width="1920" height="1440" frameborder="0" scrolling="no"><a href="https://medium.com/media/3228e8ca84683fe7e05de3b640e3c179/href">https://medium.com/media/3228e8ca84683fe7e05de3b640e3c179/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4f4d7606ba3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/lets-get-authenticated-google-sign-in-d4f4d7606ba3">Let’s Get Authenticated — Google Sign In</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Local Web Development Setup with Docker]]></title>
            <link>https://blog.devops.dev/local-web-development-setup-with-docker-c666905223c3?source=rss-6d784533b7e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c666905223c3</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[docker-container]]></category>
            <dc:creator><![CDATA[Ken Foss]]></dc:creator>
            <pubDate>Tue, 14 May 2024 16:13:46 GMT</pubDate>
            <atom:updated>2024-05-25T17:26:49.152Z</atom:updated>
            <content:encoded><![CDATA[<h4>Every Tinkerer Needs Their Tools</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qLim-tAH2Rr6azsJnEt4Q.jpeg" /></figure><p>A developer has an ever-growing toolkit, let’s build the tool box. Countless “support” services are often incorporated into web development projects. It becomes a pain to start up a local MySQL instances and the like every time you boot up. It only becomes more of an issue as you begin to develop and test more services. At a corporate level you may be given a server with each service you will use wrapped up neatly to data dump to your hearts content, but many of us need to fiddle at home. For this I use a docker-compose configuration where I can easily deploy my entire supporting cast with a quick CLI command. Let’s get into it.</p><h4>The Services</h4><p>In typical fashion, I am prepared to start you off with some services I frequent. These would be Redis, RabbitMQ and MySql. To develop on these services and test they are up and running, you will need the following:</p><ul><li>Redis-tools: Install with sudo apt-get redis-tools or mac with homebrew brew install redis</li><li>I will use DBeaver to connect to the MySQL instance, though this can be done in the CLI.</li><li>Docker-Hub: You need to start docker on your machine, an easy way to do this is to run docker-hub desktop.</li></ul><h4>The Config</h4><p>This is where the magic🧙 Happens! This config will pull the given images from docker hub and deploy them to the given ports locally, then we can connect away! Note the “volumes” section of each service, which references a “docker-conf” folder in the same directory as the config. This is extremely important, it ties the storage for each service container to a location outside the container. This way the data saved to these services will persist when the container is closed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dba9bdad56aa99349ec25e3de4d2c1b9/href">https://medium.com/media/dba9bdad56aa99349ec25e3de4d2c1b9/href</a></iframe><h4>Deployment and Testing</h4><p>With this config you need only a bit more magic to begin interacting with these services. With this command you will spin up containers built from the provided images docker-compose -f docker-toolkit.yml up -d, here the -d switch detaches the command so it will run in the background (and you can continue to use this terminal).</p><p>Now that the services are up we can use them… let’s get on it.</p><h4>Redis</h4><ol><li>Connect to the service:redis-cli -h localhost -p 6379</li><li>Create a key-value pair: set newkey “Hello World”</li><li>Visualize the key: keys *</li><li>Get the corresponding value: get newkey</li></ol><h4>RabbitMQ</h4><ol><li>Navigate to the following url: <a href="http://localhost:15672/">http://localhost:15672/</a></li><li>Enter username and password as “admin”</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ivuw7PfQI5gCIbFWU74dog.png" /><figcaption>RabbitMQ Console</figcaption></figure><h4>MySql</h4><p>My MySql settings are as follows in DBeaver, the password is “root”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*xD49-13Qrbx-qrHT43TxXg.png" /><figcaption>DBeaver Connection Configuration</figcaption></figure><p>Now, I am going to create a table called “test”, I want to ensure it persists when the container is restarted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3gcNm6qCPqFfrRzyaz_r5g.png" /><figcaption>Create Table, use the highlighted save button to generate</figcaption></figure><p>Success! Upon restarting of the container our table is there just how we created it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wQml2izw5xyDalGdvyCs7Q.png" /><figcaption>Persistent Data in SQL</figcaption></figure><h4>Restarting Your Containers</h4><p>There is no need to run the docker-compose every time you start these services. The containers persist even as you restart your machine. If we go into docker desktop we can see these services and restart them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IUuImyjRdO1RIQGIDHBP9Q.png" /><figcaption>Docker Desktop — Containers</figcaption></figure><p>Now, you can restart these containers with the “play” button. If you prefer CLI commands the following will show your available containers:</p><pre>docker ps -a</pre><p>And start a container of your choosing:</p><pre>docker start my_container_name</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c666905223c3" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/local-web-development-setup-with-docker-c666905223c3">Local Web Development Setup with Docker</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dive into Cross-Site Request Forgery]]></title>
            <link>https://levelup.gitconnected.com/dive-into-csrf-defense-real-attack-demonstrations-safeguards-with-spring-security-69c22b25c322?source=rss-6d784533b7e8------2</link>
            <guid isPermaLink="false">https://medium.com/p/69c22b25c322</guid>
            <category><![CDATA[csrf]]></category>
            <category><![CDATA[csrf-protection]]></category>
            <category><![CDATA[csrf-bypass]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[csrf-attack]]></category>
            <dc:creator><![CDATA[Ken Foss]]></dc:creator>
            <pubDate>Wed, 01 May 2024 02:06:51 GMT</pubDate>
            <atom:updated>2024-06-11T15:46:16.409Z</atom:updated>
            <content:encoded><![CDATA[<h4>Real Attack Demonstrations with Cross-Site Scripting &amp; Safeguards with Spring Security</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8DwdRkCCi_11eczIcYCQGg.jpeg" /></figure><p>Site security starts at the authentication layer, users are greeted with an all too familiar sign-in screen and trust that once they hit the submit button their information is protected. On the back-end, this process is far more intense, their sign-in generally triggers the creation of a session id token or a JSON web token (JWT) to identify them as an authenticated user. These tokens serve as a singular identifier to the users identity and are often stored in their browser cookies. A CSRF attack, or Cross-Site-Request-Forgery, targets such defense mechanisms stored in a cookie. With a valid session id token a hacker can wreak havoc on your application.</p><p>We are going to explore how an attacker may attempt such an attack through HTML scripting, and then demonstrate a few defense mechanisms with Spring Security.</p><h4>Background — Cookies and CORS (Cross-Origin Requests)</h4><p>If you are new to CORS (Cross Origin Requests), or completely unfamiliar with the term, I strongly recommend reading the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">MDN documentation</a> on the subject before you proceed.</p><p>Cookies are not set by default on cross-origin requests, your RESTful API will need to be configured properly to allow cross origin requests to include credentials. To do so you must set Access-Control-Allow-Credentials=true. Now, to avoid further frustration it is important to note that the browser will reject any response that includes Access-Contol-Allow-Origin=* (when credentials are allowed) so even in testing scenarios we must be purposeful with our allowed CORS origins. As you will see later in this post, this is what your REST endpoints will resemble in our SpringBoot application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6ed8d7991fd864bbfe100d0c7ab1962/href">https://medium.com/media/c6ed8d7991fd864bbfe100d0c7ab1962/href</a></iframe><p>To the same effect, front-end request must include credentials. This will look as such in our React application:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/951eeceeb23a750d1ba97c1949ae607b/href">https://medium.com/media/951eeceeb23a750d1ba97c1949ae607b/href</a></iframe><h3>The Attack</h3><p>You may be familiar with the<strong> Same-Origin Policy(SOP), </strong>largely followed by browsers across the web. It is a crucial security concept in web browsers that restricts how documents or scripts loaded from one origin(domain) can interact with resources from another. However, cross-origin <strong>writes</strong> <strong>are allowed</strong>, and redirects are considered writes (as are links, redirects and form submissions). You can read more on what requests are exempt from SOP in the <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy">MDN docs</a>. An assailant can lure users to their HTML page while they are logged into the target site and the embedded script of this page will have access to the origins cookies. Once a user has navigated to the malicious link while logged into your application your session tokens are no longer secure.</p><p>In this section we will attack our own unsafe application, and demonstrate what an attacker might do. It is important to know the nature of the danger before approaching our solution.</p><h4>The Setup</h4><p>Here is the entirety of the testing setup for the vulnerable version of our app, the next few sections will explain what is happening and walk you through a demo where you can test this attack yourself.</p><p><a href="https://github.com/KenFoss/CSRF_demo/tree/vulnerable-site-demo">GitHub - KenFoss/CSRF_demo at vulnerable-site-demo</a></p><h4>Application Flow</h4><p>When within the unsafe-app directory in the git project given above, run the command npm start and the application will launch on port 3000. On startup this application will use the /login-testendpoint in com.demo.csrf.web.rest.security of the Spring-Boot back-end via a useEffect hook. This sets a cookie entitled “test-session-id” to the front-end and saves it in the browser. The new cookie is now automatically included in requests to the back-end, which will ensure it’s presence before allowing requests to its endpoints.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FxFeM81D7fiY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DxFeM81D7fiY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FxFeM81D7fiY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b23b21f704351f7f15d9c2f9999c2f7/href">https://medium.com/media/6b23b21f704351f7f15d9c2f9999c2f7/href</a></iframe><p>The back-end application is configured with a filter that simulates authentication of a session id, in this case checking that the test-session-id cookie has been passed with the request. A session id is used by a server to associate subsequent requests from the same user with their session data, and is often sent and stored as a cookie. This can include authentication status, user preferences and more. With the session passed along in the cookies an attacker can often access sensitive requests such as POST requests while disguised as the user of the session id in use. In the case of a JSON web token stored or passed as a cookie, the same vulnerability applies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3fba55ed042fc15c3fe00c1438bd9b9/href">https://medium.com/media/a3fba55ed042fc15c3fe00c1438bd9b9/href</a></iframe><p>So, now when we attempt to access data via our /get-data endpoint we are met with an 403 forbidden response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*lmr6APlFUcUQVHVK8vXEaQ.png" /></figure><p>However, if we call our /login-test endpoint first the request will succeed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*YDMCOhsKKWhGc_noX0Mvpg.png" /></figure><p>So, back to our unsafe React application. We have hit our login endpoint and have our session cookie. This gives us access to the back-end and allows a post via the post locally button. Let’s give it a try:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FxFeM81D7fiY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DxFeM81D7fiY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FxFeM81D7fiY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b23b21f704351f7f15d9c2f9999c2f7/href">https://medium.com/media/6b23b21f704351f7f15d9c2f9999c2f7/href</a></iframe><h4>Where does it go wrong?</h4><p>The nature of the Same Origin Policy(SOP) will protect our token from other domains. If we navigate to a new tab this can be demonstrated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cLw2GmHGJcZeedL_7uZQPQ.png" /></figure><p>It is apparent our cookie from localhost:3000 is not accessible via this domain and should we try the same post request from before in the console, it will fail.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FG3rVoDwSoVU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DG3rVoDwSoVU&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/30924f7c3efaccc74e156158fdcef950/href">https://medium.com/media/30924f7c3efaccc74e156158fdcef950/href</a></iframe><p>You will notice that the test session cookie was not included in our request, and as a result, we were denied access, as expected. This is due to the Same-Origin Policy. However, if we were to embed this POST request in a form, as is done in the evil.html file, we can evade SOP restrictions and attack our back-end system.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f778a62d3c02715c2396480f1f9a7fdd/href">https://medium.com/media/f778a62d3c02715c2396480f1f9a7fdd/href</a></iframe><h4>Let’s Give it a Try</h4><p>Ensure you are running evil-serve.js within the evil-script directory of the github project found in <a href="#ff05"><strong>the setup</strong></a>. To run this simple node application and serve the HTML page you can use the command node evil-serve.js. Click on the link from our unsafe app, and let the breach begin.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FB2IRkrtuskQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DB2IRkrtuskQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FB2IRkrtuskQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/55a1a0afe696a4388086ad4143d0c52a/href">https://medium.com/media/55a1a0afe696a4388086ad4143d0c52a/href</a></iframe><p>Congratulations, you hacked yourself! In the above video, we first navigate to localhost:3001(evil.html) in the same browser as the site we are attacking. The attempt succeeds despite being attempted on another domain. Note, if you attempt to access localhost:3001 in another browser the request is unauthorized, without the cookies from your app the request cannot pass the filter.</p><h3>The Defense</h3><p>CSRF attacks themselves are very finicky and tip-toe around the nature of Same Origin Policy to include the cookies from the origin site with the HTML scripts POST requests. We can trip the attacker on another hurdle by requiring a special token be set in the header, then simply including the cookies with their request will not pass through our security. This is often the nature of CSRF defense mechanisms. Another token is passed to the front-end either by cookie or response body, and must be included on subsequent post requests in the specified header. We will explore two ways of passing this <em>CSRF token, </em>one of which leaves its own gaps in security.</p><h4>Sending a token to the Front-end</h4><p>While I will give you the setup for using a cookie based CSRF token repository, I would like to note the dangers of using such a security measure. The<a href="https://owasp.org/"><em> Open Web Application Security Project (OWASP)</em></a> cautions against using cookies (or bowser local storage) to store the CSRF token client side. It is recommended the token be included as a response header or in the response body, never as a cookie. It is often better practice to store it in a JavaScript variable or elsewhere on the DOM.</p><p>Just as an attacker can access session ids in an HTML scripting attack, they can access the CSRF token. All they have to do is attempt the request they are attacking twice, the first time they will get your CSRF token returned as a cookie, it is now accessible to their domain. In the second request they will include this as a header, and since they already included your session id they now have full reign over your data.</p><h4>The Setup — CSRF Get Request</h4><p>Our data is all secured through Spring Security. To retrieve the token from a get request we must configure use of a HttpSessionCsrfTokenRepository() and the appropriate request handler.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6dc14a57897ebd0823a522e228ed0f78/href">https://medium.com/media/6dc14a57897ebd0823a522e228ed0f78/href</a></iframe><p>The token repository will handle generation and storage of the token, it can then be injected into a get request method and returned to the user. The request handler will ensure the presence and validity of said token on subsequent POST requests. Now that we have configured the application for CSRF request handling and token generation, we can construct a GET endpoint that will use dependency injection to retrieve our token and send it to the user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70e6c259d597f492229f6b33e52e95c1/href">https://medium.com/media/70e6c259d597f492229f6b33e52e95c1/href</a></iframe><p>Like magic all of our post endpoints are protected! You can examine the GitHub branch below for the setup of the example endpoint we will use in the demo, but it differs little from the last setup.</p><p><a href="https://github.com/KenFoss/CSRF_demo/tree/safe-site-demo">GitHub - KenFoss/CSRF_demo at safe-site-demo</a></p><h4>The Attack — CSRF GET Request Method</h4><p>If we use an endpoint to get the CSRF token, the front-end will need to store said token on its own. The token is never exposed to the browser cookies and will not persist in browser storage past the original request. Once this token is received and stored, it must be used in subsequent POST requests as a X-CSRF-TOKEN header else a 403 unauthorized response be returned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CgwrUMZHlf_KEHX4N9fotA.png" /><figcaption>Created in FigJam</figcaption></figure><p>In our implementation the token will be stored in a useState() hook. Once our login-test endpoint retrieves the session token, a CSRF token is immediately retrieved and stored in a JavaScript variable within our application for use in our POST request. See <a href="#16ed"><strong>the setup</strong></a><strong> </strong>for the React implementation of this token retrieval step, it is all done with useEffect and useState hooks. So, let’s try it out and see if our evil HTML script can get to work!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FazXYOeNC6dA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DazXYOeNC6dA&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cf5e83d4dce5108182092810091b26e/href">https://medium.com/media/1cf5e83d4dce5108182092810091b26e/href</a></iframe><p>You will notice the token is retrieved in the response from the get-token endpoint. Now, when we access the malicious script it’s post request fails with a 403-unauthorized response.</p><h4>The Setup — CSRF Cookies</h4><p>When we use CSRF cookie the spring security configuration is largely the same, however we will use a CookieCsrfTokenRepository in this scenario as such.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dfa25b13edbb5033b134ce7ed1ea5a1/href">https://medium.com/media/9dfa25b13edbb5033b134ce7ed1ea5a1/href</a></iframe><p>This configuration is often perceived as easier in applications with JavaScript front-ends (angular, React) as any GET request will result in obtaining this token. Then, throughout the application flow the token can be accessed in the browser cookies. It is imperative the cookie token repository be set with <strong>HTTP only set to false</strong>, this allows the cookie to be accessible to JavaScript. This setup is highlighted in the GitHub branch below.</p><p><a href="https://github.com/KenFoss/CSRF_demo/tree/safe-site-with-cookies-demo">GitHub - KenFoss/CSRF_demo at safe-site-with-cookies-demo</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mUS-rsDcUX-OCgN3gi74CA.png" /><figcaption>Created in FigJam</figcaption></figure><p>This flow is similar to that of the GET endpoint, however any POST request to the back-end application will result in token retrieval. Since login requests are often POST requests, this means an application need only clear authentication to attain the CSRF cookie. A major benefit of using the cookie is that it will be available in the browser cookies throughout application flow. Post requests can simply query the document cookies and attach the token as a request header. There is no need to store the token in a variable. If we use this setup the malicious script is still unsuccessful in its post attempt.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F30CsuLYvuOo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D30CsuLYvuOo&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3441dba2f5557cd833ded5ca48536832/href">https://medium.com/media/3441dba2f5557cd833ded5ca48536832/href</a></iframe><h4>The Attack — CSRF Cookies</h4><p>So our simple evil.html (now old-evil.html) did not work, now the hacker just has to do a bit more work. As was mentioned <a href="#916c">before </a>they need only send the POST request twice, attaining a valid CSRF token between, to hack your site. Here is the script they can use to do so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/764ad55edbcb518a593c1ebdf06595c3/href">https://medium.com/media/764ad55edbcb518a593c1ebdf06595c3/href</a></iframe><p>Let’s give it a try!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5dJkORMd0TM&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5dJkORMd0TM&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2F5dJkORMd0TM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1af78aab0c738dbf707c22f0559c95e0/href">https://medium.com/media/1af78aab0c738dbf707c22f0559c95e0/href</a></iframe><p>Oh no! You’ve been hacked! 👾👾👾</p><h3>Wrapping Up</h3><p>Hopefully this post helped you with the configuration of spring security, and demonstrated it’s effectiveness and necessity. Clone the github repository and hack it yourself! I often find a hands-on approach helps me learn the best. If there were to be one takeaway here, it would be to do your best to stay away from using a cookie to send the CSRF token to your front-end. Good luck out there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69c22b25c322" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/dive-into-csrf-defense-real-attack-demonstrations-safeguards-with-spring-security-69c22b25c322">Dive into Cross-Site Request Forgery</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>