<?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 Jidar Ahmed Amin on Medium]]></title>
        <description><![CDATA[Stories by Jidar Ahmed Amin on Medium]]></description>
        <link>https://medium.com/@justup1080?source=rss-41b0adfc5f8b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KcLZ_R7Sj1jzrCsO-8v9tQ.jpeg</url>
            <title>Stories by Jidar Ahmed Amin on Medium</title>
            <link>https://medium.com/@justup1080?source=rss-41b0adfc5f8b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 12:32:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@justup1080/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[Tutorial: Creating a Minimalist HTTP Server in C]]></title>
            <link>https://medium.com/@justup1080/tutorial-creating-a-minimalist-http-server-in-c-2303d140c725?source=rss-41b0adfc5f8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2303d140c725</guid>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[sockets]]></category>
            <dc:creator><![CDATA[Jidar Ahmed Amin]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 01:31:58 GMT</pubDate>
            <atom:updated>2024-01-22T01:31:58.879Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mxLWRxhGUDr63OLLxDmATQ.jpeg" /><figcaption>Server</figcaption></figure><blockquote>This implementation of an HTTP server is a minimalistic version, designed to demonstrate the core functionalities of an HTTP server.<br> It includes the basic requirements for an HTTP server to operate, such as socket programming, request handling, and response generation.<br> While this server is fully functional, it is important to note that it is a simplified model. Real-world HTTP servers often include additional features such as logging, error handling, security measures, and support for more complex HTTP methods and routes.<br> Therefore, this server can be seen as a foundation upon which more complex and robust servers can be built. It serves as a starting point for anyone looking to understand the underlying principles of HTTP servers and network programming.</blockquote><h3>Socket Lifecycle Functions</h3><h4>1. socket() Function: Creating a Socket</h4><ul><li>Purpose: Creates a new socket with specified domain, type, and protocol.</li></ul><p>Parameters:</p><ul><li>domain: Protocol family (e.g., AF_INET for IPv4).</li><li>type: Type of service (SOCK_STREAM for TCP, SOCK_DGRAM for UDP).</li><li>protocol: Protocol to be used; usually set to 0 for automatic selection.</li><li>Return: Returns a socket descriptor if successful, -1 on failure.</li></ul><h4>2. bind() Function: Associating Socket with Address and Port</h4><ul><li>Purpose: Associates the socket with a specific IP address and port.</li></ul><p>Parameters:</p><ul><li>socket: Socket descriptor.</li><li>addr: Pointer to struct sockaddr containing IP address and port.</li><li>addrlen: Size of the structure.</li><li>Return: Returns 0 if successful, -1 on failure.</li></ul><h4>3. listen() Function: Marking Socket as Passive</h4><ul><li>Purpose: Marks the socket as a passive socket for incoming connection requests.</li></ul><p>Parameters:</p><ul><li>socket: Socket descriptor.</li><li>backlog: Maximum length of the queue of pending connections.</li><li>Return: Returns 0 if successful, -1 on failure.</li></ul><h4>4. accept() Function: Accepting Connection Requests</h4><ul><li>Purpose: Extracts the first connection request, creates a new socket for the connection.</li></ul><p>Parameters:</p><ul><li>socket: Original socket for listening.</li><li>addr: Pointer to struct sockaddr for client&#39;s address.</li><li>addrlen: Pointer to socklen_t for the length of the client&#39;s address.</li><li>Return: Returns a new socket descriptor if successful, -1 on failure.</li></ul><h4>5. connect() Function: Client Connecting to the Server</h4><ul><li>Purpose: Establishes a connection to the server.</li></ul><p>Parameters:</p><ul><li>socket: Socket descriptor.</li><li>addr: Pointer to struct sockaddr containing server&#39;s IP address and port.</li><li>addrlen: Size of the structure.</li><li>Return: Returns 0 if successful, -1 on failure.</li></ul><h4>6. send() and recv() Functions: Sending and Receiving Data</h4><ul><li>Purpose: Used to send and receive data on a socket.</li></ul><p>Parameters:</p><ul><li>socket: Socket descriptor.</li><li>buffer: Data buffer.</li><li>length: Number of bytes to send or receive.</li><li>Return: Returns the number of bytes sent or received, -1 on failure.</li></ul><h4>7. close() Function: Closing a Socket</h4><ul><li>Purpose: Closes a socket.</li></ul><p>Parameter:</p><ul><li>socket: Socket descriptor.</li><li>Return: Returns 0 if successful, -1 on failure.</li></ul><h3>Minimal HTTP Server Implementation in C</h3><p>server.h :</p><pre>#ifndef server_h<br>#define server_h<br><br>#include &lt;netinet/in.h&gt;<br><br>#define BUFFER_SIZE 16000<br><br>struct Server {<br>    int domain;<br>    int port;<br>    int service;<br>    int protocol;<br>    int backlog;<br>    u_long interface;<br><br>    int socket;<br>    struct sockaddr_in address;<br><br>    void (*launch)(struct Server *server);<br>};<br><br>struct Server server_Constructor(int domain, int port, int service, int protocol, int backlog, u_long interface, void (*launch)(struct Server *server));<br>void launch(struct Server *server);<br><br>#endif</pre><p>server.c :</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;unistd.h&gt;<br>#include &lt;string.h&gt;<br>#include &quot;server.h&quot;<br><br>struct Server server_Constructor(int domain, int port, int service, int protocol, int backlog, u_long interface, void (*launch)(struct Server *server)) {<br>    struct Server server;<br><br>    server.domain = domain;<br>    server.service = service;<br>    server.port = port;<br>    server.protocol = protocol;<br>    server.backlog = backlog;<br><br>    server.address.sin_family = domain;<br>    server.address.sin_port = htons(port);<br>    server.address.sin_addr.s_addr = htonl(interface);<br><br>    server.socket = socket(domain, service, protocol);<br>    if (server.socket &lt; 0) {<br>        perror(&quot;Failed to initialize/connect to socket...\n&quot;);<br>        exit(EXIT_FAILURE);<br>    }<br><br>    if (bind(server.socket, (struct sockaddr*)&amp;server.address, sizeof(server.address)) &lt; 0) {<br>        perror(&quot;Failed to bind socket...\n&quot;);<br>        exit(EXIT_FAILURE);<br>    }<br><br>    if (listen(server.socket, server.backlog) &lt; 0) {<br>        perror(&quot;Failed to start listening...\n&quot;);<br>        exit(EXIT_FAILURE);<br>    }<br><br>    server.launch = launch;<br>    return server;<br>}<br><br>void launch(struct Server *server) {<br>    char buffer[BUFFER_SIZE];<br>    while (1) {<br>        printf(&quot;=== WAITING FOR CONNECTION === \n&quot;);<br>        int addrlen = sizeof(server-&gt;address);<br>        int new_socket = accept(server-&gt;socket, (struct sockaddr*)&amp;server-&gt;address, (socklen_t*)&amp;addrlen);<br>        ssize_t bytesRead = read(new_socket, buffer, BUFFER_SIZE - 1);<br>        if (bytesRead &gt;= 0) {<br>            buffer[bytesRead] = &#39;\0&#39;;  // Null terminate the string<br>            puts(buffer);<br>        } else {<br>            perror(&quot;Error reading buffer...\n&quot;);<br>        }<br>        char *response = &quot;HTTP/1.1 200 OK\r\n&quot;<br>                         &quot;Content-Type: text/html; charset=UTF-8\r\n\r\n&quot;<br>                         &quot;&lt;!DOCTYPE html&gt;\r\n&quot;<br>                         &quot;&lt;html&gt;\r\n&quot;<br>                         &quot;&lt;head&gt;\r\n&quot;<br>                         &quot;&lt;title&gt;Testing Basic HTTP-SERVER&lt;/title&gt;\r\n&quot;<br>                         &quot;&lt;/head&gt;\r\n&quot;<br>                         &quot;&lt;body&gt;\r\n&quot;<br>                         &quot;Hello, Ahmed!\r\n&quot;<br>                         &quot;&lt;/body&gt;\r\n&quot;<br>                         &quot;&lt;/html&gt;\r\n&quot;;<br>        write(new_socket, response, strlen(response));<br>        close(new_socket);<br>    }<br>}</pre><p>main.c :</p><pre>#include &quot;server.h&quot;<br><br>int main() {<br>    struct Server server = server_Constructor(AF_INET, 80, SOCK_STREAM, 0, 10, INADDR_ANY, launch);<br>    server.launch(&amp;server);<br>    return 0;<br>}</pre><h3>Testing Steps</h3><h4><em>Configure Windows Defender Firewall (On Windows Client):</em></h4><ul><li>Open Windows Defender Firewall settings.</li><li>Click on “Advanced settings.”</li><li>Select “Inbound Rules” &gt; “New Rule.”</li><li>Choose “Port,” select “TCP,” enter the server’s port (e.g., 80), and allow the connection.</li></ul><h4>On Kali Linux Server:</h4><ul><li>Open a terminal.</li><li>Update and install iptables: apt-get update and apt-get install iptables.</li><li>Check and configure iptables rules, you can add a rule if necessary sudo iptables -A INPUT -p tcp — dport 80 -j ACCEPT</li><li>Save your iptables rules with the command sudo /sbin/iptables-save</li></ul><h4>Compile and Run the Server Object File:</h4><ul><li>gcc -o myServer main.c server.c</li><li>./myServer</li></ul><h4>Check if the Server is Running and Listening:</h4><ul><li>Use top to verify the process is running.</li><li>Use netstat -tuln to check if the server is listening on the specified port (e.g., 80). An example output of this would be:</li></ul><pre>┌──(ahmed㉿DESKTOP-V2HJGUR)-[~]<br>└─$ netstat -tuln<br>Active Internet connections (only servers)<br>Proto Recv-Q Send-Q Local Address           Foreign Address         State<br>tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN<br>udp        0      0 127.0.0.1:323           0.0.0.0:*<br>udp6       0      0 ::1:323                 :::*</pre><p>Your server should be in a LISTEN state.</p><h4>Check Your Server IP:</h4><ul><li>Your machine’s IP address is the server’s IP:</li><li>Run ifconfig</li><li>First inet value withing the eth0 or wlan0</li></ul><h4>Open Preferred Browser:</h4><ul><li>On Windows machine, open http://&lt;Your_Server_IP&gt;/.</li><li>The response message should be printed.</li></ul><h4>Check Server Output:</h4><p>The server terminal should display incoming HTTP requests. eg:</p><pre>        === WAITING FOR CONNECTION ===<br>        GET /favicon.ico HTTP/1.1<br>        Host: &lt;Your server IP&gt;<br>        Connection: keep-alive<br>        User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...<br>        Accept: image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8<br>        Referer: http://&lt;IP&gt;/<br>        Accept-Encoding: gzip, deflate<br>        Accept-Language: fr,fr-FR;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6</pre><p>Congratulations! Your server is running successfully.</p><blockquote><strong>Warning:</strong> This is a minimal version for study purposes; it is not secure for production. Always consider security measures in a production environment.</blockquote><h3>Sources:</h3><ul><li><a href="https://www.geeksforgeeks.org/socket-programming-cc/">Socket Programming in C — GeeksforGeeks</a></li><li><a href="https://dev.to/sanjayrv/a-beginners-guide-to-socket-programming-in-c-5an5">A Beginners Guide to Socket Programming in C — DEV Community</a></li><li><a href="https://www.geeksforgeeks.org/tcp-server-client-implementation-in-c/">TCP Server-Client implementation in C — GeeksforGeeks</a></li><li><a href="https://stackoverflow.com/questions/307692/how-to-open-and-use-a-socket-in-c">How to open and use a socket in C? — Stack Overflow</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2303d140c725" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Essentials of RESTful Services: Exploring Spring Boot’s Power]]></title>
            <link>https://medium.com/@justup1080/essentials-of-restful-services-exploring-spring-boots-power-0a6d1346ff1b?source=rss-41b0adfc5f8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a6d1346ff1b</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[restful-api]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Jidar Ahmed Amin]]></dc:creator>
            <pubDate>Fri, 19 Jan 2024 01:27:46 GMT</pubDate>
            <atom:updated>2024-01-19T01:27:46.572Z</atom:updated>
            <content:encoded><![CDATA[<p>Spring Boot — an unparalleled framework for building robust and scalable APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yi9ouhCDHa7S9pnqxzvNXw.jpeg" /><figcaption>Spring</figcaption></figure><p>From understanding the core principles of REST to hands-on implementation using Spring Boot, we’ll cover everything you need to know to craft a basic, robust and secure API.</p><p>Whether you’re a seasoned developer or just starting your journey in API development, these segments are designed to provide you with the foundational knowledge and practical skills required to excel in the world of RESTful services.</p><h4>Note:</h4><blockquote>Please note that in this educational doc, we will not be working with external databases or real-world JPA implementations. Instead, we will rely on the convenience of in-memory databases, such as H2, for <strong>testing purposes</strong>. Additionally, user authentication will be handled using an <strong>in-memory</strong> user details service.</blockquote><blockquote>While this approach may deviate from real-world scenarios, it is intentionally chosen to prioritize clarity and ease of understanding, particularly for those who are new to RESTful services and Spring Boot.</blockquote><blockquote>We encourage learners to adapt the concepts covered in this course to their specific use cases and environments when working on real-world projects.</blockquote><h3>What is an API?</h3><p>An API, or Application Programming Interface, is a set of rules and tools that allows one software application to interact with another. It defines the methods and data formats that applications can use to request and exchange information.</p><p>APIs come in various types and are designed to serve different purposes across various fields; Libray APIs, Operating System APIs, Hardware APIs and Web APIs as we illustrated before the RESTful API is our focused case in the Web field for now.</p><h3>RESTful API ?</h3><p>A RESTful API is an application programming interface designed based on the principles of Representational State Transfer (REST). It follows a set of constraints, including statelessness, resource-based interactions, and the use of standard HTTP methods (GET, POST, PUT, DELETE).</p><p>A RESTful API allows systems to communicate over the web, treating resources as entities that can be identified and manipulated. It typically returns data in standardized formats such as JSON or XML, promoting a scalable, uniform, and flexible approach to web service development.</p><p>A RESTful API developed with <strong>Spring Boot</strong> adheres to the principles of Representational State Transfer (REST) and is created using the Spring Boot framework. Leveraging Spring Boot simplifies the development process, providing a streamlined approach for building robust and scalable APIs.</p><h3><strong>Test-Driven Development (TDD)</strong></h3><p>TDD asserts expected behavior before implementation, guiding developers to write the minimum code required for functionality, fostering correctness and maintainability.</p><p>Embracing TDD while developing your RESTful API in Spring Boot enhances code quality, reduces bugs, and streamlines the overall development process. Consider it a best practice to elevate your API development journey.</p><p>TDD is based on the Red, Green, Refactor loop:</p><ul><li><strong>Red</strong>: Write a failing test for the desired functionality.</li><li><strong>Green</strong>: Implement the simplest thing that can work to make the test pass.</li><li><strong>Refactor</strong>: Look for opportunities to simplify, reduce duplication, or otherwise improve the code without changing any behavior — to refactor.</li><li><strong>Repeat!</strong></li></ul><p>It’s better to start with <strong>Unit Tests </strong>using the<strong> JUnit library</strong>, the bottom operation of the <a href="https://martinfowler.com/articles/practical-test-pyramid.html">Test Pyramid</a> for <strong>more isolation</strong>.</p><h4>Guidance on Test-Driven Development (TDD):</h4><blockquote>As we navigate through the essentials of RESTful API development, it’s recommended to explore Test-Driven Development (TDD) independently. While TDD won’t be extensively covered in this guide, its integration holds significant value in ensuring robust coding practices. Consider delving into TDD to fortify your development approach and enhance code quality. In this documentation, we’ll focus primarily on the essential code constructs, keeping the spotlight on crafting a resilient RESTful API with Spring Boot.</blockquote><h3>Spring &amp; Spring Boot</h3><p><strong><em>Spring</em></strong> is a comprehensive framework that provides various modules for building different types of applications. It’s like having a giant toolbox with every tool you could possibly need to build anything you want.</p><p>As we build our `Family Cash Card` API we will use <strong>Spring MVC </strong>for the web application, <strong>Spring Data</strong> for data access, and <strong>Spring Security</strong> for authentication and authorization.</p><p><strong><em>Spring Boot</em></strong> is a more opinionated, streamlined version of Spring that comes with a lot of built-in features to help you get started quickly and easily.</p><h3>Spring’s Inversal Of Control (IoC) Container</h3><p>The Spring Inversion of Control (IoC) Container is a core concept that forms the backbone of the Spring Framework. It delegates the control of object creation and management to the Spring container, inverting the traditional flow of control.</p><p>This pivotal mechanism enhances modularity, promotes loose coupling, and significantly simplifies the configuration and management of components within a Spring-based application. Understanding IoC is foundational before delving into Spring Boot, as it sets the stage for the framework’s unparalleled features and capabilities.</p><figure><img alt="Spring IoC Operation" src="https://cdn-images-1.medium.com/max/609/1*VLkqPo3qpU4bHSzGSK4C8g.png" /></figure><p>Check <a href="https://subscription.packtpub.com/book/web-development/9781787284661/1/ch01lvl1sec8/introduction-to-the-spring-ioc-container">Spring IoC</a> for more.</p><p>Now equipped with a foundational understanding of key concepts like RESTful APIs, Spring Boot’s power, and the significance of Test-Driven Development (TDD), we seamlessly transition to the heart of our journey: creating RESTful endpoints</p><h3>Spring’s Dependency Injection (DI)</h3><p>A design pattern used by Spring to implement IoC. It’s responsible for wiring together beans by injecting dependencies (other beans) into a target bean.</p><h3>Bean</h3><p>A bean is an object that is instantiated, assembled, and otherwise managed by a Spring<strong> IoC</strong> container.</p><h3>Spring’s IoC, DI &amp; Bean all work together</h3><p>So, in essence, IoC manages the beans’ lifecycle, and DI connects these beans with their dependencies. This results in a well-structured, loosely coupled application where the individual components (beans) can be developed and tested independently.</p><h4>Disclaimer:</h4><blockquote>This guide skips detailed project setup and dives directly into the essentials of building a robust RESTful API using Spring Boot. If you’re familiar with project initialization, let’s get started. For setup guidance, see the <a href="https://spring.io/guides/gs/spring-boot/">Guide</a>.</blockquote><h3>Creating RESTful Endpoints</h3><h4>Architecture Flow of a Spring Boot Application (MVC Based)</h4><p>Simply; Spring boot uses all the features of Spring like Spring MVC, Spring Data and JPA. A generic Spring Boot application consists of a controller which serves the clients HTTP request. This controller then interacts with the service layer which processes the request to modify the model and the database using the JPA repository through dependency injection. A view page is returned to the user if no error occurred.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*J3gjKn3FKubWX9tn1nV-ug.png" /></figure><h4>API Contract is a must-know</h4><p>In simpler terms, an API contract is like a formal agreement between two parties in the software world — the one providing a service (provider) and the one using that service (consumer).</p><p>This agreement serves as a clear guide on how they should interact with each other. The contract outlines how data is exchanged, the rules for communication, and how to handle both successful and unsuccessful situations. Let’s take a look over the following example:</p><pre>Request<br>  URI: /cashcards/{id}<br>  HTTP Verb: GET<br>  Body: None<br><br>Response:<br>  HTTP Status:<br>    200 OK if the user is authorized and the Cash Card was successfully retrieved<br>    401 UNAUTHORIZED if the user is unauthenticated or unauthorized<br>    404 NOT FOUND if the user is authenticated and authorized but the Cash Card cannot be found<br>  Response Body Type: JSON<br>  Example Response Body:<br>    {<br>      &quot;id&quot;: 99,<br>      &quot;amount&quot;: 123.45<br>    }</pre><p>Importantly, the parties involved don’t need to use the same programming language; they just need to follow the same set of rules laid out in the API contract.</p><p>Testing an API contract includes <strong>Serialization</strong> and <strong>Deserialization</strong> tests of the <strong>data</strong>, which will be covered in another topic.</p><h4>Project Management Tool</h4><p>In the segments of this documentation, the project is built using <strong>Gradle</strong>. However, you have the flexibility to build it using <strong>Maven</strong> as well. Below are the shell commands for both Maven and Gradle</p><p><strong>— Using Gradle:</strong></p><pre># Build the project<br>./gradlew clean build<br><br># Run the Spring Boot application<br>./gradlew bootRun</pre><p><strong>— Using Maven:</strong></p><pre># Build the project<br>mvn clean install<br><br># Run the Spring Boot application<br>mvn spring-boot:run</pre><h4>Implementing RESTful CRUD Operations</h4><p>In your build.gradle file, make sure that thespring-starter-web dependency is present</p><pre>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br>    testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br>    testRuntimeOnly &#39;org.junit.platform:junit-platform-launcher&#39; // See https://docs.gradle.org/8.3/userguide/upgrading_version_8.html#test_framework_implementation_dependencies<br>}</pre><p>Our record class (The entity we will be working on) is defined as follow in the CashCard.java file (for now)</p><pre>record CashCard(@Id Long id, Double amount) {<br>}</pre><p>Then, create three other separate files CashCardController.java, CashCardRepository.java and SecurityConfig.java , and there you go, that’s a step into your MVC Structure.</p><p>The src‘s directory structure should be as follow:</p><pre>└── src<br>    ├── main<br>    │   ├── java<br>    │   │   └── example<br>    │   │       └── cashcard<br>    │   │           ├── CashCard.java<br>    │   │           ├── CashCardApplication.java<br>    │   │           ├── CashCardController.java<br>    │   │           ├── CashCardRepository.java<br>    │   │           └── SecurityConfig.java<br>    │   └── resources<br>    │       ├── application.properties<br>    │       └── schema.sql<br>    └── test<br>        ├── java<br>        │   └── example<br>        │       └── cashcard<br>        │           ├── CashCardApplicationTests.java<br>        └── resources<br>            ├── data.sql</pre><p>Ignore the schema.sql and data.sqlfor now.</p><p>One Common concept associated with REST is the Hypertext Transfer Protocol. In <strong>HTTP</strong>, a caller sends a Request to a URI. A web server receives the request, and routes it to a request handler. The handler creates a Response, which is then sent back to the caller.</p><p>The components of the Request and Response are:</p><p><em>Request</em></p><ul><li>Method (also called Verb)</li><li>URI (also called Endpoint)</li><li>Body</li></ul><p><em>Response</em></p><ul><li>Status Code</li><li>Body</li></ul><p>Associating the CRUD with HTTP Methods using the Family Cash Card example application, our endpoint that is routed-to will be /cashcards .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*qeD1XNAV4LGjj0Py7wRYsA.png" /><figcaption>REST, CRUD &amp; HTTP</figcaption></figure><p>Since REST says that Read endpoints should use the HTTP GET method, you need to tell Spring to route requests to the method only on GET requests. You can use @GetMapping annotation, which needs the URI Path, in your CashCardController.java:</p><pre>@RestController<br>class CashCardController {<br>  @GetMapping(&quot;/cashcards/{requestedId}&quot;)<br>  private ResponseEntity&lt;CashCard&gt; findById(@PathVariable Long requestedId) {<br>     CashCard cashCard = /* Here would be the code to retrieve the CashCard */;<br>     return ResponseEntity.ok(cashCard);<br>  }<br>}</pre><p><strong>Controller-Repository Architecture: </strong>The Controller-Repository architecture is a design pattern where the Controller handles incoming requests, processes them, and interacts with the Repository to manage data storage and retrieval.</p><p>For our Repository selection, we’ll use a specific type of Repository: Spring Data’s CrudRepository.</p><p>Make sure you add the spring-data-jdbcdependency in your build.gradle file</p><pre>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br>    testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br>    testRuntimeOnly &#39;org.junit.platform:junit-platform-launcher&#39; // See https://docs.gradle.org/8.3/userguide/upgrading_version_8.html#test_framework_implementation_dependencies<br><br>    // this<br>    implementation &#39;org.springframework.data:spring-data-jdbc&#39;<br>}</pre><p>The following is a complete implementation of all CRUD operations by extending CrudRepository:</p><pre>interface CashCardRepository extends CrudRepository&lt;CashCard, Long&gt; {<br>}</pre><p>With just the implementation above, a caller can call any number of predefined CrudRepository methods, such as findById:</p><pre>cashCard = cashCardRepository.findById(99);</pre><p>How? Well, Spring Data takes care of the implementation :)</p><p>The <strong>repository</strong> in this guide will be associated with an <strong>H2 in-memory</strong> database, specifically tailored for testing purposes. This setup ensures a streamlined and efficient testing environment without impacting your production database.</p><p>For that, we will be adding the following dependency to our build.gradle</p><pre>implementation &#39;com.h2database:h2&#39;</pre><blockquote>Spring Boot will automatically configure our application to communicate with H2.</blockquote><p>Now, let’s use these tools to complete our findById() methods in the Controller; First, consider this code snippet in our CashCardController.java</p><pre> private CashCardController(CashCardRepository cashCardRepository) {<br>     this.cashCardRepository = cashCardRepository;<br> }</pre><p>The type of injection demonstrated in the controller constructor is known as constructor injection. In this approach, dependencies, in this case, the ‘CashCardRepositoryCashCardRepository, are injected through the constructor when creating an instance of the CashCardController class. This is a common and recommended method for injecting dependencies in Spring applications, promoting cleaner code and facilitating easier testing and maintenance.</p><p>We have to initialize our in memory Database with some data to work on, for that reason, the data.sql and schema.sql exist within our app structure.</p><pre>-- data.sql<br>INSERT INTO CASH_CARD(ID, AMOUNT) VALUES (99, 123.45);<br>INSERT INTO CASH_CARD(ID, AMOUNT) VALUES (100, 1.00);<br>INSERT INTO CASH_CARD(ID, AMOUNT) VALUES (101, 150.00);</pre><pre>-- schema.sql<br>CREATE TABLE cash_card<br>(<br>    ID       BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,<br>    AMOUNT   NUMBER NOT NULL DEFAULT 0,<br>);</pre><p>Thanks to spring <strong>auto-configuration,</strong> once the application starts, the in-memory database will start, and an auto-communication will be satisfied, the in-memory database shuts down once the application quits execution.</p><p>Now that the application has a data source, we can proceed with the updated version of our findById() controller method.</p><pre>    @GetMapping(&quot;/{requestedId}&quot;)<br>    private ResponseEntity&lt;CashCard&gt; findById(@PathVariable Long requestedId) {<br>        Optional&lt;CashCard&gt; cashCardOptional = cashCardRepository.findById(requestedId);<br>        if (cashCardOptional.isPresent()) {<br>            return ResponseEntity.ok(cashCardOptional.get());<br>        } else {<br>            return ResponseEntity.notFound().build();<br>        }<br>    }</pre><p>We use <strong>Optional</strong> container object because it may or may not contain a non-null value. Mostly used to avoid Nulls and work with Null-Safe Operations.</p><blockquote>Success (200 OK): The request was successful, and the response contains the requested data.</blockquote><blockquote>Failure (404 Not Found): The requested resource could not be found on the server.</blockquote><p>Now that we implemented a well structured method to <strong>READ</strong> an information, let’s jump into the next CRUD operation <strong>CREATE</strong> handled by the createCashCard method that takes two arguments, the new cash card to add and a URI builder to build a unique URI for our newly created cashcard.</p><p>Adding the following code to our CashCardController.java :</p><pre>    @PostMapping<br>    private ResponseEntity&lt;Void&gt; createCashCard(@RequestBody CashCard newCashCardRequest, UriComponentsBuilder ucb) {<br>        CashCard savedCashCard = cashCardRepository.save(newCashCardRequest);<br>        URI locationOfNewCashCard = ucb<br>                .path(&quot;cashcards/{id}&quot;)<br>                .buildAndExpand(savedCashCard.id())<br>                .toUri();<br>        return ResponseEntity.created(locationOfNewCashCard).build();<br>    }</pre><p>Notice that, as we mentionned before, we are not supplying an ID for this operation, it absolutely makes no sense.</p><p>So what we did above is basically saving the passed new cash card to the database and creating a unique URI (Uniform Ressource Identifier) for the item so it can be deleted or updated after.</p><blockquote>Success (201 Created): The resource has been successfully created. The server should include a ‘Location’ header with the URL of the newly created resource.</blockquote><blockquote>Failure (e.g., 400 Bad Request): The request is malformed, or the server couldn’t process it.</blockquote><p><strong>The </strong><strong>CashCardController.java :</strong></p><pre>package example.cashcard;<br><br>import org.springframework.data.domain.Sort;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.*;<br>import org.springframework.web.util.UriComponentsBuilder;<br><br>import java.net.URI;<br>import java.util.List;<br>import java.util.Optional;<br><br>@RestController<br>@RequestMapping(&quot;/cashcards&quot;)<br>class CashCardController {<br>    private final CashCardRepository cashCardRepository;<br><br>    private CashCardController(CashCardRepository cashCardRepository) {<br>        this.cashCardRepository = cashCardRepository;<br>    }<br><br>    @GetMapping(&quot;/{requestedId}&quot;)<br>    private ResponseEntity&lt;CashCard&gt; findById(@PathVariable Long requestedId) {<br>        Optional&lt;CashCard&gt; cashCardOptional = cashCardRepository.findById(requestedId);<br>        if (cashCardOptional.isPresent()) {<br>            return ResponseEntity.ok(cashCardOptional.get());<br>        } else {<br>            return ResponseEntity.notFound().build();<br>        }<br>    }<br><br>    @PostMapping<br>    private ResponseEntity&lt;Void&gt; createCashCard(@RequestBody CashCard newCashCardRequest, UriComponentsBuilder ucb) {<br>        CashCard savedCashCard = cashCardRepository.save(newCashCardRequest);<br>        URI locationOfNewCashCard = ucb<br>                .path(&quot;cashcards/{id}&quot;)<br>                .buildAndExpand(savedCashCard.id())<br>                .toUri();<br>        return ResponseEntity.created(locationOfNewCashCard).build();<br>    }<br>}</pre><p>Having covered individual Cash Card operations, let’s now shift our focus to managing collections. In the next segment, we’ll explore how to retrieve lists of Cash Cards using GET, incorporating features like <strong>paging and sorting</strong>. This enhancement allows us to handle larger datasets efficiently.</p><h4>Returning a List with GET (Paging &amp; Sorting)</h4><ul><li>How can we efficiently present a large set of resources without overwhelming the client?</li><li>What mechanism allows us to navigate through different portions of a dataset seamlessly?</li></ul><p>Answer — <strong>Paging: </strong>a technique used to break down a large set of data into smaller, more manageable subsets called pages. Each page contains a specific number of items. This approach is particularly useful when dealing with extensive datasets, ensuring efficient data retrieval and reduced load on both the server and the client.</p><ul><li>How can users request data in a specific order, such as ascending or descending? —</li><li>What feature enables the dynamic arrangement of resources based on user-defined criteria?</li></ul><p>Answer — <strong>Sorting</strong>: Sorting involves arranging data based on specific criteria, such as ascending or descending order. In the context of a RESTful API, sorting allows clients to receive data in a predetermined sequence, enhancing user experience and facilitating easier analysis.</p><ul><li>How can we represent information about the current page and sorting criteria in our API requests? —</li><li>What abstraction simplifies the integration of paging and sorting parameters in our repository queries?</li></ul><p>Answer —<strong> Pageable</strong>: The ‘Pageable’ object is a versatile abstraction in Spring that encapsulates information about page size, page number, and sorting criteria.</p><p>The updated CashCardRepository.java :</p><pre>import org.springframework.data.repository.CrudRepository;<br>import org.springframework.data.repository.PagingAndSortingRepository;<br><br>interface CashCardRepository extends CrudRepository&lt;CashCard, Long&gt;, PagingAndSortingRepository&lt;CashCard, Long&gt; { ... }</pre><p><strong>The URI:</strong></p><p>Now let’s learn how we can compose a URI for the new endpoint, step-by-step (we’ve omitted the https://domain prefix in the following):</p><p>Get the second page (index starts at 0) with the size of 3 (3 items per page) sorted by the object property: amount, in a descendent order</p><pre>/cashcards?page=1&amp;size=3&amp;sort=amount,desc</pre><p>The complete implementation of the Controller method for our new “get a page of Cash Cards” endpoint, add the following method to the CashCardController.java</p><pre>    @GetMapping<br>    private ResponseEntity&lt;List&lt;CashCard&gt;&gt; findAll(Pageable pageable) {<br>        Page&lt;CashCard&gt; page = cashCardRepository.findAll(<br>                PageRequest.of(<br>                        pageable.getPageNumber(),<br>                        pageable.getPageSize(),<br>                        pageable.getSortOr(Sort.by(Sort.Direction.ASC, &quot;amount&quot;))<br>                ));<br>        return ResponseEntity.ok(page.getContent());<br>    }</pre><p>We use Pageable, which allows Spring to parse out the page number and size query string parameters.</p><blockquote>Note: If the caller doesn’t provide the parameters, Spring provides defaults: page=0, size=20.</blockquote><p>We use getSortOr() so that even if the caller doesn’t supply the sort parameter, there is a default.</p><p>— I’ve decided to postpone the implementation of the <strong>PUT</strong> and <strong>DELETE</strong> methods. As I’ve already covered the fundamental aspects, these methods won’t pose a significant challenge. We’ll address them in a subsequent document at a later time.</p><h3>Securing the API: Simple Spring Security</h3><p>Till now, these are the implemented dependencies within the build.gradle file</p><pre>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br>    testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br>    testRuntimeOnly &#39;org.junit.platform:junit-platform-launcher&#39; // See https://docs.gradle.org/8.3/userguide/upgrading_version_8.html#test_framework_implementation_dependencies<br><br>    implementation &#39;org.springframework.data:spring-data-jdbc&#39;<br>    implementation &#39;com.h2database:h2&#39;<br>}</pre><h4>What will be covered</h4><p>We will briefly overview the Same Origin Policy (SOP) and common <a href="https://www.mosse-institute.com/bootcamps/web-exploitation.html#:~:text=Web%20exploitation%20is%20the%20process,launch%20attacks%20on%20other%20systems.">Web Exploits</a>, while our primary focus will be on understanding HTTP Authentication and Authorization. We will delve into how these mechanisms work and how we can leverage Spring Security to prevent unauthorized access.</p><h3>Same Origin Policy (SOP)</h3><p>The web is fraught with security risks. The Same Origin Policy (SOP) is a basic protective measure implemented by HTTP clients and servers. It allows only scripts within a web page to send requests to the page’s origin (URI).</p><p>SOP is vital for website security, preventing unauthorized scripts from sending requests to other sites, which could lead to malicious actions, such as unauthorized bank transactions</p><h4>Cross-Origin Resource Sharing</h4><p>In systems with services on different URIs (like Microservices), Cross-Origin Resource Sharing (CORS) allows browsers and servers to relax the Same Origin Policy (SOP). Servers can permit a list of “allowed origins” for requests from outside their origin.</p><p>Spring Security’s <strong><em>@CrossOrigin</em></strong> annotation lets you specify allowed sites. However, using it without arguments allows all origins, so caution is advised.</p><h3>Common Web Exploits</h3><p>In addition to taking advantage of known security flaws, cybercriminals are continually unearthing new vulnerabilities on the web. Fortunately, Spring Security offers a robust suite of tools to defend against prevalent security breaches. We will delve into two typical exploits, understand their mechanisms, and explore how Spring Security aids in their prevention.</p><h4>Cross-Site Request Forgery (CSRF)</h4><p>Cross-Site Request Forgery (CSRF), or “Sea-Surf”, is a vulnerability enabled by <a href="https://www.kaspersky.com/resource-center/definitions/cookies">Cookies</a>, also known as Session Riding. It occurs when malicious code sends a request to an authenticated server, which can’t distinguish if the request was unintended.</p><p>To counter CSRF attacks, a <strong>CSRF Token </strong>is used. Unlike an Auth Token, a CSRF Token is unique per request, making it difficult for an external actor to interfere in the client-server interaction.</p><p>Spring Security offers default support for CSRF tokens, providing an additional layer of protection.</p><h4>Cross-Site Scripting (XSS)</h4><p>Cross-Site Scripting (XSS) is a serious vulnerability where an attacker manipulates a victim application into running arbitrary code. This can be done in various ways, such as storing a string with a &lt;script&gt; tag in a database and waiting for it to be rendered on a webpage, executing the script.</p><blockquote>XSS is potentially more dangerous than CSRF. In CSRF, only actions that a user is authorized to do can be executed. However in XSS, <em>arbitrary malicious code</em> executes <em>on the client or on the server</em>. Additionally, XSS attacks don’t depend on Authentication. Rather, XSS attacks depend on security “<strong>holes</strong>” caused by poor programming practices.</blockquote><p>The primary defense against XSS attacks is correct processing of all data from external sources, like web forms and URI query strings. For instance, attacks using &lt;script&gt; tags can be mitigated by correctly escaping special HTML characters when rendering the string.</p><h3>Understanding HTTP Authentication and Authorization</h3><p>Securing a web application requires both authentication and authorization.</p><p><strong>Authentication</strong> checks the identity of a user, for example, by requesting a username and password.</p><p><strong>Authorization</strong> allows or restricts access to certain resources or actions based on the user’s role, permissions, or other factors.</p><blockquote>W<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization">hen we talk about authentication and authorization, we are usually referring to how they are implemented using HTTP headers, methods, status codes, and other features of the protocol</a>.</blockquote><p><strong>Spring Security</strong> is a robust framework that supports both authentication and authorization in Spring Boot applications. It has various features and mechanisms to handle different kinds of authentication and authorization scenarios, such as form-based login, OAuth2, JWT, role-based access control, method security, and more…</p><h3>Spring Security</h3><p>Spring Security is a framework that provides authentication and authorization for Spring-based applications. It supports various mechanisms to secure both imperative and reactive web applications, such as form-based login, OAuth2, JWT, role-based access control, method security, and more.</p><h3>Implementing Simple Spring Security</h3><p>Based on our case example, the Family Cash Card Application, we can assume that the user who created the Cash Card is the “<strong>card owner</strong>”. Only the card owner can see or modify a Cash Card.</p><p>The logic will look like this:</p><blockquote>IF the user is logged in</blockquote><blockquote>— AND they have the “card owner” role</blockquote><blockquote>— — AND they possess the requested Cash Card</blockquote><blockquote>— — — THEN fulfill the user’s request</blockquote><blockquote>BUT prevent users from accessing Cash Cards that are not theirs.</blockquote><h4>Security Requirements</h4><p>In anticipation of this, we implemented the idea of an ‘<strong>owner</strong>’ within the application.</p><p>The ‘<strong>owner</strong>’ represents the distinct identity of the individual who has the authority to create and oversee a specific Cash Card.</p><p>Let’s go over the modifications we’ve made:</p><ul><li>We’ve incorporated ‘<strong>owner</strong>’ as a field in the CashCard Java record.</li></ul><pre>import org.springframework.data.annotation.Id;<br><br>record CashCard(@Id Long id, Double amount, String owner) {<br>}</pre><ul><li>We’ve included ‘owner’ in all <strong>.sql</strong> files (schema.sql &amp; data.sql)</li></ul><pre>CREATE TABLE cash_card<br>(<br>    ID       BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,<br>    AMOUNT   NUMBER NOT NULL DEFAULT 0,<br>    OWNER    VARCHAR(256) NOT NULL<br>);</pre><pre>INSERT INTO CASH_CARD(ID, AMOUNT, OWNER) VALUES (99, 123.45, &#39;sarah1&#39;);<br>INSERT INTO CASH_CARD(ID, AMOUNT, OWNER) VALUES (100, 1.00, &#39;sarah1&#39;);<br>INSERT INTO CASH_CARD(ID, AMOUNT, OWNER) VALUES (101, 150.00, &#39;sarah1&#39;);</pre><p>Next, we added the spring-boot-starter-security implementation to our build.gradle in the dependencies{} section</p><pre>implementation: &#39;org.springframework.boot:spring-boot-starter-security&#39;</pre><p><strong>!Very Important: </strong>Upon integrating the Spring Security dependency into our application, security features were automatically activated. Given that we haven’t defined the procedures for authentication and authorization within our Cash Card API, <strong>Spring Security has effectively imposed a full restriction on our API.</strong></p><p>Which means we have to <strong>Configure Spring Security</strong> ourselves for our application in order to unlock our API, Spring security did lock it by default, just by adding the dependency.</p><blockquote>Locking down a RESTful API in our case means that none of the API’s endpoints are accessible.</blockquote><p>And if you ran a unit test (using the ./gradlew test command) within your application after directly adding the dependency, all your API endpoints tests will fail resulting in an output similar to the one below</p><pre>expected: &lt;SOME NUMBER&gt;<br> but was: 0</pre><h4>Configuring Spring Security</h4><p>Annotate the SecurityConfig class located in the SecurityConfig.java file with the @Configuration annotation.</p><p>The @Configuration annotation tells Spring to use this class to configure Spring and Spring Boot itself. Any Beans specified in this class will now be available to Spring&#39;s Auto Configuration engine.</p><pre>@Configuration<br>class SecurityConfig {<br><br>}</pre><h4>Enabling Basic Authentification</h4><p>Add the following Bean to yourSecurityConfig class, the reason a @Bean annotation was added is that Spring Security expects a Bean to configure its <strong>Filter Chain.</strong></p><pre>    @Bean<br>    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {<br>        http<br>                .authorizeHttpRequests(request -&gt; request<br>                        .requestMatchers(&quot;/cashcards/**&quot;)<br>                        .authenticated())<br>                .csrf(csrf -&gt; csrf.disable())<br>                .httpBasic(Customizer.withDefaults());<br>        return http.build();<br>    }</pre><p>Explanation:</p><ul><li><em>All HTTP requests to </em><em>cashcards/ endpoints are required to be authenticated using HTTP Basic Authentication security (username and password).</em></li><li><em>Also, do not require CSRF security.</em></li></ul><p>Now The Authentification is <strong>enabled,</strong> let’s provide a username and password with out HTTP requests. To do this and since we are relying on In-Memory-Only Data for testing purposes, we’ll use an InMemoryUserDetailsManager and configuring a UserDetailsService bean.</p><p>Add the following bean to your SecurityConfig class</p><pre>  @Bean<br>  UserDetailsService testOnlyUsers(PasswordEncoder passwordEncoder) {<br>   User.UserBuilder users = User.builder();<br>   UserDetails sarah = users<br>     .username(&quot;sarah1&quot;)<br>     .password(passwordEncoder.encode(&quot;abc123&quot;))<br>     .roles() // No roles for now<br>     .build();<br>   return new InMemoryUserDetailsManager(sarah);<br>  }</pre><p>Easy to understand, we’ve configured in our memory a username of ‘sarah1’ with a password ‘abc123’.</p><p>Spring’s IoC container will find the UserDetailsService Bean and Spring Data will use it when needed.</p><pre>[~/demo] $ ./gradlew test<br>...<br>BUILD SUCCESSFUL in 9s</pre><p>And with only that, we’ve implemented and tested Basic Auth!</p><h4>Support Authorization</h4><p>We’ll implement <a href="https://auth0.com/docs/manage-users/access-control/rbac#:~:text=Role%2Dbased%20access%20control%20(RBAC,assigning%20permissions%20to%20users%20individually.">Role-Based Access Control</a> (RBAC).</p><blockquote>RBAC refers to the idea of assigning permissions to users based on their role within an organization.</blockquote><p><strong>Setup</strong>: Update SecurityConfig.testOnlyUsers and add the CARD-OWNER role to sarah1. Also, let’s add a new user named “hank-owns-no-cards” with a role of NON-OWNER.</p><pre>@Bean<br>UserDetailsService testOnlyUsers(PasswordEncoder passwordEncoder) {<br>  User.UserBuilder users = User.builder();<br>  UserDetails sarah = users<br>    .username(&quot;sarah1&quot;)<br>    .password(passwordEncoder.encode(&quot;abc123&quot;))<br>    .roles(&quot;CARD-OWNER&quot;) // new role<br>    .build();<br>  UserDetails hankOwnsNoCards = users<br>    .username(&quot;hank-owns-no-cards&quot;)<br>    .password(passwordEncoder.encode(&quot;qrs456&quot;))<br>    .roles(&quot;NON-OWNER&quot;) // new role<br>    .build();<br>  return new InMemoryUserDetailsManager(sarah, hankOwnsNoCards);<br>}</pre><p>Edit SecurityConfig.filterChain to restrict access to only users with the CARD-OWNER role.</p><pre>@Bean<br>SecurityFilterChain filterChain(HttpSecurity http) throws Exception {<br>     http<br>             .authorizeHttpRequests(request -&gt; request<br>                     .requestMatchers(&quot;/cashcards/**&quot;)<br>                     .hasRole(&quot;CARD-OWNER&quot;)) // enable RBAC: Replace the .authenticated() call with the hasRole(...) call.<br>             .csrf(csrf -&gt; csrf.disable())<br>             .httpBasic(Customizer.withDefaults());<br>     return http.build();<br>}</pre><p>Let’s throw a simple test to see if RBAC is enabled in our ~/demo/src/test/java/example/cashcard/CashCardApplicationTests.java file</p><pre>@Test<br>void shouldRejectUsersWhoAreNotCardOwners() {<br>    ResponseEntity&lt;String&gt; response = restTemplate<br>      .withBasicAuth(&quot;hank-owns-no-cards&quot;, &quot;qrs456&quot;)<br>      .getForEntity(&quot;/cashcards/99&quot;, String.class);<br>    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);<br>}</pre><p>As we run this test using</p><pre>./gradlew test</pre><p>The output comes with the message</p><pre>[~/demo] $ ./gradlew test<br>...<br>CashCardApplicationTests &gt; shouldRejectUsersWhoAreNotCardOwners() PASSED</pre><p>A 403 FORBIDDEN HTTP code was returned indicating that the user with the cardentials {username: ‘hank-owns-no-cards’, password: passwordEncoder.encode(“qrs456”), role: ‘NON-OWNER’} was successfully rejected from accessing the /cashcards/99 endpoint since it’s reserved for sarah1 only.</p><p>Congratulations! Successfully implemented the RBAC-Based Authorization, Even though, <strong>we still have a glaring security hole in our application!</strong></p><h4>Repository Updates</h4><p>As mentioned in the previous section, we have a glaring security hole in our application.</p><p>The problem is that any user with the CARD-OWNER role will have full access to other user’s data (Cash Cards), therefore:</p><ul><li>We’ll add functionality to CashCardRepository to restrict or &quot;<strong>scope</strong>&quot; queries to the correct OWNER.</li><li>Next, we’ll update our CashCardController to guarantee that only the correct OWNER is used.</li></ul><p>Let’s update the findBy methods within the CashCardRepository</p><pre>...<br>import org.springframework.data.domain.Page;<br>import org.springframework.data.domain.PageRequest;<br>...<br><br>interface CashCardRepository extends CrudRepository&lt;CashCard, Long&gt;, PagingAndSortingRepository&lt;CashCard, Long&gt; {<br>   CashCard findByIdAndOwner(Long id, String owner);<br>   Page&lt;CashCard&gt; findByOwner(String owner, PageRequest pageRequest);<br>}</pre><p>As you see, we are enforcing both methods to take an owner argument. These repository CRUD methods are based on pre-defined sequences of SQL Querries that we ourselves don’t have to implement.</p><blockquote>Spring Data will take care of the actual implementations (writing the SQL queries) for us. Spring Data also allows you to use your own SQL if needed (Customizable) using the @Querry annotation.</blockquote><h4>Controller Updates</h4><p>Now, that the CashCardRepository supports filtering by owner , all what’s left is to use this functionality in our CashCardController .</p><p>To do that, we will be introducing the concept of a Principal , the Principal <strong>is basicaly an object that holds our user&#39;s authenticated, authorized information</strong>.</p><p>So, let’s update our GET methods first by introducing the Principal :</p><pre>    @GetMapping(&quot;/{requestedId}&quot;)<br>    private ResponseEntity&lt;CashCard&gt; findById(@PathVariable Long requestedId, Principal principal) {<br>        Optional&lt;CashCard&gt; cashCardOptional = Optional.ofNullable(cashCardRepository.findByIdAndOwner(requestedId, principal.getName()));<br>        if (cashCardOptional.isPresent()) {<br>            return ResponseEntity.ok(cashCardOptional.get());<br>        } else {<br>            return ResponseEntity.notFound().build();<br>        }<br>    }<br><br>    @GetMapping<br>    private ResponseEntity&lt;List&lt;CashCard&gt;&gt; findAll(Pageable pageable, Principal principal) {<br>        Page&lt;CashCard&gt; page = cashCardRepository.findByOwner(principal.getName(),<br>                PageRequest.of(<br>                        pageable.getPageNumber(),<br>                        pageable.getPageSize(),<br>                        pageable.getSortOr(Sort.by(Sort.Direction.ASC, &quot;amount&quot;))<br>                ));<br>        return ResponseEntity.ok(page.getContent());<br>    }</pre><p>Note that principal.getName() will return the username provided from Basic Auth (<em>must be unique</em>).</p><p>Since we are reading/filtering by owner , a cash card must be saved with a specific owner right? Update the POST endpoint in the Controller:</p><pre>    @PostMapping<br>    private ResponseEntity&lt;Void&gt; createCashCard(@RequestBody CashCard newCashCardRequest, UriComponentsBuilder ucb, Principal principal) {<br>        CashCard cashCardWithOwner = new CashCard(null, newCashCardRequest.amount(), principal.getName());<br>        CashCard savedCashCard = cashCardRepository.save(cashCardWithOwner);<br>        URI locationOfNewCashCard = ucb<br>                .path(&quot;cashcards/{id}&quot;)<br>                .buildAndExpand(savedCashCard.id())<br>                .toUri();<br>        return ResponseEntity.created(locationOfNewCashCard).build();<br>    }</pre><p>We used the provided Principal to ensure that the correct owner is saved with the new CashCard.</p><p>— Great Job!</p><h3>Educational Insight: Managing Errors with Spring Security</h3><p>Our Controller will be issuing a <strong>403 FORBIDDEN</strong> response instead of a typical error response. This is because Spring Security is automatically adopting a best practice for managing errors in Spring Web.</p><p>It’s important to realize that any data returned by our application could potentially aid a malicious actor in breaching our application’s security. For instance, information about actions that lead to our application encountering an error.</p><p>To prevent the inadvertent disclosure of information about our application, Spring Security has set up Spring Web to issue a <em>generic 403 FORBIDDEN response under most error circumstances</em>. If nearly all actions result in a 403 FORBIDDEN response, then an attacker is left in the dark about what’s really happening.</p><h3>Summary</h3><p>In this document, we’ve embarked on an enlightening journey through the fundamentals of a RESTful API using Spring, and how to secure it.</p><p>We’ve learned that the ‘owner’ is a unique identity, giving the authority to create and manage a specific Cash Card. We’ve also discovered how Spring Security, when added to our application, automatically enables security features.</p><p>We’ve understood that in the absence of defined authentication and authorization procedures, Spring Security locks down our API, making none of its endpoints accessible. This is a <em>wild</em> security measure to prevent unauthorized access.</p><p>Moreover, we’ve grasped how Spring Security manages errors to avoid leaking information that could be useful to malicious actors. It’s configured to return a generic 403 FORBIDDEN response in most error situations, keeping potential attackers in the dark.</p><p>This document serves as a stepping stone towards mastering RESTful APIs in Spring and their security. The journey doesn’t end here, though. There’s always more to learn and explore!</p><h4>Further Resources</h4><p>For further reading and resources, please refer to the following:</p><ol><li><a href="https://spring.io/guides/gs/testing-restdocs/">Spring Docs</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Glossary/REST">MDN Web Docs</a></li><li><a href="https://www.javatpoint.com/restful-web-services-spring-boot">JavatPoint</a></li></ol><p><em>Keep exploring, keep learning, and remember, every step you take is a step closer to mastery. Happy coding!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a6d1346ff1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>