<?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 Furkan Danışmaz on Medium]]></title>
        <description><![CDATA[Stories by Furkan Danışmaz on Medium]]></description>
        <link>https://medium.com/@danismaz.furkan?source=rss-94ea17f665b4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PuI8r8npVG0j0VuTwIAAIQ@2x.jpeg</url>
            <title>Stories by Furkan Danışmaz on Medium</title>
            <link>https://medium.com/@danismaz.furkan?source=rss-94ea17f665b4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 04:22:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danismaz.furkan/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[Answers to FAQ about being a Software Engineer in Picus]]></title>
            <link>https://medium.com/picus-security-engineering/answers-to-faq-about-being-a-software-engineer-in-picus-ec94d3235f6a?source=rss-94ea17f665b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec94d3235f6a</guid>
            <category><![CDATA[remote-working]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[picus-security]]></category>
            <category><![CDATA[technical-debt]]></category>
            <dc:creator><![CDATA[Furkan Danışmaz]]></dc:creator>
            <pubDate>Mon, 04 Apr 2022 09:52:03 GMT</pubDate>
            <atom:updated>2023-05-09T06:27:58.551Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVHkJ5SDVOFumjf0FJkKXg.png" /></figure><p>As one of Turkey’s leading startup companies, Picus’ awareness is increasing day by day. While writing this article, I wanted to talk about the engineering culture inside as a software engineer who has been working at Picus for about 2 years.</p><p>One of the most common question that we get is “How much cyber security knowledge is expected from a software engineer in Picus.” To answer this question I would like to introduce the Picuslabs. Picus has very strong labs teams that handle the heavy lifting in terms of research for the problems that we want to offer solutions to our customers. While making research they try to answer if we as Picus can offer a valuable solution in an elegant way, if yes what are the pros and cons of each alternative.</p><p>As well as doing research before adding new functionality to the product, they also handle producing all the threat and detection content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Ga8fC4rr0legiPvrIAWBA.jpeg" /></figure><p>If we get back to the question, no cyber security knowledge is expected from the software engineers, at least at the beginning. Of course it is important to understand the basics to comprehend the big picture of the product. However, that knowledge is easily gained within the first few months with the help of the onboarding process and ready to help team members.</p><p>Another question that we frequently get is “How do the engineering teams operate?”</p><p>There is a roadmap that is managed and constantly updated by the Product Management team. As I mentioned above, the research that needs to be done in order to achieve the medium and long-term goals in this roadmap are carried out by the labs teams, while the UX team analyzes the short-term goals in detail from the user experience perspective and prepares the necessary designs.</p><p>That way, the development teams focus on the items below:</p><ul><li>The delivery of the features in the current scope &amp; fixing the existing problems</li><li>Working on the next scope by analyzing the items in the roadmap from the technical perspective</li><li>Designing and preparing the infrastructure for the items that will be developed in near future.</li><li>Managing the technical debts</li><li>Clear &amp; maintainable code base</li></ul><p>Delivering the features of the current scope, fixing the existing bugs, working on the next scope and preparing the necessary infrastructure for it are pretty obvious things for almost all software development teams. So, I’m skipping them because I want to talk more about how we approach technical debts and code base maintainability.</p><h4>Technical debts &amp; refactoring</h4><p>There are so many features we want to add to our product and we are trying to add them quickly. Speed brings faults, bad practices &amp; low performance, wrong design decisions, and even mistakes in analysis. When these errors accumulate, it can be very laborious and costly to return. We are aware of it and that’s why we pay attention to our mistakes, and want to return from them as early as possible. We constantly approach the decisions we make and the code we write with a critical eye, we generate technical debts for ourselves and manage them explicitly in our development board.</p><p>Paying off the technical debts often means refactoring. For us, refactoring is not a separate activity to be handled from time to time, we see it as a part of the software development cycle instead and include it our plans.</p><p><em>If you want to read more about refactoring, </em><a href="https://medium.com/@danismaz.furkan/a-perspective-of-codebase-mastery-on-refactoring-23b86f8cc4c0"><em>here</em></a><em> is my personal thoughts about it.</em></p><h4>Automated Tests</h4><p>Another thing that we see as part of the software development process is automated testing (especially unit and integration tests). Before you can write a test, the code you want to test must be testable. In order to write a testable code, you inevitably have to apply the basic software principles which as a result helps you write more modular and more manageable code. Another benefit of writing tests is that they are the protectors of the code base from unexpected side effects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hL4ZuHhn2RVdAtUCsslkBQ.jpeg" /></figure><p>Automated testing is part of the CI/CD pipeline for us, as in many software companies. If all tests are not passed, the relevant piece of code cannot go to the main development branch and therefore cannot go live.</p><p>But we realised that noticing the failing tests after the CI/CD pipeline fails is a little bit late. For that reason, we wrote a git pre-push hook that is automatically triggered with the git push but before the code is actually pushed to the origin. That hook automatically regenerates the mocks, runs the tests in the local environment, and fails the push command execution if there are test failures.</p><h4>Code Review</h4><p>The code review phase is one of our strengths. The review activity is a prerequisite for a piece of code to go to the main development branch. While doing code review, we warn each other about our mistakes, discuss more effective versions of the proposed solutions, check if the basic software principles are applied, and most importantly we learn from each other. This helps all the software developers in the team meet on the same page over time.</p><p>One final question that I want to talk about is “Working remotely is nice but also hard. How Picus handle it?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Z-taqey1NBJ6w3E7JCU4Q.jpeg" /></figure><p>Picus has managed to say “health first” by removing the obligation to come to the office from the beginning of the pandemic process, and even turned remote working into an advantage. Many companies worry about switching to remote work because they are afraid of a decrease in productivity. I can clearly say that productivity in Picus, on the contrary, has increased. Yes, it is not easy to achieve this, but it is quite possible when the necessary environment is provided. Trust, autonomy, and communication are the keys here.</p><p>With remote work, the importance of intra-team and inter-team communication increases even more. As software teams, we are aware of it, and we always keep in touch, support each other, do pair programming when necessary and solve problems together. We move forward as a team.</p><p>One challenge that comes with working remotely is emotional disconnection. It is very difficult to develop ties in relationships where we do not work side by side and communicate only in digital environments. Although we think that professionalism is a necessity in the business world and act accordingly, we believe that developing close ties within and between the teams has a very important role in success. That’s why it is important for us to get together occasionally and spend time together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_-hauUuVOCBrzhIXuVKeeg.png" /></figure><p>In this article, I talked about both the distribution of the responsibilities within Picus Security and what we care about as engineering teams. Of course, the way we work and the points we care about are not limited to what I wrote here. For example, we pay attention to constantly improving ourselves and sharing what we learn. We attach importance to following the right software development practices. We constantly criticize not only the code, but also our processes, and strive to improve the way we work. In each cycle, we set our sprint goals as a team and try to comply as a team.</p><p>There are many other points like these that can be listed but I tried to talk about more interesting topics and tried to answer the most common questions about being a software engineer in Picus Security. I hope I was able to paint a picture in your mind for those who are wondering.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec94d3235f6a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/picus-security-engineering/answers-to-faq-about-being-a-software-engineer-in-picus-ec94d3235f6a">Answers to FAQ about being a Software Engineer in Picus</a> was originally published in <a href="https://medium.com/picus-security-engineering">Picus Security Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Know If a Golang App is Executed with go test]]></title>
            <link>https://medium.com/picus-security-engineering/how-to-know-if-a-golang-app-is-executed-with-go-test-66487ccd71b6?source=rss-94ea17f665b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/66487ccd71b6</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Furkan Danışmaz]]></dc:creator>
            <pubDate>Tue, 18 May 2021 08:18:09 GMT</pubDate>
            <atom:updated>2021-05-18T08:18:09.076Z</atom:updated>
            <content:encoded><![CDATA[<p>If you came across this story, it is obvious that you want to be able to know (programmatically) if your code is being executed with go or go test and may be you are wondering if your code should know the difference.</p><p>To start with, of course it is better if you can avoid putting if statements inside your code that checks if the code is being executed with go test. However, you may come across with some cases that you have no better option. In my case, we are initializing some background jobs that creates resources and open session to cloud resources and I don’t want them to be initialized during test execution.</p><h3>What’s Wrong With Using An Environment Variable?</h3><p>The first thing that comes to mind is to use some environment variable. That’s a very easy way to solve this problem:</p><ul><li>Define an environment variable. EXECUTION_ENVIRONMENT for example</li></ul><pre>func IsTestRun() bool {<br>  return os.Getenv(&quot;EXECUTION_ENVIRONMENT&quot;) == &quot;test&quot;<br>}</pre><ul><li>and set that environment variable before running your application in test mode:</li></ul><pre>export EXECUTION_ENVIRONMENT=&quot;test&quot;<br>go test ./... </pre><p>Down side of this approach is you always have to set the environment variable before running your tests.</p><h3>Using the flag Package</h3><p>While executing our code with go test, we are sending some extra flags as OS arguments (like the test itself after the go command) and we can access them in our programs, so why don’t we just make use of them.</p><pre>if flag.Lookup(&quot;test.v&quot;) == nil {<br>  // normal execution<br>} else {<br>  // test execution<br>}</pre><p>However, for this code to work first you should define all the possible flags and call flag.Parse() function.</p><pre>package test</pre><pre>func init() {<br>  if flag.Lookup(&quot;test.v&quot;) == nil {<br>    flag.Bool(&quot;test.v&quot;, false, &quot;verbose output&quot;)<br>  }</pre><pre>  if flag.Lookup(&quot;test.v&quot;) == nil {<br>    flag.String(&quot;test.run&quot;, &quot;&quot;, &quot;run tests matching expression&quot;)<br>  }</pre><pre>  // define all possible flags here</pre><pre>  flag.Parse()<br>}</pre><pre>func IsTestRun() bool {<br>  <em>return </em>flag.Lookup(&quot;test.v&quot;).Value.(flag.Getter).Get().(bool)<br>}</pre><p>OK, I think this is a better way than using an extra environment variable but still defining all the possible flags is annoying, isn’t it?</p><p>And there is another problem with this code. It panics :) with a message telling that you are registering the same flags more than once even though we put a nil check before registering them.</p><h3>Using the testing Package</h3><p>The testing package already has Init function that handles all the possible flag registrations for go test which is exactly what I was looking for. With the help of the testing.Init() my code that checks if the app is executed with go test became as follows:</p><pre>package test</pre><pre><em>func </em>init() {<br>   testing.Init()<br>   flag.Parse()<br>}</pre><pre>func IsTestRun() bool {<br>  <em>return </em>flag.Lookup(&quot;test.v&quot;).Value.(flag.Getter).Get().(bool)<br>}</pre><p>Now, you can call this function and know that if your code is executed with go test</p><pre>func init() {<br>    // do common initializations</pre><pre>    if test.IsTestRun() {<br>        // some mock initializations for tests if needed<br>    } else {<br>        // actual initializations<br>    }</pre><pre>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66487ccd71b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/picus-security-engineering/how-to-know-if-a-golang-app-is-executed-with-go-test-66487ccd71b6">How to Know If a Golang App is Executed with go test</a> was originally published in <a href="https://medium.com/picus-security-engineering">Picus Security Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Perspective of Codebase Mastery on Refactoring]]></title>
            <link>https://medium.com/@danismaz.furkan/a-perspective-of-codebase-mastery-on-refactoring-23b86f8cc4c0?source=rss-94ea17f665b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/23b86f8cc4c0</guid>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[Furkan Danışmaz]]></dc:creator>
            <pubDate>Sat, 17 Oct 2020 13:55:14 GMT</pubDate>
            <atom:updated>2020-10-17T14:11:02.090Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*muGV-cLjvQkGCZ4QxS6S3g.jpeg" /></figure><p>We develop software to solve a problem, automate complex processes and improve efficiency. In other words, it is a tool for people to make their lives easier. Therefore, as developers our primary focus is to add functionalities and make sure they are working correctly.</p><p>But wait, some dirty developers waste their time to fix code that is already working as expected. How can you fix a code that is already correct. What is your goal you idiot? If it works, don’t touch it!</p><p>So many people tend to have this approach. If it is working, why bother improving it. It is a waste of time. Besides, you may break it. But is that really correct? In this story, I’ll try to explain why we (as developers) need code refactoring and why it is NOT a waste of time.</p><h3>What Was I Thinking?</h3><p>We all know that, developers do code refactoring to improve code quality or performance, remove code smells, and reduce code duplications. These are obvious reasons, no need to talk about them. But there is another benefit (and I believe it is the most important one) that I want to talk about. Mastering the code base.</p><p>We write thousands and thousands of lines of code in a software project. No matter how good we document our code, and our design decisions, it is impossible to remember the purpose of each and every line. Sometimes, we need to change a piece of code that we wrote a couple of months ago because the related requirement has changed, or a bug is found on the production, or it is broken as of a side effect of another change that is made on another piece of code (shouldn’t happen, but it does!). Have you asked yourself “What was I thinking while writing this?” I believe the answer is “YES” for most of the developers (if not all). The reason you ask such question to yourself is that, you haven’t spent time thinking about that piece of code for a very long time and as a result you forgot the purpose despite you are the author of it.</p><p>It is even harder when we need to change a code that is authored by another developer.</p><h3>Mastering the Code</h3><p>Understanding the code is the first step of refactoring. That’s why developers who spend more time on it, have a better understanding of the code. They constantly refresh their memories and that’s the key. As a result, they can easily make changes to the system when needed because they are able to see the big picture, not some independent pieces. Not good enough? How about the following items:</p><ul><li>Being able to maintain the code without the fear of breaking it</li><li>Less time for fixing bugs</li><li>Less time for making changes</li></ul><p>Some developers spend hours to understand and solve bugs or making changes to the existing code while some others spend minutes. Why is that? Of course it is related to the complexity of the bug (or the change request), but this statement would remain true even if all the bugs on the world were on the same level of complexity. You may think that it is also related to the knowledge &amp; experience level of the developers. I am not arguing that either. What I am trying to tell is this statement would still be true if all developers had the same knowledge &amp; experience because I believe that, it’s also related to how well you remember the code.</p><p>When you force all developers to focus on feature development and do not support code refactoring, nobody will master the code base. Eventually the upper management and the product management will have a hard time when they want to make changes to the existing features, when some bugs are found on the production, even when adding new features.</p><h3>When to Refactor?</h3><p>I heard developers or managers many times saying that “our code is so messed up that it takes very long time to make changes, and while we are fixing bugs, we are introducing new ones. Let’s spare a sprint for refactoring”. OK, let’s spare a sprint for it, but where to begin? If that’s your approach, then I would agree that refactoring is a waste of time. It just doesn’t work like this.</p><p>The important thing about code refactoring is to criticize the code all the time and have specific improvements in mind (or in your notes). Only that way you will feel the need for refactoring even when you are adding a new feature, or fixing a bug. And only that way you will master your code base.</p><p>I am not saying you should forget about feature development or bug fixes, and do refactoring all the time. Of course, completing the issues “in time” is more important than code refactoring. After all customers don’t care how clean your code base is. What I suggest is to make refactoring be part of your development process. Criticize the the code that you touch within the scope of your task, realize code smells, duplications, unnecessary operations, and bad practices. If you don’t have enough time to apply the improvements that you have in your mind, note them down and apply them later when you are not in a rush.</p><h3>The END</h3><p>I personally find code refactoring similar to cleaning home or having a shower. It feels like you are getting rid of the dirts, isn’t it? If you don’t clean your house for a very long time, the dirt that you are living in will eventually kill you. I think the very same thing applies for software development. If you don’t refactor your code for a very long time, you will eventually have trouble while maintaining it.</p><p>This is my recent perspective on code refactoring and I would like to hear if you have different opinions . Thank you for reading this far.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23b86f8cc4c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Different Factory Method Pattern Implementation in Java using Jackson]]></title>
            <link>https://medium.com/@danismaz.furkan/a-different-factory-method-pattern-implementation-in-java-using-jackson-57b773f5c043?source=rss-94ea17f665b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/57b773f5c043</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[factory-method]]></category>
            <category><![CDATA[jackson]]></category>
            <category><![CDATA[inheritence]]></category>
            <dc:creator><![CDATA[Furkan Danışmaz]]></dc:creator>
            <pubDate>Sat, 20 Jun 2020 20:32:31 GMT</pubDate>
            <atom:updated>2020-07-25T19:14:43.276Z</atom:updated>
            <content:encoded><![CDATA[<p>Before starting, I need to say this story is not about explaining the Factory Method design pattern. Today I needed a Factory implementation and suddenly I asked myself why not use the polymorphic deserialization feature of the Jackson, so I implemented it that way and I wanted to share it.</p><p>I think the ones who are familiar with Jackson polymorphic deserialization already got the idea. The goal is to get rid of the switch or if statements of the Factory Method pattern. The Jackson library is capable of creating instance of the correct type from a JSON string if it somehow contains the type information. Let’s make use of it.</p><h3>An example of Polymorphic Deserialization</h3><p>Suppose that we need a Writer object at some point in our code but what type of writer we should use varies based on the context. We have MSWordWriter, PDFWriter, ExcelWriter, etc…</p><pre>public enum WriterType {<br>    PDF,<br>    MICROSOFT_WORD,<br>    OPEN_OFFICE_WRITER,<br>    ...<br>}</pre><pre>public abstract class Writer {<br>    public abstract void write(String content);<br>}</pre><pre>public class MSWordWriter extends Writer {<br>    public void write(String content) {<br>        ...<br>    }<br>}</pre><pre>public class PDFWriter extends Writer {<br>    public void write(String content) {<br>        ...<br>    }<br>}</pre><pre>public class OpenOfficeWriter extends Writer {<br>    public void write(String content) {<br>        ...<br>    }<br>}</pre><h4>Let the Jackson Decide Which Type of Object to be created</h4><p>The Jackson’s polymorphic deserialization is a very handy feature that enables us write simpler and cleaner code. It is especially useful when two software components communicate with JSON messages in which the type of the object passed in the message payload may vary. Without it, we would have to implement a different endpoint for each type of object, or write a custom parser which can decide which type of object needs to be created. Anyway, thanks to Jackson we don’t worry about those things. Let’s add it to our project.</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;<br>    &lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;<br>    &lt;version&gt;2.9.7&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>We need to decorate our base type to let the Jackson know how the type information will be passed within the JSON messages. Based on that type information, Jackson will decide which type of object to create.</p><pre>@JsonTypeInfo(<br>        use = JsonTypeInfo.Id.<em>NAME</em>,<br>        property = &quot;type&quot;<br>)<br>@JsonSubTypes({<br>        @JsonSubTypes.Type(value = MSWordWriter.class, name = &quot;MICROSOFT_WORD&quot;),<br>        @JsonSubTypes.Type(value = PDFWriter.class, name = &quot;PDF&quot;)<br>        ...<br>})<br>public abstract class Writer {<br>    public abstract void write(String content);<br>}</pre><p>Now, if we serialize an instance of a Writer class, the serialized JSON string will contain “type” field with a value “PDF” if the object is an instance of PDFWriter, or “MICROSOFT_WORD” if it is a MSWordWriter and so on.</p><pre>{<br>    &quot;type&quot;: &quot;PDF&quot;<br>}</pre><p>Also it can deserialize this JSON message into a Writer object which is PDFWriter in this case.</p><h3>Back to Factory Method Implementation</h3><p>Now that we know the Jackson can handle the creation of Java objects of the correct type, the only missing part is that we need to convert the WriterType enum into a JSON string (like in the above example) so that we can write a Factory Method pattern implementation that accepts a WriterType value and produces an instance of Writer.</p><p>We first need to create a wrapper class which can be serialized into the same JSON string.</p><pre>@Value<br>public class NewWriterMessage {<br>    private WriterType type;<br>}</pre><p>Now, it is time to write the Factory Method</p><pre>import com.fasterxml.jackson.core.JsonProcessingException;<br>import com.fasterxml.jackson.databind.ObjectMapper;</pre><pre>public class WriterFactory {<br><br>    public static Writer createWriter(WriterType type) {<br>        String newObjectMessage = <em>createNewObjectMessage</em>(type);<br>        return <em>createWriter</em>(newConverterMessage);<br>    }</pre><pre>    private static String <em>createNewObjectMessage</em>(WriterType type) {<br>        NewWriterMessage message = new NewWriterMessage();<br>        message.setType(type);</pre><pre>        try {<br>            ObjectMapper mapper = new ObjectMapper();<br>            return mapper.writeValueAsString(message);<br>        } catch (JsonProcessingException e) {<br>            ...<br>        }<br>    }</pre><pre>    private static Writer <em>createWriter</em>(String message) {<br>        try {<br>            ObjectMapper mapper = new ObjectMapper();<br>            return mapper.readValue(message, Writer.class);<br>        } catch (IOException e) {<br>            ...<br>        }<br>    }<br>}</pre><p>That’s all. Very simple, isn’t it? We just convert our WriterType into JSON string and let the Jackson handle the rest. I hope you like it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57b773f5c043" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS CloudFormation: Defining Lambda Backed Custom Resources]]></title>
            <link>https://medium.com/@danismaz.furkan/aws-cloudformation-defining-lambda-backed-custom-resources-ea5d6a353cbc?source=rss-94ea17f665b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea5d6a353cbc</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-cloudformation]]></category>
            <category><![CDATA[aws-custom-resources]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Furkan Danışmaz]]></dc:creator>
            <pubDate>Fri, 29 Nov 2019 09:30:16 GMT</pubDate>
            <atom:updated>2021-12-24T04:21:42.604Z</atom:updated>
            <content:encoded><![CDATA[<p>In my <a href="https://medium.com/@danismaz.furkan/practices-for-cloud-computing-f628fee3068e">previous post,</a> I’ve mentioned about some practices to improve cost efficiency on cloud solutions. The first section in that story was about being in control of your cloud resources. Best way to achieve this is of course automating your provisioning and deployment processes.</p><p>AWS CloudFormation is an AWS service that provides a common language for defining AWS resources as a code. Using AWS CloudFormation, you can define almost any AWS resource type and also add custom business logic using custom resources.</p><p>In this story, I will not dive into details of how to define AWS resources with CloudFormation for two reasons. First, there are too many resource types to cover in one story and second, I think the AWS CloudFormation documentation is pretty clear.</p><p>This story is about defining custom resources, instead to handle custom business logic during resource provisioning or deployment. I’ll show how to trigger a lambda function from CloudFormation where we can add any custom provisioning step (like inserting or updating some records on the database) and return response back to CloudFormation.</p><h3>The CloudFormation Template</h3><p>In this CloudFormation template example there are 3 resource definitions:</p><ul><li>lambda execution role</li><li>lambda function definition</li><li>custom resource definition</li></ul><h4>Lambda Execution Role</h4><p>We need the lambda execution role to be able to invoke the lambda function.</p><pre>&quot;MyLambdaExecutionRole&quot;: {<br>  &quot;Type&quot;: &quot;AWS::IAM::Role&quot;,<br>  &quot;Properties&quot;: {<br>    &quot;AssumeRolePolicyDocument&quot;: {<br>      &quot;Statement&quot;: [<br>        {<br>          &quot;Effect&quot;: &quot;Allow&quot;,<br>          &quot;Principal&quot;: {<br>            &quot;Service&quot;: [<br>              &quot;lambda.amazonaws.com&quot;<br>            ]<br>          },<br>          &quot;Action&quot;: [<br>            &quot;sts:AssumeRole&quot;<br>          ]<br>        }<br>      ]<br>    },<br>    &quot;Policies&quot;: [<br>      {<br>        &quot;PolicyName&quot;: &quot;AllowLogging&quot;,<br>        &quot;PolicyDocument&quot;: {<br>          &quot;Statement&quot;: [<br>            {<br>              &quot;Effect&quot;: &quot;Allow&quot;,<br>              &quot;Action&quot;: [<br>                &quot;logs:CreateLogGroup&quot;,<br>                &quot;logs:CreateLogStream&quot;,<br>                &quot;logs:PutLogEvents&quot;<br>              ],<br>              &quot;Resource&quot;: &quot;arn:aws:logs:*:*:*&quot;<br>            }<br>          ]<br>        }<br>      }<br>    ],<br>    &quot;Description&quot;: &quot;A simple role for executing lambda functions with no permissions&quot;,<br>    &quot;RoleName&quot;: &quot;MyLambdaExecutionRole&quot;,<br>    &quot;Path&quot;: &quot;/my/path&quot;<br>  }<br>}</pre><h4>Lambda Function Definition</h4><p>The lambda function definition given below, points to a local jar file in the “Code” property.</p><p>Alternatively, you can upload your artifacts to an S3 bucket manually and point there in your template.</p><p>If you choose to continue with pointing to a local artifact, you should process your template with the cloudformation package command (before deploying it), which uploads the local artifacts to an S3 bucket that you specify and replaces the local artifact references in your template with that S3 location.</p><p>Either way, the IAM account that will execute the CloudFormation template, needs to have a read privilege to the corresponding S3 bucket.</p><pre>&quot;MyLambdaFunction&quot;: {<br>  &quot;Type&quot;: &quot;AWS::Lambda::Function&quot;,<br>  &quot;Properties&quot;: {<br>    &quot;FunctionName&quot;: &quot;MyLambdaFunctionName&quot;,<br>    &quot;Handler&quot;: &quot;com.mypackage.CustomResourceHandler::handleRequest&quot;,<br>    &quot;Code&quot;: &quot;target/my-artifact-jar-with-dependencies.jar&quot;,<br>    &quot;Runtime&quot;: &quot;java8&quot;,<br>    &quot;MemorySize&quot;: 128,<br>    &quot;Role&quot;: {<br>      &quot;Fn::GetAtt&quot;: [<br>        &quot;MyLambdaExecutionRole&quot;,<br>        &quot;Arn&quot;<br>      ]<br>    },<br>    &quot;Timeout&quot;: 120,<br>    &quot;Environment&quot;: {<br>      &quot;Variables&quot;: {<br>        &quot;ActiveProfiles&quot;: {<br>          &quot;Ref&quot;: &quot;ActiveProfiles&quot;<br>        }<br>      }<br>    }<br>  }<br>}</pre><h4>The Custom Resource That Triggers The Lambda Function</h4><p>The custom resource definition given below will automatically trigger the lambda function after that lambda function is created.</p><pre>&quot;MyCustomResource&quot;: {<br>    &quot;Type&quot;: &quot;Custom::LambdaInvoker&quot;,<br>    &quot;DependsOn&quot;: [<br>      &quot;MyLambdaFunction&quot;<br>    ],<br>    &quot;Properties&quot;: {<br>      &quot;ServiceToken&quot;: {<br>        &quot;Fn::GetAtt&quot;: [&quot;MyLambdaFunction&quot;,&quot;Arn&quot;]<br>      },<br>      &quot;Region&quot;: {<br>        &quot;Ref&quot;: &quot;AWS::Region&quot;<br>      },<br>      &quot;myFirstParameter&quot;: {<br>        &quot;Ref&quot;: &quot;Param1&quot;<br>      },<br>      &quot;mySecondParameter&quot;: {<br>        &quot;Ref&quot;: &quot;Param2&quot;<br>      }<br>    }<br>  }<br>}</pre><p>I passed the ARN of the lambda function to the custom resource definition as a parameter (see the ServiceToken property). By doing this, I tell the CloudFormation to invoke that lambda function during the creation, update, or deletion of this custom resource.</p><p>You can define any parameter you like in your custom resource definition. Those parameters will be passed to your lambda function within the custom resource request object.</p><p>Your lambda function will receive an input in the following format:</p><pre>{<br>  &quot;RequestType&quot;: &quot;Create&quot;,<br>  &quot;ResponseURL&quot;: &quot;http://...&quot;,<br>  &quot;StackId&quot;: &quot;stack-1&quot;,<br>  &quot;RequestId&quot;: &quot;Request-1&quot;,<br>  &quot;ResourceType&quot;: &quot;Custom&quot;,<br>  &quot;LogicalResourceId&quot;: &quot;Logical-Resource-1&quot;,<br>  &quot;ResourceProperties&quot;: {<br>    &quot;myFirstParameter&quot;: &quot;123&quot;,<br>    &quot;mySecondParameter&quot;: &quot;asd&quot;,<br>  }<br>}</pre><p>The RequestType can be either Create, Update or Delete. If you are creating a new CloudFormation stack, it will be Create. If you are updating or deleting the stack that you’ve previously created, then it will be Update or Delete correspondingly.</p><p>One thing to pay attention is the ResponseUrl. While creating, updating or deleting a custom resource, the CloudFormation will wait until you return a response to the provided ResponseURL in the request object. And you’ll not be able to delete the stack during that time period until you get timeout (which is 1 hour).</p><p>The ResourceProperties is the final field that I want to mention. ResourceProperties is a JSON object that contains the parameters you pass from your custom resource definition in your CloudFormation template.</p><p>See the <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/crpg-ref-requests.html">Custom Resource Request Fields</a> and the <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/crpg-ref-responses.html">Custom Resource Response Fields</a> for more information.</p><h4>Getting the Custom Resource Request Object and Returning Response to Given Response URL</h4><p>I’ve used the cfn-response library in my lambda function which includes Custom Resource Request and Response model as well as implementation for sending response back to the pre-signed S3 URL (the ResponseURL).</p><pre>&lt;!-- Maven Dependency --&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;com.sunrun&lt;/groupId&gt;<br>    &lt;artifactId&gt;cfn-response&lt;/artifactId&gt;<br>    &lt;version&gt;${cfn-response.version}&lt;/version&gt;<br>&lt;/dependency&gt;</pre><pre>// The handler function<br>public class CustomResourceHandler {<br><br>    public void handleRequest(final CfnRequest&lt;MyDataType&gt; request, Context context) {<br>            // Your custom operations goes here<br>            this.sendResponse(request, context, Status.SUCCESS);<br>        }<br>    }<br>}<br></pre><pre>// Sending Response to ResponseURL<br>public void sendResponse(CfnRequest&lt;MyDataType&gt; request, Context context, Status status, String reason) {<br>    CfnResponseSender sender = new CfnResponseSender();<br>    // generate your physical id<br>    sender.send(request, status, context, reason, null, physicalId);<br>}</pre><p>I hope this story helped you with defining custom resources using AWS CloudFormation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea5d6a353cbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Language Support to Spring MVC Applications]]></title>
            <link>https://medium.com/@danismaz.furkan/multi-language-support-to-spring-mvc-applications-a8afa3cc8e79?source=rss-94ea17f665b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8afa3cc8e79</guid>
            <category><![CDATA[locale]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[i18n]]></category>
            <dc:creator><![CDATA[Furkan Danışmaz]]></dc:creator>
            <pubDate>Sun, 02 Jun 2019 16:13:09 GMT</pubDate>
            <atom:updated>2020-02-04T10:15:27.652Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BJlXWtIGxpWwA1oF9BPlhw.jpeg" /></figure><h3>i18n with Spring MVC Applications</h3><p>If you want to return your text messages in a language determined by the context of a request in a Spring MVC application, there are a few steps you should follow:</p><ol><li>Create your message resource bundles and write your messages in all languages that you want your application to support.</li><li>Create a ResourceBundleMessageSource bean and register your message resource bundles.</li><li>Register a locale resolver.</li><li>Inject MessageSource bean where you want to resolve messages from message codes</li><li>Resolve messages</li></ol><p>Let’s see them in action.</p><h3>Creating Message Resource Bundles</h3><p>You may create your resource files anywhere in your classpath but it is better to put them under /resources folder or in a subfolder that is under resources like /resources/messages</p><p>For each language you want to support, you should create a different resource file with the same name having a locale postfix like below:</p><pre>/resources/messages/myapp-common.properties<br>/resources/messages/myapp-common_tr_TR.properties</pre><p>The resource file having no locale postfix will be your default locale.</p><p>If you don’t want to put all of your messages into a single file, you can create multiple message resource bundles:</p><pre>/resources/messages/myapp-common.properties<br>/resources/messages/myapp-common_tr_TR.properties<br>/resources/messages/myapp-user-management.properties<br>/resources/messages/myapp-user-management_tr_TR.properties<br>...</pre><p>Put your messages into your message resource files for each language with the same key. Messages in default language should be put into the resource file with no locale postfix:</p><pre><strong>myapp.error.email.required</strong>=Please provide your e-mail address.</pre><p>Messages in other languages should be put into the correct resource file. For example, Turkish messages should be put into the resource files with _tr_TR postfix.</p><pre><strong>myapp.error.email.required</strong>=Lütfen e-posta adresinizi giriniz.</pre><p>If you are using IntelliJ, it has built-in support for resource bundles that adds the capability of modifying messages of a resource bundle for all languages in a single view. Also, eclipse has a plugin for it but you need to install it manually.</p><h3>Creating the ResourceBundleMessageSource Bean</h3><p>In a configuration class of your application (a class in your classpath annotated with @Configuration) you should create a MessageSource bean and load your resource bundles so that you can inject and use it anywhere you want to resolve messages.</p><pre>@Bean<br><strong>public </strong>MessageSource messageSource() {<br>    ResourceBundleMessageSource messageSource = <strong>new </strong>ResourceBundleMessageSource();<br>    messageSource.addBasenames(<strong>&quot;messages/myapp-common&quot;</strong>);<br>    messageSource.addBasenames(<strong>&quot;messages/myapp-user-management&quot;</strong>);<br>    messageSource.setDefaultEncoding(<strong>&quot;UTF-8&quot;</strong>);<br>    <strong>return </strong>messageSource;<br>}</pre><p>Notice that you don’t need to register your resource bundle files for each locale separately. Add them without their locale postfix.</p><h3>The Locale Resolver Bean</h3><p>The locale resolver bean is the one that decides the locale of your request. There are built-in locale resolvers of Spring but you may also write your own by implementing the LocaleResolver interface of spring-webmvc.</p><p>Below is a sample implementation that resolves the locale from the Accept-Language request header.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45ea06e3b9d278196994d182588b6a38/href">https://medium.com/media/45ea06e3b9d278196994d182588b6a38/href</a></iframe><p>Whether you implement your own or use an existing one you need to create a locale resolver bean you want to use.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5652a1875cf836915084109092cc4380/href">https://medium.com/media/5652a1875cf836915084109092cc4380/href</a></iframe><h3>Injecting MessageSource and Resolving Messages</h3><p>Now we are ready to resolve messages. If you have used a LocaleResolver that decides the locale from the request header, then your messages will be in the language based on the request header you are using. If none provided, then the default locale will be used.</p><p>While resolving messages, you need the MessageSource bean and the key of the message you want to resolve.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c9917e14852d2b41d7d08beacafb080/href">https://medium.com/media/4c9917e14852d2b41d7d08beacafb080/href</a></iframe><p>If you want your messages to accept arguments, the MessageSource bean lets you do that.</p><pre><strong>myapp.error.username.length.min</strong>=Username cannot be less than {0} characters</pre><p>The second argument of the getMessage method is an object array where you can provide arguments to your message like below.</p><pre><strong>String </strong>message = <strong>this</strong>.<strong>messageSource</strong>.getMessage(&quot;myapp.error.username.length.min&quot;, new Object[] { 4 }, <strong>this</strong>.locale());</pre><h3>Using Message Codes on Bean Validation</h3><p>For server side validation of data, we can use existing JSR-303 Annotations like @NotNull, @NotBlank, @NotEmpty, @Positive, @PositiveOrZero, @Negative, @NegativeOrZero, @Min, @Max, @Size, @Future, @FutureOrPresent, @Past, @PastOrPresent, @Email, etc…</p><p>Those annotations has message attribute which is added to the object or field errors of the binding result when the corresponding object or field does not match the validation criteria.</p><pre>public class Person {<br>    <br>    @Size(min=4, message=&quot;Username cannot be shorter than 4 characters&quot;)<br>    private String username;</pre><pre>    ...<br>}</pre><p>You can validate a Person object in the request body for example in a Spring MVC application by just adding @Valid annotation in front of it.</p><pre>@RestController<br>@RequestMapping(&quot;/person&quot;)<br>public class PersonController {</pre><pre>  @PostMapping<br>  public ResponseEntity create(@Valid @RequestBody Person person) {<br>     ...<br>  }</pre><p>You can use message codes inside validation annotations instead of hard-coded string values like below:</p><pre>public class Person {<br>    <br>  @Size(min=4, message=&quot;{app.validation.username}&quot;)<br>  private String username;</pre><pre>  ...<br>}</pre><p>Notice that, either the name of the resource bundle need to be ValidationMessages like ValidationMessages.properties, ValidationMessages_tr_TR.properties or you need to set the validation message source of the LocalValidatorFactoryBean like below:</p><pre>@Bean<br>public LocalValidatorFactoryBean getValidator() {<br>  LocalValidatorFactoryBean validatorFactory<br>     = new LocalValidatorFactoryBean();<br>  validatorFactory.setValidationMessageSource(messageSource());<br>  return validatorFactory;<br>}</pre><p>Hope this helps returning messages to clients based on the locale of the requests.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8afa3cc8e79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Cloud Config with HashiCorp Vault Backend]]></title>
            <link>https://medium.com/@danismaz.furkan/spring-cloud-config-with-vault-backend-766b95676005?source=rss-94ea17f665b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/766b95676005</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[spring-cloud-config]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[vault]]></category>
            <dc:creator><![CDATA[Furkan Danışmaz]]></dc:creator>
            <pubDate>Thu, 07 Feb 2019 21:27:58 GMT</pubDate>
            <atom:updated>2019-09-24T10:11:04.014Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kkHZ6pBWtmLiVGvCCsFrDw.png" /><figcaption>Spring Cloud Config with HashiCorp Vault Backend</figcaption></figure><p>As I mentioned in one of my previous <a href="https://medium.com/@danismaz.furkan/spring-cloud-config-with-file-system-backend-c18ae16b7ad5">posts</a>, with Spring Cloud Config we can externalize &amp; centralize our configurations and use them in any of our Java application.</p><p>Currently, with Spring Cloud Config, we have several backend options like Git, File System, JDBC or Vault. If your production environment is AWS, I think using JDBC backend or Vault backend are good options.</p><p>Reasons:</p><ul><li>If you choose to use file system backend you will end up with putting your configuration files into some resource files in your classpath. Which means if you need to change the values in your configuration files, you need to restart your cloud config server.</li><li>Your cloud may not access your source code repository</li><li>Currently, Spring Cloud Config does not support AWS S3 backend</li></ul><p>In this story, I’ll talk about Vault and Spring Cloud config with Vault backend.</p><h3>So, let’s start with Vault. What is Vault?</h3><p>Description from Vault’s official website.</p><blockquote>Vault is a tool for securely accessing <em>secrets</em>. A secret is anything that you want to tightly control access to, such as API keys, passwords, or certificates. Vault provides a unified interface to any secret while providing tight access control and recording a detailed audit log.</blockquote><p><a href="https://www.hashicorp.com/products/vault/">https://www.hashicorp.com/products/vault/</a></p><h3>Spring Cloud Config Server with Vault Backend</h3><h4>Vault Installation</h4><p>First, we need to download and install Vault to our local machine. Basically, you need to:</p><ul><li>download vault</li><li>unzip the downloaded zip</li><li>add the executable vault location to your PATH environment variable</li><li>[OPTIONAL] you can also install autocomplete feature</li></ul><p>You can follow the installation documentation <a href="https://learn.hashicorp.com/vault/getting-started/install">https://learn.hashicorp.com/vault/getting-started/install</a></p><h4>Creating a Vault Server</h4><p>Now that we have installed vault to our local machine, we need to start a vault server. We can use the dev server for learning purposes but it is not recommended to use it in the production environment.</p><pre>&gt; vault server -dev</pre><p>This will output unseal key and root token. Copy those keys to somewhere and execute the following commands:</p><pre>&gt; export VAULT_DEV_ROOT_TOKEN_ID=&quot;your-secret&quot;<br>&gt; export VAULT_ADDR=&#39;<a href="http://127.0.0.1:8200&#39;">http://127.0.0.1:8200&#39;</a></pre><p>Now, we can test our vault server with:</p><pre>&gt; vault status</pre><p>I suggest you analyze vault further, understand its basic commands and secret engines. All the information you need is well explained in the <a href="https://learn.hashicorp.com/vault/">documentation</a>.</p><h4>Let’s Store Some Secrets</h4><p>We can store key-value pairs with the vault kv put command like below:</p><pre>&gt; vault kv put secret/myapp key1=value1</pre><p>You can use the vault kv get command or your browser to see your secrets.</p><pre>&gt; vault kv get secret/myapp</pre><p>or from your browser <a href="http://localhost:8200.">http://localhost:8200.</a> You can enter the application with your root token.</p><h4>Spring Cloud Config Server</h4><p>Below is provided dependencies for Maven projects</p><pre>&lt;dependencyManagement&gt;<br>    &lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-cloud-config-dependencies&lt;/artifactId&gt;<br>            &lt;version&gt;2.1.0.RELEASE&lt;/version&gt;<br>            &lt;type&gt;pom&lt;/type&gt;<br>            &lt;scope&gt;import&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br>&lt;/dependencyManagement&gt;<br><br>&lt;dependencies&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-cloud-config-server&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p>We just need to create a class with @SpringBootApplication and @EnableConfigServer annotations and write a main method in it like below:</p><pre>@SpringBootApplication<br>@EnableConfigServer<br>public class App {<br><br>    public static void main(String[] args) {<br>        SpringApplication.<em>run</em>(App.class);<br>    }<br>}</pre><p>A sample configuration is given below. Notice that the default spring.cloud.config.server.kv-version is 1. If you are using Vault 0.10.0 or later (most probably you are) then you should set it to 2</p><pre><strong>spring.cloud.config.server</strong>:<br>  <strong>vault</strong>:<br>    <strong>port</strong>: 8200<br>    <strong>host</strong>: 127.0.0.1<br>    <strong>scheme</strong>: http<br>    <strong>authentication</strong>: TOKEN<br>    <strong>token</strong>: &lt;your-root-token&gt;<br>    <strong>kv-version</strong>: 2</pre><h4>Getting Properties from Cloud Config Server</h4><p>Before writing a Cloud Config client, let’s test our config server via an HTTP request. You can use CURL, or some REST client tool like POSTMAN.</p><pre>$ curl -X &quot;GET&quot; &quot;http://localhost:8888/myapp/default&quot; -H &quot;X-Config-Token: yourtoken&quot;</pre><p>This should return a response like the following:</p><pre>{<br>    &quot;name&quot;: &quot;myapp&quot;,<br>    &quot;profiles&quot;: [<br>        &quot;default&quot;<br>    ],<br>    &quot;label&quot;: null,<br>    &quot;version&quot;: null,<br>    &quot;state&quot;: null,<br>    &quot;propertySources&quot;: [<br>        {<br>            &quot;name&quot;: &quot;vault:myapp&quot;,<br>            &quot;source&quot;: {<br>                &quot;key1&quot;: &quot;value1&quot;<br>            }<br>        }<br>    ]<br>}</pre><p>When you use a cloud config backend that is not in your config server’s classpath, you don’t need to restart your config server when you need to make changes in your configurations. You can even refresh your clients in such cases without restarting them if your clients use @RefreshScope annotations for the values loaded from the config server. You just need to call the /refresh endpoint of Spring Boot Actuator.</p><h4>References</h4><ul><li><a href="https://cloud.spring.io/spring-cloud-config/multi/multi__spring_cloud_config_server.html">2. Spring Cloud Config Server</a></li><li><a href="https://learn.hashicorp.com/vault/">Vault Curriculum - HashiCorp Learn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=766b95676005" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Injection with Dagger]]></title>
            <link>https://medium.com/@danismaz.furkan/dependency-injection-with-dagger-5694f0f6fb84?source=rss-94ea17f665b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5694f0f6fb84</guid>
            <category><![CDATA[ioc]]></category>
            <category><![CDATA[inversion-of-control]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[dagger-2]]></category>
            <dc:creator><![CDATA[Furkan Danışmaz]]></dc:creator>
            <pubDate>Sun, 11 Nov 2018 18:11:37 GMT</pubDate>
            <atom:updated>2018-11-25T11:47:57.100Z</atom:updated>
            <content:encoded><![CDATA[<p>Spring Framework is a great library that comes in handy for many cases. While helping you to solve problems in different domains like data persistence and transactions, request handling mechanism, dependency injection, aspect-oriented programming, authentication/authorization, microservices architecture and many more, it also lets you build more structured, robust and more maintainable code. People usually get more and more fascinated as they continue to use Spring Framework and are disposed to add it to their project as a first job.</p><p>Spring Framework (along with its power) is a little bit kind of heavy. If you intend to use it just for dependency injection, for example, you may consider using other lightweight IoC frameworks like Guice or Dagger instead. Consider a serverless architecture. Your functions need to boot-up as fast as possible since the speed &amp; memory usage matters as they cost money to you.</p><p>If you search for IoC benchmarks on the internet or build your own, you will find out that the Dagger is the most suitable option for Java applications (apart from not using a framework at all) when the performance is the most critical thing that you should consider. In this story, I will show how to use Dagger with an example.</p><h4>A Maven Java Project with Dagger</h4><p>You need to add the Dagger dependency to the dependency list:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.google.dagger&lt;/groupId&gt;<br>    &lt;artifactId&gt;dagger&lt;/artifactId&gt;<br>    &lt;version&gt;${dagger.version}&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Then you need to configure the annotation processor:</p><pre>&lt;plugin&gt;<br>    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>    &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;<br>    &lt;version&gt;${maven-compiler-plugin.version}&lt;/version&gt;<br>    &lt;configuration&gt;<br>        &lt;annotationProcessorPaths&gt;<br>            &lt;path&gt;<br>                &lt;groupId&gt;com.google.dagger&lt;/groupId&gt;<br>                &lt;artifactId&gt;dagger-compiler&lt;/artifactId&gt;<br>                &lt;version&gt;${dagger.version}&lt;/version&gt;<br>            &lt;/path&gt;<br>        &lt;/annotationProcessorPaths&gt;<br>    &lt;/configuration&gt;<br>&lt;/plugin&gt;</pre><h4>The Dagger @Component</h4><p>Dagger generates code (at compile time) about how to create objects that are to be injected when needed based on the configurations you make in your code.</p><p>During compile time, Dagger searches for @Component annotated interfaces. When it finds one, it generates a class with the same name prefixed with Dagger implementing that interface and a static create() method that creates an instance of it. Those @Component annotated interfaces are the places where you need to define the injectable objects.</p><pre>@Component<br>public interface IoCContainer {<br>    <br>    MyService myService();<br><br>}</pre><p>You just need to write an abstract method without any parameter and with a return type of your desired object. If you don’t do that, Dagger won’t generate any code that creates object of that type.</p><p>Note that, the class that you declare to be injectable needs @Inject annotation on top of its constructor. You’ll get compiler error otherwise.</p><pre>public class MyService {<br><br>    @Inject<br>    public MyService() {<br>        ...<br>    }<br><br>    ...<br>}</pre><p>You can also inject objects to injectable objects:</p><pre>public class MyService {<br><br>    private MyBusinessLogic businessLogic;<br><br>    @Inject<br>    public MyService(MyBusinessLogic businessLogic) {<br>        this.businessLogic = businessLogic;<br>        ...<br>    }<br><br>    ...<br>}<br><br>public class MyBusinessLogic {<br><br>    @Inject<br>    public MyBusinessLogic() {<br>    }<br><br>    ...<br>}</pre><p>Notice that, again I decorated the constructor of the second class with @Inject annotation. Without it, dagger won’t be able to inject</p><h4>How to Use</h4><p>As I said above, for each @Component annotated interface, you’ll get a class with the same name prefixed with Dagger implementing that interface. For the example given above, we’ll get DaggerIoCContainer class and we can create an instance of it with its create() method:</p><pre>public static void main(String[] args) {<br>    IoCContainer ioc = DaggerIoCContainer.create();<br>    MyService myService = ioc.myService();<br>}</pre><h4>Modules</h4><p>The above example shows the simplest case of injecting dependencies. But what about:</p><ul><li>when we need to inject an instance of an interface?</li><li>when we need to inject a class of a third-party library that we cannot modify (Decorate its construtor with @Inject)?</li><li>when we need to inject an object that needs to be configured first?</li></ul><p>In such cases, we need to help Dagger and define how to construct objects to be injected with @Proivdes annotated methods.</p><pre>public interface MyService2 {<br>    ...<br>}<br><br>public class MyService2Impl implements MyService2 {<br>    ...<br>    <br>    @Inject<br>    public MyServiceImpl() {<br>    }<br><br>    ...<br>}<br><br>@Module<br>public class SampleDaggerModule {<br><br>    @Provides<br>    @Singleton<br>    public static MyService2 myService2() {<br>        return new MyService2Impl();<br>    }<br><br>    ...<br>}</pre><p>We can define how to construct objects that we need and configure them before being injected to other objects. To do so, we just need to decorate the methods that returns such objects with @Provides annotation and decorate the containing class with @Module. All @Provides annotated methods should belong to a @Module annotated class.</p><p>To make the dagger be aware of such module, we need to add it to the modules property of @Component annotation.</p><pre>@Singleton<br>@Component(modules = SampleDaggerModule.class)<br>public interface IoCContainer {<br>   ...<br>}</pre><h4>Final Words</h4><ul><li>Dagger is a very lightweight dependency injection framework</li><li>It is compatible with JSR-330 standard injection annotations.</li><li>It doesn’t support private field injection</li><li>We need to decorate the constructor of the classes that we want to be injectable with the @Inject annotation.</li><li>We need to write @Module annotated classes with @Provides annotated methods when @Inject is not sufficient.</li></ul><p>github: <a href="https://github.com/fdanismaz/java/tree/master/dagger">https://github.com/fdanismaz/java/tree/master/dagger</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5694f0f6fb84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Executing Batch Jobs with Spring-Batch]]></title>
            <link>https://medium.com/@danismaz.furkan/executing-batch-jobs-with-spring-batch-1d0430910f2e?source=rss-94ea17f665b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d0430910f2e</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[spring-batch]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Furkan Danışmaz]]></dc:creator>
            <pubDate>Sat, 27 Oct 2018 09:56:33 GMT</pubDate>
            <atom:updated>2018-10-27T16:50:33.400Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever need to execute a batch job with one or more steps to be processed sequentially or in parallel? Have you ever need to process your incoming data chunk by chunk? Spring Batch is what you need when you deal with such problems. It provides great facilities for handling very large amount of data.</p><p>In this story, I will explain the key concepts of spring batch with examples.</p><h4>Job</h4><p>The heart of spring-batch is Job which reprensents a batch job containing one or more steps that can be executed sequentially or in parallel.</p><h4>Step</h4><p>A step is simply an independently executable part of a job. Spring batch framework encourages you to divide your business logic into multiple parts (steps) which you can manage and test in isolation.</p><p>A step consists of:</p><ul><li>a reader</li><li>a processor</li><li>a writer.</li></ul><h4>The Reader</h4><p>A reader of a step is responsible for reading data from your data source and feed your processor. You can write your own reader classes or you can use an existing one like FlatFileItemReader&lt;T&gt;. Readers of steps should implement the ItemReader&lt;T&gt; interface.</p><h4>The Processor</h4><p>A processor of a step is where you write your custom business logic. It should implement the ItemProcessor&lt;I, O&gt; interface which has the process method being responsible for processing just one item of type I and return an object of type O as a result.</p><p>Below is a one sample processor.</p><pre>public class LogProcessor implements ItemProcessor&lt;Log, Message&gt; {</pre><pre>    @Override<br>    public Message process(Log log) throws Exception {<br>        log.info(&quot;Converting log into message&quot;);<br>        Message message = this.createMessageFromLog(log);<br>        return message;<br>    }<br>}</pre><h4>The Writer</h4><p>A writer is responsible for writing the output of your processor to some stream or a place. It should implement the ItemWriter&lt;T&gt; interface. For example, you can implement the ItemStreamWriter&lt;T&gt; interface which is an extension to ItemWriter&lt;T&gt; and write your results to a FileOutputStrem like the following:</p><pre>@Slf4j<br><strong>public class </strong>MessageStreamWriter <strong>implements <br>                                   </strong>ItemStreamWriter&lt;Message&gt; {<br><br>    <strong>private </strong>OutputStream <strong>outputStream</strong>;<br><br>    @Override<br>    <strong>public void </strong>open(ExecutionContext executionContext) <strong>throws </strong>ItemStreamException {<br>        <strong>try </strong>{<br>            File file = <strong>new </strong>File(System.<em>getProperty</em>(<strong>&quot;user.dir&quot;</strong>) + <strong>&quot;/output.txt&quot;</strong>);<br>            <strong>if </strong>(!file.exists()) {<br>                file.createNewFile();<br>            }<br><br>            <strong>this</strong>.<strong>outputStream </strong>= <strong>new </strong>FileOutputStream(file);<br>        } <strong>catch </strong>(Exception e) {<br>            <strong>throw new </strong>ItemStreamException(e.getMessage(), e);<br>        }<br>    }<br><br>    @Override<br>    <strong>public void </strong>update(ExecutionContext executionContext) <strong>throws </strong>ItemStreamException {<em><br>    </em>}<br><br>    @Override<br>    <strong>public void </strong>close() <strong>throws </strong>ItemStreamException {<br>        <strong>if </strong>(<strong>this</strong>.<strong>outputStream </strong>!= <strong>null</strong>) {<br>            <strong>try </strong>{<br>                <strong>this</strong>.<strong>outputStream</strong>.close();<br>            } <strong>catch </strong>(IOException e) {<br>                <strong><em>log</em></strong>.error(<strong>&quot;Cannot close output stream&quot;</strong>);<br>            }<br>        }<br>    }<br><br>    @Override<br>    <strong>public void </strong>write(List&lt;? <strong>extends </strong>Message&gt; list) <br>        <strong>throws </strong>Exception {</pre><pre>        list.stream().forEach(x -&gt; {<br>            <strong>try </strong>{<br>                <strong>this</strong>.<strong>outputStream</strong>.write(<br>                     ((Message) x).toString().getBytes());<br>            } <strong>catch </strong>(IOException e) {<br>                <strong><em>log</em></strong>.error(<strong>&quot;Cannot write message&quot;</strong>);<br>            }<br>        });<br>    }<br>}</pre><p>Remember that a reader, a processor and a writer form a <strong>Step</strong>. Once you have defined your reader, processor and writer you can build your step object with StepBuilderFactory.</p><pre>@Autowired<br><strong>private </strong>StepBuilderFactory <strong>stepBuilderFactory</strong>;</pre><pre>@Autowired<br><strong>private</strong> LogProcessor <strong>logProcessor</strong>;</pre><pre>@Autowired<br><strong>private</strong> MessageStreamWriter <strong>messageStreamWriter</strong>;</pre><pre>@Bean<br>@Qualifier(&quot;logToMessageConverterStep&quot;)<br><strong>public </strong>Step logToMessageConverter(MessageStreamWriter writer) {<br>    <strong>return this</strong>.<strong>stepBuilderFactory</strong>.get(<strong>&quot;logToMessage&quot;</strong>)<br>            .&lt;Log, Message&gt;chunk(10)<br>            .reader(<strong>this</strong>.reader())<br>            .processor(<strong>this.</strong>logProcessor)<br>            .writer(<strong>this</strong>.messageStreamWriter)<br>            .build();<br>}</pre><p>After defining your steps like above, it is time to build your jobs:</p><pre>@Autowired<br>@Qualifier(&quot;logToMessageConverterStep&quot;)<br><strong>private</strong> Step <strong>logToMessageConverter;</strong></pre><pre>@Bean<strong><br>public </strong>Job logToMessageConverterJob(<br>             <strong>MyJobExecutionListener</strong> listener) {</pre><pre>    <strong>return this</strong>.<strong>jobBuilderFactory</strong>.get(<strong>&quot;logToMessageConverterJob&quot;</strong>)<br>            .listener(listener)<br>            .flow(<strong>this</strong>.<strong>logToMessageConverter</strong>)<br>            .end()<br>            .build();<br>}</pre><p>Notice that in the example above, a listener is attached to the job. While building your Job, you can provide a JobExecutionListener where you can run your custom business logic.</p><pre><strong>public class </strong>MyJobExecutionListener <strong>extends <br>    </strong>JobExecutionListenerSupport {<br><br>    @Override<br>    <strong>public void </strong>afterJob(<strong>JobExecution</strong> jobExecution) {<br>        <strong>if </strong>(jobExecution.getStatus() == BatchStatus.<strong><em>COMPLETED</em></strong>) {<br>            <strong><em>log</em></strong>.info(<strong>&quot;JOB COMPLETED !!!&quot;</strong>);<br>        }<br>    }<br>}</pre><h3>Summary</h3><p>With Spring Batch, you can:</p><ul><li>execute your custom business logic on a very large amount of data in a very structured, manageable and robust way.</li><li>divide your logic into separate and independently executable steps</li><li>write tests and validate each step in isolation</li><li>build flows where you can execute your steps sequentially or in parallel</li><li>manage (and change when you need) the flow of your logic as easily as it can be from one place</li><li>manage job executions (start, stop, retry, pause, resume, skip)</li></ul><p>github: <a href="https://github.com/fdanismaz/java/tree/master/spring-batch">https://github.com/fdanismaz/java/tree/master/spring-batch</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d0430910f2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic CSRF Attack Simulation & Protection with Spring Security]]></title>
            <link>https://medium.com/@danismaz.furkan/basic-csrf-attack-simulation-protection-with-spring-security-82c37810a90?source=rss-94ea17f665b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/82c37810a90</guid>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[csrf]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Furkan Danışmaz]]></dc:creator>
            <pubDate>Tue, 16 Oct 2018 19:11:13 GMT</pubDate>
            <atom:updated>2019-09-24T10:14:45.728Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QLJPykCtpFg2pf_61ITtKQ.jpeg" /><figcaption>Cross-Site Request Forgery Attack</figcaption></figure><p>With its simplest form, CSRF attacks make you execute unwanted operations without your notice. In this story, I will try to explain what CSRF is and how it works with an example.</p><p>Suppose that you have an application with protected resources, meaning that you want to prevent unauthorized accesses. So, you have decided to secure your resources to prevent unauthorized access but still, you’re vulnerable to CSRF attacks. How?</p><h4>A Sample Scenario</h4><ol><li>You have an application with endpoints which you want to prevent unauthorized access. Therefore, you have secured your resources with server-side session management.</li><li>You have a page including a form where your users submit data which results in the execution of a task</li><li>There is an application prepared by an attacker in which he/she hides a similar form and a tricky button which submits the form with some values in it</li><li>A user of your system visits your app and logs in.</li><li>The same user visits the application of the attacker and clicks the tricky button without being aware of what it actually does.</li></ol><h4>Outline</h4><ol><li>Creating an application with Spring Boot — The actual application</li><li>Protect the resources of the application against unauthorized access with Spring Security</li><li>Disable the CSRF protection of Spring Security for demonstration purposes (because it is enabled by default)</li><li>Create another application with Spring Boot — The attacker’s application</li><li>Simulate a CSRF attack</li><li>Enable the CSRF protection back and see the result.</li></ol><p>Before enabling the CSRF protection back, the attacker will succeed to make users send requests to your application because:</p><ul><li>Your actual application will think that your users being attacked sent requests intentionally</li><li>Your actual application will not prompt username and password since the users being attacked are actually authenticated</li></ul><h4>The Actual Application</h4><p>Dependencies:</p><pre>&lt;dependencies&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-web&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.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-thymeleaf&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p>Security Config:</p><pre>@Configuration<br>public class SecurityConfig extends WebSecurityConfigurerAdapter {</pre><pre>public AuthenticationProvider authenticationProvider() {<br>        return new SampleAuthenticationProvider();<br>    }</pre><pre>    @Override<br>    protected void configure(AuthenticationManagerBuilder auth) throws Exception {<br>        auth.authenticationProvider(this.authenticationProvider());<br>    }</pre><pre>    @Override<br>    protected void configure(HttpSecurity http) throws Exception {<br>        http.authorizeRequests()<br>                .anyRequest().authenticated()<br>                .and()<br>                .httpBasic();</pre><pre>        http.csrf().disable(); // For demonstrating purposes<br>    }<br>}</pre><p>Sample authentication provider:</p><pre>public class SampleAuthenticationProvider implements AuthenticationProvider {<br>    @Override<br>    public Authentication authenticate(Authentication authentication) throws AuthenticationException {<br>        String username = authentication.getName();<br>        String password = authentication.getCredentials().toString();</pre><pre>        if (this.validateCredentials(username, password)) {<br>            return new UsernamePasswordAuthenticationToken(username, password, new ArrayList&lt;&gt;());<br>        }</pre><pre>        return null;<br>    }</pre><pre>private boolean validateCredentials(String username, String password) {<br>        return username.equals(&quot;johndoe&quot;) &amp;&amp; password.equals(&quot;password&quot;);<br>    }</pre><pre>    @Override<br>    public boolean supports(Class&lt;?&gt; authentication) {<br>        return authentication.equals(UsernamePasswordAuthenticationToken.class);<br>    }<br>}</pre><p>Protected Resource</p><pre>@Controller<br>@RequestMapping(&quot;/account&quot;)<br>public class AccountController {</pre><pre>    @GetMapping<br>    public String transferMoney() {<br>        return &quot;account&quot;;<br>    }</pre><pre>    @PostMapping(&quot;/transfer&quot;)<br>    public String transfer() {<br>        return &quot;success&quot;;<br>    }<br>}</pre><p>The entry point:</p><pre>@SpringBootApplication<br>public class App {</pre><pre>    public static void main(String[] args) {<br>        SpringApplication.run(App.class);<br>    }<br>}</pre><p>/resources/templates/account.html</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html xmlns:th=&quot;<a href="http://www.thymeleaf.org/">http://www.thymeleaf.org</a>&quot; lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;title&gt;Actual Application&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;</pre><pre>    &lt;form action=&quot;/account/transfer&quot; method=&quot;post&quot;&gt;<br>        &lt;input type=&quot;submit&quot; value=&quot;Transfer Money&quot;&gt;<br>    &lt;/form&gt;</pre><pre>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>By default, csrf protection is enabled in Spring Security but we’ve closed it for demonstration purposes.</p><h4>The Attacker’s App</h4><p>Dependencies:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-web&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-thymeleaf&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Controller rendering the tricky page:</p><pre>@Controller<br>@RequestMapping(&quot;/home&quot;)<br>public class HomeController {</pre><pre>    @GetMapping(&quot;/index&quot;)<br>    public String index() {<br>        return &quot;index&quot;;<br>    }<br>}</pre><p>The tricky page:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;title&gt;Attacker Application&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;form action=&quot;http://localhost:9090/account/transfer&quot; method=&quot;post&quot;&gt;<br>        &lt;input type=&quot;submit&quot; value=&quot;Tricky Button&quot;&gt;<br>    &lt;/form&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Notice the URL of the form. It is configured to send requests to your actual application.</p><p>The entry point:</p><pre>@SpringBootApplication<br>public class App {</pre><pre>    public static void main(String[] args) {<br>        SpringApplication.run(App.class);<br>    }<br>}</pre><h4>Test Steps</h4><ol><li>Run the actual application</li><li>Try to go to the protected resource. The browser will ask you for username and password. Go ahead and login to the system</li><li>Run the attacker’s application</li><li>Open the attacker’s application homepage</li><li>Click on the Tricky button</li></ol><p>You’ll see that the attacker’s app will successfully make a POST request to the protected resource in your actual app.</p><h4>How to prevent?</h4><p>As I said before, Spring Security has built-in protection for CSRF attacks. So you need not do anything for your form posts. However, you need to add CSRF header before sending any AJAX requests.</p><p>For this example:</p><ul><li>Delete the line that disables CSRF in the SecurityConfig class of the actual application.</li><li>Change the account.html file in the actual application from:</li></ul><pre>&lt;form action=&quot;/account/transfer&quot; method=&quot;post&quot;&gt;<br>    &lt;input type=&quot;submit&quot; value=&quot;Transfer Money&quot;&gt;<br>&lt;/form&gt;</pre><p>to</p><pre>&lt;form th:action=&quot;@{/account/transfer}&quot; method=&quot;post&quot;&gt;<br>    &lt;input type=&quot;submit&quot; value=&quot;Transfer Money&quot;&gt;<br>&lt;/form&gt;</pre><p>Now, restart your applications and execute the same test scenario again. You will be able to use your actual application successfully but this time you will get an error when you click on the Tricky button.</p><h4>What has changed?</h4><p>Run your actual application and inspect the account.html in the browser. You should see a hidden element like below inside your&lt;form&gt; element:</p><pre>&lt;input type=&quot;hidden&quot; name=&quot;_csrf&quot; value=&quot;c621d314-e95f-4955-b4cb-355a00bc4464&quot;&gt;</pre><p>Definitely, we didn’t put any HTML code like this into our account.html. This is done during the server side rendering operation. Since there is no way that the attacker app can know this UUID, it can not make successful requests to your actual application. Therefore, you are now protected against CSRF attacks.</p><p>I hope this helps you to understand CSRF attacks and how to protect your application against them.</p><p>github: <a href="https://github.com/fdanismaz/java/tree/master/csrf-protection">https://github.com/fdanismaz/java/tree/master/csrf-protection</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82c37810a90" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>