<?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 Supun Bhagya on Medium]]></title>
        <description><![CDATA[Stories by Supun Bhagya on Medium]]></description>
        <link>https://medium.com/@supunbhagya?source=rss-d7f113754551------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TpsHnPX1V12FSZJC8j29UQ.jpeg</url>
            <title>Stories by Supun Bhagya on Medium</title>
            <link>https://medium.com/@supunbhagya?source=rss-d7f113754551------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:26:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@supunbhagya/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[Request-driven vs Event-driven Microservices]]></title>
            <link>https://supunbhagya.medium.com/request-driven-vs-event-driven-microservices-7b1fe40dccde?source=rss-d7f113754551------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b1fe40dccde</guid>
            <category><![CDATA[microservices-pattern]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Supun Bhagya]]></dc:creator>
            <pubDate>Sun, 30 Aug 2020 13:10:06 GMT</pubDate>
            <atom:updated>2020-11-09T23:02:58.144Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CyeQxSSiaYcNCV-sVFkdow.png" /></figure><p>The topic “microservice” has become popular among developers and organizations. There are different ways to design microservices, this article compares a couple of main microservice architectures patterns, request-driven and event-driven.</p><p>First of all, what is a microservice?</p><p><em>It is an application which is loosely coupled, highly testable, independently deployed, defining clear business domain boundary and maintain by a relatively small team</em></p><p><strong>Request Driven Microservices</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CvC63uCq6ItlzAXXNoTrKA.jpeg" /><figcaption>Request driven microservice pattern</figcaption></figure><p>In the request-response based approach, services communicate using HTTP or RPC. These days, in most cases, this is done using REST HTTP calls.</p><p>Let&#39;s consider a simple e-commerce use case, “Order Confirmation”. As demonstrated in the above figure, Order service confirmed an order and call other microservices synchronously.</p><p>This kind of architecture named <strong>“Service Orchestration”</strong> since there is one service to manage the flow and instruct other services to perform actions. In our example, the Order Service manages the flow and it acts as the <em>“orchestrator”</em> for the flow.</p><p><strong>Request Driven Microservices Benefits and Tradeoffs</strong></p><p><strong>Benefits</strong></p><ul><li>There is a clear control of the flow, looking at the code of the orchestrator, we can determine the sequence of the actions.</li></ul><p><strong>Tradeoffs</strong></p><ul><li>If one of the dependent services is down, there is a high chance to exclude calls to the other services.</li><li>If there is a failure in the Orchestrator service, it will be a single point of failure. When this service is down, the entire flow won’t be executed.</li><li>There is no easy way to recover the actions by reprocessing failed calls to dependent services.</li><li>Rest API of the dependent services cannot be easily modified. If it is changed, consumers of the API also need to be modified. Therefore, microservices are not loosely coupled.</li></ul><p><strong>Event-Driven Microservices</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FjPMcx01iZwvesUvgKm%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fchicagodancecrash-jPMcx01iZwvesUvgKm&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2FjPMcx01iZwvesUvgKm%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/c53f1ef14f1f822c4560b830350cbcb7/href">https://medium.com/media/c53f1ef14f1f822c4560b830350cbcb7/href</a></iframe><p>The best way to visualize the Event-driven microservice pattern by using a <strong>choreography dance. </strong>Each dancer knows their role and what to do next, and how to react for an event, there is no instructor or orchestrator to tell what they should do. Similarly, each microservice knows their role and what to do based on an event that occurred in the application. Also, the key principle here is services execute their actions <em>asynchronously</em>.</p><p>Let&#39;s convert our previous request-driven application to an event-driven e-commerce application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xq5m9kLfpkv2l9rcxdtivA.jpeg" /><figcaption>Event-driven microservice pattern</figcaption></figure><p>As you can see, Order service produces an event “OrderCreated” and publish to the event stream. (The event stream is another application that is purely designed to host event streams. Kafka and AWS Kinesis are good examples of event stream applications.)</p><p><strong>Event-Driven Microservices Benefits and Tradeoffs</strong></p><p><strong>Benefits</strong></p><ul><li>The producer service of the events does not know about its consumer services. On the other hand, the consumers also do not necessarily know about the producer. As a result, services can deploy and maintain independently. This is a key requirement to build loosely coupled microservices.</li><li>As you can see in the above figure, multiple services can consume the same event. Therefore, the producer just needs to publish an event to the event stream.</li><li>Asynchronous nature in event-driven architecture allows different services to consume events according to their processing power. This behaviour removes the tightly coupled communication mechanism in the request-response pattern. In the event-driven pattern, the producer does not need to wait for a response from the consumer.</li><li>Much easier to add, remove or modify services. In other words, this architecture allows to plug or unplug a service without modifying other services.</li><li>If a service goes offline while producer process events, it can replay (rewind) those events once it came back online</li></ul><p><strong>Tradeoffs</strong></p><ul><li>There is no clear central place (orchestrator) defining the whole flow.</li><li>Managing distributed transaction could be complex. There are multiple services that consume an event, as a result, if an exception occurred in one of the services, what should happen to the entire flow or implementing a rollback process is challenging.</li></ul><p><strong>A mix of two patterns</strong></p><p>What happens if an event does not carry all the required data to perform an action. For instance, what if “OrderCreated” event does not have customer address to fulfil shipment process in “Shipment Service”.</p><p>One solution is creating a “<em>fat event”</em> with all the required details. However, this may not be ideal in all use cases.</p><p>Another option is introducing a hybrid architecture, a mix of event-driven and request-driven. The shipping service consumes “OrderCreated” event asynchronously. But within the shipping service, it can make a REST API call to get customer data synchronously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*e8hzj3JoCxM3azdqPBm0kg.png" /><figcaption>Make a REST call to get customer data</figcaption></figure><p><strong>Which pattern to select?</strong></p><p>Both patterns have benefits, tradeoffs and their suitability also depend on the use case. However, if there is an opportunity to implement event-driven microservice, that will surely provide a good foundation to build loosely coupled microservices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b1fe40dccde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot with DynamoDB]]></title>
            <link>https://supunbhagya.medium.com/spring-boot-with-dynamodb-faa8a57a5276?source=rss-d7f113754551------2</link>
            <guid isPermaLink="false">https://medium.com/p/faa8a57a5276</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[dynamodb]]></category>
            <dc:creator><![CDATA[Supun Bhagya]]></dc:creator>
            <pubDate>Sun, 05 Apr 2020 04:20:35 GMT</pubDate>
            <atom:updated>2020-04-05T07:08:07.706Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*HMuF38DegHfCSqmkxxMRMw.png" /></figure><p>Amazon DynamoDB is AWS managed key-value and document database that delivers single-digit millisecond performance at any scale. In this article, we will build a simple Spring Boot application to integrate with DynamoDB.</p><p><strong>1. Create a Spring Boot project</strong></p><p>We can use <a href="https://start.spring.io/">Spring initializer</a> to generate a project. I’ve used Java 11, Maven and Spring Web as a dependency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9iZYty1eB5iX5x2wZWAOgA.png" /></figure><p><strong>2. Add AWS SDK dependencies</strong></p><p>Open the project with your IDE and add AWS SDK for Java bill of materials (BOM) dependency to our POM. This will ensure that the modules you specify use the same version of the SDK and that they’re compatible with each other.</p><pre>&lt;dependencyManagement&gt;<br>  &lt;dependencies&gt;<br>   &lt;dependency&gt;<br>    &lt;groupId&gt;com.amazonaws&lt;/groupId&gt;<br>    &lt;artifactId&gt;aws-java-sdk-bom&lt;/artifactId&gt;<br>    &lt;version&gt;${aws.java.sdk.bom}&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;</pre><p>Then, add AWS DynamoDB dependency to our POM</p><pre>&lt;dependency&gt;<br> &lt;groupId&gt;com.amazonaws&lt;/groupId&gt;<br> &lt;artifactId&gt;aws-java-sdk-dynamodb&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p><strong>3. Configure AWS DynamoDB client and DynamoDB mapper</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/408fd52775f02f98ed0164a2d4a3a48e/href">https://medium.com/media/408fd52775f02f98ed0164a2d4a3a48e/href</a></iframe><p><strong><em>AmazonDynamoDB </em></strong>provides access to Dynamodb using your credentials. In this case, I have used access key and access secret to interact with DynamoDB. You have to make sure your user has granted DynamoDB permission.</p><p><strong><em>DynamoDBMapper </em></strong>provides interactions with dynamoDB. It loads the data model for dynamodb using annotations defined in <em>com.amazonaws.services.dynamodbv2.datamodeling</em> package. This is much similar to JPA annotations if you are familiar with relational databases such as MySQL.</p><p><strong>init() </strong>method automatically creates the table in dynamoDB if the table does not exist in AWS.</p><p><strong>4. Create a data model</strong></p><p>It is time to define our entity class, this is similar to define a POJO entity class in JPA. We can leverage the annotations defined in <em>com.amazonaws.services.dynamodbv2.datamodeling </em>package to map our entity class to a database table. I have defined a simple entity <em>Customer </em>for our application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b519c05755d07b32131af73ae6065d86/href">https://medium.com/media/b519c05755d07b32131af73ae6065d86/href</a></iframe><p><strong>5. Create a Dao class</strong></p><p>Let&#39;s define a data access class to interact with our customer DynamoDB table. I have omitted service layer purposely as we do not have any business logic to process. Also, I have declared only two simple <em>createCustomer </em>and <em>getCustomer </em>methods in the CustomerDao class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e360576c29e952bc9296479dd9157bf/href">https://medium.com/media/1e360576c29e952bc9296479dd9157bf/href</a></iframe><p><strong>6. Create a rest controller</strong></p><p>This simple rest controller has two endpoints to <em>create a customer</em> and <em>retrieve a customer</em> by customerId. Those methods also have basic exception handling as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae9c387d3c7a8bd0ab7a9e12ef207926/href">https://medium.com/media/ae9c387d3c7a8bd0ab7a9e12ef207926/href</a></iframe><p>Now everything is ready, we can test our application. Run <em>SpringDynamodbApplication.java </em>class. Once the server is up on <a href="http://localhost:5555/customer&#39;">http://localhost:5555</a>, you can log in to AWS console and go to DynamoDB service. You should see the created table,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HfrEWXjeZHhchZxiIWN1WQ.png" /></figure><p><strong>Test 1</strong></p><p>Create a customer running following curl command</p><pre>curl --location --request POST &#39;<a href="http://localhost:5555/customer&#39;">http://localhost:5555/customer&#39;</a> \<br>--header &#39;Content-Type: application/json&#39; \<br>--data-raw &#39;{<br> &quot;name&quot;:&quot;Sinol&quot;,<br> &quot;email&quot;:&quot;<a href="/service/mailto:sinol@codersinol.com">sinol@codersinol.com</a>&quot;<br>}&#39;</pre><p>The response of the POST request will be similar to this,</p><pre>{<br>  &quot;customerId&quot;: &quot;86eb9f2d-5d6c-4e5d-8368-4949bceb35b5&quot;,<br>  &quot;name&quot;: &quot;Sinol&quot;,<br>  &quot;email&quot;: &quot;sinol@codersinol.com&quot;<br>}</pre><p><strong>Test 2</strong></p><p>Retrieve the customer calling getCustomer endpoint,</p><pre>curl --location --request GET &#39;<a href="http://localhost:5555/customers/86eb9f2d-5d6c-4e5d-8368-4949bceb35b5&#39;">http://localhost:5555/customers/86eb9f2d-5d6c-4e5d-8368-4949bceb35b5&#39;</a> \<br>--header &#39;Content-Type: application/json&#39; \<br>--data-raw &#39;{<br> &quot;name&quot;:&quot;Sinol&quot;,<br> &quot;email&quot;:&quot;<a href="/service/mailto:sinol@codersinol.com">sinol@codersinol.com</a>&quot;<br>}&#39;</pre><p>You can access full code of this application here <a href="https://github.com/coderSinol/spingboot-with-dynamoDB">https://github.com/coderSinol/spingboot-with-dynamoDB</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faa8a57a5276" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Router Redux demo app]]></title>
            <link>https://supunbhagya.medium.com/react-router-redux-demo-app-a3216384f706?source=rss-d7f113754551------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3216384f706</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Supun Bhagya]]></dc:creator>
            <pubDate>Wed, 27 Feb 2019 10:36:00 GMT</pubDate>
            <atom:updated>2019-06-03T06:14:10.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*rj9UBTjOMcqni5sBggiI6w.png" /></figure><p>This is a simple app to demonstrate the basics to develop a production ready React app using Router and Redux. This app has two functionalities, add a student to the student registration system and view all added students. the app UI needs a bit of styling, so I use <a href="https://material-ui.com/"><strong>material-ui</strong></a><strong> package </strong>to achieve that.</p><h4>1. Environment set up</h4><p><em>I assume you have installed node.js and ready to execute npm commands.</em></p><p>Firstly, create react app folder structure and required files using the <a href="https://github.com/facebook/create-react-app"><strong><em>create-react-app</em></strong></a> command. Then we will install other dependencies <strong><em>Router, Redux and material-ui</em></strong></p><pre>npm create-react-app react-router-redux-demo<br>cd react-router-redux-demo<br>npm install --save react-router-dom <br>npm install --save redux<br>npm install --save react-redux<br>npm install @material-ui/core</pre><p>What is react-router?</p><p>React Router is the standard routing library for React. It loads code/components based on the specified URL path. As you know, React app use only one HTML file to render components. React Router dynamically renders components on this HTML file according to the URL path. More importantly, this feature allows us to add multipage behaviour to a react app.</p><p>What is Redux</p><p>Redux makes it easy to manage the state of JavaScript applications. In other words, Redux helps us to manage the data model of our application and reflect these changes on the views.</p><p><strong>2. Folder Structure</strong></p><p>We will use the following folder structure for the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*InbZMOSNMevMMOSW0RQnKA.png" /></figure><p>Actions: Call service methods and update the state of our application</p><p>Components: React components and Views</p><p>Constants: Common Constants definitions to be used in the application</p><p>Helper: Supporting items</p><p>Reducers: Model definitions to manage the state of the application</p><p>Services: Execute operations such as accessing external resources</p><p><strong>3. Add Redux to the app</strong></p><p>We need to understand three basics of Redux before applying it to React.</p><ul><li>Store</li></ul><p>Redux store holds the application state. The state of the application can be accessed by <strong><em>getState()</em></strong><em> </em>method. Also, React components can register their listeners to the Redux store using <strong>connect()</strong> which comes with <strong>react-redux </strong>package.</p><p>Here is our store for this application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7af6b8c80bd36a3fd50d08fefc34e1e/href">https://medium.com/media/f7af6b8c80bd36a3fd50d08fefc34e1e/href</a></iframe><ul><li>Actions</li></ul><p>Actions are payloads of information that send data from the application to the Redux store. Action payload contains action type and data. Following is an example of Redux action, ADD_STUDENT_REQUEST is the type of this action and it carries a student as its data.</p><pre>{  <br>   type: ADD_STUDENT_REQUEST,<br>   student: {<br>             &quot;firstName&quot;:&quot;Rafael&quot;,<br>             &quot;lastName&quot;:&quot;Nadal&quot;,<br>             &quot;country&quot;:&quot;Spain&quot;,<br>             &quot;course&quot;:&quot;React&quot;<br>            }<br>}</pre><p>An action is sent to the store using <strong>dispatch(action) </strong>action. AllAction.js defines different actions to update the application state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9793db26084207e9159f5ad6dfd892a6/href">https://medium.com/media/9793db26084207e9159f5ad6dfd892a6/href</a></iframe><ul><li>Reducers</li></ul><p>Reducers specify how the application’s state changes in response to actions sent to the store. The reducer is a pure function that takes the previous state and action then returns the next state. Here is our reducer to add a new student. You can see crudStudent() returns different states for different action types.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc2ce8935fc827646b5bc9ffa16812f4/href">https://medium.com/media/fc2ce8935fc827646b5bc9ffa16812f4/href</a></iframe><p><strong>4. Services</strong></p><p>This is the layer that interacts with external resources. A service method may call an external API to fetch data, read <a href="https://www.w3schools.com/html/html5_webstorage.asp">local storage</a> or execute simple client-side logic. In our case, the service methods read and write students to the <a href="https://www.w3schools.com/html/html5_webstorage.asp">local storage</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d932279b0ec863736e66f54e8ca7eb09/href">https://medium.com/media/d932279b0ec863736e66f54e8ca7eb09/href</a></iframe><p><strong>5. Components</strong></p><p>Firstly, We will create <em>MenuBar.js</em> component, which is used to navigate to different views(pages) of the application. This is a common component of this application. We will use &lt;AppBar&gt; component from <strong>material-ui</strong> to add a little bit of styling to this component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cee27b624219c145094675026ac5bea2/href">https://medium.com/media/cee27b624219c145094675026ac5bea2/href</a></iframe><p>Now, we can create <em>Home.js</em> component. As you can see, it uses <em>MenuBar.js</em> as its dependent component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9eb358fa664f96e1a127c64e511344ff/href">https://medium.com/media/9eb358fa664f96e1a127c64e511344ff/href</a></iframe><p>Similarly, we will create the other two components <a href="https://github.com/coderSinol/React-router-redux-demo/blob/master/src/Components/AddStudent.js"><em>AddStudent</em></a><em>.js</em> and <a href="https://github.com/coderSinol/React-router-redux-demo/blob/master/src/Components/ViewStudents.js"><em>ViewStudents</em></a><em>.js</em></p><p><strong>6. React Route</strong></p><p>Our purpose is creating a multipage application using React. This can be achieved using React-Router. There is a couple of options to do this,</p><ul><li>BrowserRouter: <a href="https://application.com/dashboard">https://mydomain.com/h</a>ome</li><li>HashRouter: <a href="https://application.com/dashboard">https://mydomain.com/#h</a>ome</li></ul><p>We will use BrowserRouter for our application as it provides much-needed features in the production such as SEO friendly URLs and shareable links.</p><p>All route definitions are in the App.js component. This is the root component of the application and it renders other components based on the URL path.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0e976cbd4d226bef616dd563bb1178e/href">https://medium.com/media/b0e976cbd4d226bef616dd563bb1178e/href</a></iframe><p><strong>7. Test it</strong></p><p>Now app is ready to test. Run <strong>npm start</strong> to run the app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*iakdvkGgc2pgojNIAI9RRw.png" /></figure><p>Full code in my Git repository <a href="https://github.com/coderSinol/React-router-redux-demo">https://github.com/coderSinol/React-router-redux-demo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3216384f706" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Oauth2 ResourceServer + Oauth2 Security + Authorization Code grant flow]]></title>
            <link>https://supunbhagya.medium.com/spring-oauth2-resourceserver-oauth2-security-authorization-code-grant-flow-9eb72fd5d27d?source=rss-d7f113754551------2</link>
            <guid isPermaLink="false">https://medium.com/p/9eb72fd5d27d</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Supun Bhagya]]></dc:creator>
            <pubDate>Tue, 12 Feb 2019 01:28:29 GMT</pubDate>
            <atom:updated>2019-09-10T00:11:31.774Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Overview</strong></h3><p>In the previous <a href="https://medium.com/@igabhagya/spring-oauth2-authorization-server-jwt-jpa-data-model-1e458dcdac04">article</a>, we implemented a Spring Oauth2 Authorization server. In this article, we are going to create an Oauth2 resource server implementing Spring Oauth2 and secure its methods using Oauth2. Also, we will test both the Authorization and Resource server using the Authorization code grant flow.</p><p><strong>What is a Resource server?</strong></p><p>Resource server provides protected resources. It communicates with its Authorization server to validate a request to access a protected resource. Typically the endpoints of a resource server are protected based on the oauth2 scopes and user roles.</p><p>You can find the code in GitHub repository <a href="https://github.com/coderSinol/oauth2-resource">https://github.com/coderSinol/oauth2-resource</a></p><ol><li><strong>Configure Remote Token Service</strong></li></ol><p>The secured methods in the resource server need to be accessed passing a token as the Authorization header or a request parameter. But the first approach is recommended considering the security concerns.</p><p>Resource server needs to validate the received token with the Authorization server. In this example, Authorization and Resource servers run as separate applications. Therefore, we will use Remote Token service in the Resource server to validate the received token with the Authorization server.</p><p><strong>Implementation</strong></p><p>We will implement a custom remote token service implementing Spring Oauth2 ResourceServerTokenServices interface to communicate with the Authorization server. This authorization server can be any IAM provider or the server created in previous <a href="https://medium.com/@igabhagya/spring-oauth2-authorization-server-jwt-jpa-data-model-1e458dcdac04">article</a>. You can see the <strong>loadAuthentication </strong>method is implemented to communicate with the Authorization server and return the Authentication object. The token validation is done calling <strong>/oauth/check_token </strong>endpoint in the Authorization server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53ec849f97656e0669b78fd288d4aa7f/href">https://medium.com/media/53ec849f97656e0669b78fd288d4aa7f/href</a></iframe><p><strong>2. Configure Oauth2 Resource server</strong></p><p>@EnableResourceServer annotation enables our Spring boot application to work as a Spring Oauth2 resource server.</p><p>Key configurations:</p><ul><li>Set resource Id to ResourceServerSecurityConfigurer. This is a unique identifier for our application and it is useful when validating an access token.</li><li>Configure above CustomRemoteTokenService as token service for this resource server.</li><li>Set OAuth2AuthenticationManager as the AuthenticationManager of this application.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f70190fc3d139136ad7dfd6a0aa40671/href">https://medium.com/media/f70190fc3d139136ad7dfd6a0aa40671/href</a></iframe><p><strong>3. Enable Oauth2 authentication</strong></p><p>Now, it is time to enable Oauth2 on our resource server and protect its endpoints. @EnableGlobalMethodSecurity annotation enables method level access validation for the resource server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecc93530140ddebb4debc25578c28725/href">https://medium.com/media/ecc93530140ddebb4debc25578c28725/href</a></iframe><p>Once this config is set, we can use @PreAuthorize annotation to define what access level is required to execute a method.</p><p>We will define two controller classes with different access levels in their methods. Firstly, let&#39;s create <a href="https://github.com/coderSinol/oauth2-resource/blob/master/src/main/java/com/sinol/oauth/resource/controller/PublicController.java">PublicController.java</a> which has a method getRandomMessage method without any access restrictions.</p><p>Secondly, we will create UserController.java and define its method getOauth2Principal. This method needs Oauth2 “read” scope to return a successful response. When we call this endpoint <strong>user/profile</strong>, we must pass an access token in the header or as a request parameter to get a successful response.</p><p>We can use @PreAuthorize annotation with Spring Expression Language (SpEL) to define the required access level.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69b4301aaf43e3f558d719b2677cff46/href">https://medium.com/media/69b4301aaf43e3f558d719b2677cff46/href</a></iframe><p><strong>4. Test it</strong></p><p>We will use the Chrome Postman app to test the Resource server using the Authorization Code grant flow. Postman app act as an external client application and resource owner’s user-agent which tries to access a Protected Resource behalf of a user.</p><p>Steps in Authorization Code grant flow (refer <a href="https://tools.ietf.org/html/rfc6749#section-4">https://tools.ietf.org/html/rfc6749#section-4</a> for more info)</p><ul><li>Redirect to Authorization server’s login screen</li><li>User authentication</li><li>Return Authorization Code to the callback URL</li><li>Create token request passing retrieved Authorization Code</li><li>Request a protected resource with the token</li></ul><p><strong>Step 01</strong></p><p>Create GET request to access the protected resource <a href="http://localhost:8096/user/profile">http://localhost:8096/user/profile</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2SpvMujUHCT_8G0BdjQlgA.jpeg" /></figure><p><strong>Step 02</strong></p><p>Get an access token passing client Id and secret</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*npDSx5sR8X7R9dQnU1bC_w.jpeg" /></figure><p><strong>Step 03</strong></p><p>Redirect to Authorization server’s login screen to validate user credentials. We will use previously entered user credentials admin/admin1234</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iClNIlbGW8SReeqrb_K1LQ.jpeg" /></figure><p><strong>Step 04</strong></p><p>Authorize the Postman app to access the protected resource.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rFpu2XV5TXisYzoX7TltEw.jpeg" /></figure><p><strong>Step 05</strong></p><p>Get an access token passing Authorization code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K4UNCN-eDawZFHQ8pw7Xsw.jpeg" /></figure><p><strong>Step 06</strong></p><p>Use created access token to get protected resource. You can successful response received with the name of the authenticated principal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Csj1fnzw_oK_G4Io7RROFw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9eb72fd5d27d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Oauth2 Authorization server + JWT + JPA data model]]></title>
            <link>https://supunbhagya.medium.com/spring-oauth2-authorization-server-jwt-jpa-data-model-1e458dcdac04?source=rss-d7f113754551------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e458dcdac04</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Supun Bhagya]]></dc:creator>
            <pubDate>Mon, 04 Feb 2019 09:01:01 GMT</pubDate>
            <atom:updated>2019-03-06T01:29:12.696Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><p>In this article, we will implement Spring Oauth2 Authorization server with a JWT token store. If you need more details about oauth2 specification, look at <a href="https://tools.ietf.org/html/rfc6749">here</a></p><p>If you want to see the code skipping the explanation, you can jump into the GitHub repository <a href="https://github.com/coderSinol/oAuth2">https://github.com/coderSinol/oAuth2</a></p><h4>1. The data model</h4><p>The first step is creating the required data model for Spring Oauth2 and Spring Web security. To do this we have following JPA entities (click links to see details).</p><p><a href="https://github.com/coderSinol/oAuth2/blob/master/src/main/java/com/sinol/oauth/model/Authority.java">Authority.java</a></p><p><a href="https://github.com/coderSinol/oAuth2/blob/master/src/main/java/com/sinol/oauth/model/OauthAccessToken.java">OauthAccessToken.java</a></p><p><a href="https://github.com/coderSinol/oAuth2/blob/master/src/main/java/com/sinol/oauth/model/OauthClientDetails.java">OauthClientDetails.java</a></p><p><a href="https://github.com/coderSinol/oAuth2/blob/master/src/main/java/com/sinol/oauth/model/OauthClientToken.java">OauthClientToken.java</a></p><p><a href="https://github.com/coderSinol/oAuth2/blob/master/src/main/java/com/sinol/oauth/model/OauthCode.java">OauthCode.java</a></p><p><a href="https://github.com/coderSinol/oAuth2/blob/master/src/main/java/com/sinol/oauth/model/OauthRefreshToken.java">OauthRefreshToken.java</a></p><p><a href="https://github.com/coderSinol/oAuth2/blob/master/src/main/java/com/sinol/oauth/model/User.java">User.java</a></p><p><a href="https://github.com/coderSinol/oAuth2/blob/master/src/main/java/com/sinol/oauth/model/UserAuthority.java">UserAuthority.java</a></p><p>We use MySQL database and mysql-connector. This data source will be used to store client details, users and tokens. import.sql file is used to populate data with sample Client and User to test our application.</p><h4>2. <strong>Configure Authorization server</strong></h4><p>@EnableAuthorizationServer annotation enables Spring Oauth2 implementation for Oauth2. Then we need to define this Authorisation server should produce JWT tokens. This is done defining a JwtTokenStore and pass it to AuthorizationServerEndpointsConfigurer.</p><p><strong>Key configs:</strong></p><ul><li>Define <strong>JdbcClientDetailsService </strong>in <strong>ClientDetailsServiceConfigurer </strong>to access client details</li><li>Set JwtAccessTokenConverter with a signing key</li><li>Set BCryptPasswordEncoder as our password encoder</li><li>Enable “/oauth/check_token” and “/oauth/token” endpoints using AuthorizationServerSecurityConfigurer</li><li>Finally, but most importantly, configuration to AuthorizationServerEndpointsConfigurer. Here we have passed <strong>accessConverter</strong>, <strong>authenticate manager </strong>and <strong>user detail service</strong>. The <strong>userDetailsService </strong>is responsible to access user details from the data source.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*jspSsBLAc06wAHzoF-PrdA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a6703f4a522bf00d6febe15948c6037/href">https://medium.com/media/7a6703f4a522bf00d6febe15948c6037/href</a></iframe><h4><strong>3. Enable Spring Security</strong></h4><p>Now we have configured the Authorization server. Next, we will enable Spring security.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8eb9c42cc7f7661253cbc7e2d951968f/href">https://medium.com/media/8eb9c42cc7f7661253cbc7e2d951968f/href</a></iframe><h4>4. Implement UserDetailsService</h4><p>Now it is time to implement org.springframework.security.core.userdetails.UserDetailsService interface to load user details from the database. Our Authorization server uses <a href="https://github.com/coderSinol/oAuth2/blob/master/src/main/java/com/sinol/oauth/service/UserDetailsServiceImpl.java">UserDetailsServiceImpl.java</a> service to load user details.</p><p>UserDao is a Spring JPA repository to load users from the database. The loadUserByUsername method return <a href="https://github.com/coderSinol/oAuth2/blob/master/src/main/java/com/sinol/oauth/model/dto/CustomUserDetails.java">CustomUserDetails.java</a> which implements org.springframework.security.core.userdetails.UserDetails interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66c03edfbe8c7192d830707229d5f67f/href">https://medium.com/media/66c03edfbe8c7192d830707229d5f67f/href</a></iframe><p>I’m not going to provide more details about Spring security since our focus here is Oauth2 implementation.</p><h4>5. Insert sample data set</h4><p>We use Spring JPA hibernate implementation to populate data to the database. Here, we will insert sample client application and user to the database using import.sql file.</p><p>Sample data:</p><p>Client Application Credentials: oauth2-jwt-client/admin1234</p><p>User credentials : admin/admin1234</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2b0d362f82923dbc6897bf6a3dbd721/href">https://medium.com/media/c2b0d362f82923dbc6897bf6a3dbd721/href</a></iframe><h4>6. Test it!</h4><p>All set to test our Authorization server. We will use Postman Chrome app to run a test.</p><p>We will do a POST request to <a href="http://localhost:8095/oauth/token">http://localhost:8095/oauth/token</a> endpoint to create a token. We will create a token request for client credentials grant type.</p><p>In this case, we need to pass the Authorization header and request parameter grant_type.</p><p>The Authorization header should be set as Basic Authorization. This is created in this format, Basic <em>base64</em>(&lt;Client_name:Client_secret&gt;)</p><p>Following is sample Curl request,</p><pre>curl -X POST \<br>  <a href="http://localhost:8095/oauth/token">http://localhost:8095/oauth/token</a> \<br>  -H &#39;authorization: Basic b2F1dGgyLWp3dC1jbGllbnQ6YWRtaW4xMjM0&#39; \<br>  -H &#39;cache-control: no-cache&#39; \<br>  -H &#39;content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW&#39; \<br>  -H &#39;postman-token: 7264a216-8567-8fbd-1e9e-4733d07d205b&#39; \<br>  -F grant_type=client_credentials</pre><p>Here is the Postman request. You can see the response has returned a JWT token</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xhq3JrJ-Z228QnMGKBG27g.png" /></figure><h4>7. Next step</h4><p>We have tested our Authorization server with Client Credentials grant type only. In this case, User was not involved in generating the token, only client application details were used.</p><p>The next step is to use our server to test the Authorization code grant type where there will be User interaction to create a token. This is available in my <a href="https://medium.com/@igabhagya/spring-oauth2-resourceserver-oauth2-security-authorization-code-grant-flow-9eb72fd5d27d">next article</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e458dcdac04" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>