<?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 Coffee &amp; Cloud ☕️☁️ on Medium]]></title>
        <description><![CDATA[Stories by Coffee &amp; Cloud ☕️☁️ on Medium]]></description>
        <link>https://medium.com/@coffeeandcloud?source=rss-f3df7deeeb40------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GqGSAiWViRQXhaeGbRpVMw.jpeg</url>
            <title>Stories by Coffee &amp;amp; Cloud ☕️☁️ on Medium</title>
            <link>https://medium.com/@coffeeandcloud?source=rss-f3df7deeeb40------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 19:23:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@coffeeandcloud/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[JWKS Authentication with Micronaut]]></title>
            <link>https://medium.com/@coffeeandcloud/jwks-authentication-with-micronaut-bf28845d3b61?source=rss-f3df7deeeb40------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf28845d3b61</guid>
            <dc:creator><![CDATA[Coffee & Cloud ☕️☁️]]></dc:creator>
            <pubDate>Fri, 01 Mar 2019 17:41:09 GMT</pubDate>
            <atom:updated>2019-03-01T17:41:09.482Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lUoLfQX-2pHqIZ04XyuPCQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/Jztmx9yqjBw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ryan Hutton</a> on <a href="https://unsplash.com/search/photos/galaxy?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><a href="https://micronaut.io/">Micronaut</a> [1] is a new framework for building backend applications in a very fast and lightweight fashion. Through mechanisms like the inversion of control and dependency injection, it is comparable to Spring Boot but with much less overhead. So it is much more suitable for developing microservices and API driven backends. Those applications often need some kind of authentication to keep their routes secure. This article should show how the popular usage of JWT’s can integrate easily with external identity providers like AWS Cognito, Auth0 or any other provider supporting OAuth and OpenID.</p><h4>Json Web Tokens</h4><p>The benefit of using Json Web Tokens within microservice architectures is the principle of digitally signing the token payload and ensure data integrity without the need for validating against the issuing authority. This allows users to issue a token from an external service and pass it to any microservice instance for authentication. The token gets signed by the identity provider with a private key (secret) and can be verified by the resource server or any other participant who knows the corresponding public key. Therefore, the public key can be safely distributed to all microservice instances avoiding the theft of confidential credentials.</p><p>A JWT is based on the RFC-7519 specification and composed of header, payload, and signature — three base64 encoded strings concatenated by a period [2]. It can look something like the following code snippet:</p><pre>eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoLnN1bGt5bG9vcHMuY29tIiwiaWF0IjoxNTUxMTE5OTA5LCJleHAiOjE1ODI2NTU5MDksImF1ZCI6Ind3dy5zdWxreWxvb3BzLmNvbSIsInN1YiI6Impyb2NrZXRAZXhhbXBsZS5jb20iLCJuYW1lIjoiTWlrZSIsIkVtYWlsIjoibWFrZUBzdWxreWxvb3BzLmNvbSIsIlJvbGUiOlsiYWRtaW4iLCJ1c2VyIl19.gPi05cl6lUT5OwZN19fIZ30Owq4kOJzxlkO3K9ccZ-Q</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VPDJLn23kOnesJv4YlZ48Q.png" /><figcaption>Decoded token on <a href="https://jwt.io/">jwt.io</a></figcaption></figure><blockquote><strong>Tip:</strong> A simple solution to show and verify a retrieved token is by using the online decoder hosted on <a href="https://jwt.io/">jwt.io</a>. Just paste your token and have a look at all attributes contained [3].</blockquote><h4>JWKS: JWT Key Set</h4><p>When the authentication authority is using RSA as an asymmetric encryption standard, then the public keys can be exposed over a public endpoint to allow the resource servers a standardized way to validate the tokens. This document is called a JWT key set and contains all information to decrypt the token signature and to validate it.</p><blockquote><strong>Note</strong>: This could vary on different authentication providers and is dependent on implementation.</blockquote><p>This endpoint normally is exposed under the following path of the authority providers root path:</p><pre>https://{your-oauth-provider.com}<strong>/.well-known/jwks.json</strong></pre><p>You can check if your provider is supporting this feature by calling this URL in your browser. The result should look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1b66cbd2478e8875b7aefe5e1cff0ea/href">https://medium.com/media/c1b66cbd2478e8875b7aefe5e1cff0ea/href</a></iframe><p>The JWKS document is specified after RFC-7517 and must contain an array of keys and the keys itself also require to have all the shown attributes. The array is needed because an authentication provider can manage multiple signing keys and the clients have to know which public key fits the JWT.</p><ul><li><strong>kid</strong>: The unique key id to fit the right public key to the JWT</li><li><strong>alg</strong>, <strong>kty</strong>, <strong>use</strong>: Format of the public key defined by the concrete algorithm, the key type, and its purpose. Mostly RSA is used, but also EC (elliptic curve) can be found here as an encryption standard.</li><li><strong>n</strong> and <strong>e: </strong>Modulus and exponent of the public key</li><li><strong>x5c</strong> and <strong>x5t</strong>: x.509 certificate chain and the thumbprint</li></ul><blockquote><strong>Note:</strong> JWKS endpoints are only available when using asymmetric key signatures like RSA or EC. Other algorithms like HS (HMAC with SHA) need same the secret for decryption as for encryption. That means, that secret must not be shared over a public endpoint! Otherwise, anyone can create and sign its own JWT.</blockquote><p>Through this document, the resource server is able to decrypt the signature and validate the JWT. Additional functionality can be found <a href="https://tools.ietf.org/html/rfc7517">in the RFC documentation [4]</a>.</p><h4>Verifying JWTs in theory</h4><p>The JWT verification on the resource server consists of four basic steps:</p><ol><li>Fetch the JWKS document from the authentication provider</li><li>Parse and build the Json file and set the right algorithms (e.g. RSA or EC)</li><li>Parse the token sent from the client (break it into header, payload, and signature)</li><li>Decrypt/validate the signature with the knowledge of the public key contained in the JWKS</li></ol><h4>Verifying JWTs using Micronaut</h4><p>All these steps can be done by using Micronauts JWKS implementation which is available since version 1.1.0.M1 (milestone).</p><blockquote><strong>Important:</strong> This feature is only available in milestone build which is not stable yet. In further versions, the following configuration is just ignored.</blockquote><p>By using the Micronaut CLI you can start a new project with the following command. This will create an application with Kotlin support and will add the “security-jwt” package correctly as a dependency.</p><pre>-&gt; mn create-app my-app -l=kotlin -features security-jwt</pre><p>Next, we will add a secured controller to our project. This is done by annotating the whole controller or single routes with “@Secured”. The controller will return the authentication object with all claims contained in the JWT as well as the additional information or 401 Forbidden when the token is invalid or not there (in the header). You can also directly access the “Principal” known from Java enterprise environments which can hold fine-grained information about the user, roles and permissions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9ab8b2e052ba63a9c14903af66f6010/href">https://medium.com/media/a9ab8b2e052ba63a9c14903af66f6010/href</a></iframe><p>The second thing we have to do is to configure the JWKS. This can be done by simply editing the application.yml file in the root of our project. Some of these parameters are already set through the CLI, but your security configuration should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1a820fb567d547df4160453df09c0de/href">https://medium.com/media/d1a820fb567d547df4160453df09c0de/href</a></iframe><p>Line 3 and 11 will enable Micronauts security config globally and allow the use of JWTs. The token object contains the JWKS signatures (line 13) which obviously can consist of multiple JWKS. The important thing here is to specify an element with the name of your provider, otherwise, the endpoint URL will not be parsed correctly. The name can just pick a random name you like and pass the URL attribute of the jwks.json provided by your authentication service.</p><blockquote><strong>Tip:</strong> For more information about other configuration options, you can refer to the <a href="https://micronaut-projects.github.io/micronaut-grpc/snapshot/guide/configurationreference.html">official Micronaut configuration reference [5]</a>.</blockquote><p>Additionally, I have disabled the “login” and “OAuth” endpoints. Those are used when the service acts as an authentication provider itself and exposes the endpoints for the OAuth flow and login page.</p><p>Now, when you start your project, the security provider will fetch the document from your authentication provider automatically and will validate all incoming tokens. You can check the configuration by sending a GET request containing the authorization header with your Bearer JWT token:</p><pre>curl -X GET <a href="http://localhost:8080/event">http://localhost:8080/event</a> \<br>-H &quot;Authorization: Bearer YOUR_JWT_TOKEN&quot;</pre><h4>Conclusion</h4><p>JWKS is an easy and flexible way to do JWT validation on microservices without the overhead of using an API gateway or other heavy authentication mechanisms. When the signing key of your authentication provider changes, no adaption of the microservices is needed. This is another great step into decoupling the architecture and separating the concerns.</p><p>Micronaut makes the implementation of this authentication mechanism very easy and straight forward without writing a lot of boilerplate code. Let’s see what the next releases will add.</p><h4>Further reading</h4><ul><li>[1] Micronaut Project (<a href="https://micronaut.io/">https://micronaut.io/</a>)</li><li>[2] RFC-7519 (<a href="https://tools.ietf.org/html/rfc7519">https://tools.ietf.org/html/rfc7519</a>)</li><li>[3] jwt.io (<a href="https://jwt.io/">https://jwt.io</a>)</li><li>[4] RFC-7517 (<a href="https://tools.ietf.org/html/rfc7517">https://tools.ietf.org/html/rfc7517</a>)</li><li>[5] Micronaut configuration reference (<a href="https://micronaut-projects.github.io/micronaut-grpc/snapshot/guide/configurationreference.html">https://micronaut-projects.github.io/micronaut-grpc/snapshot/guide/configurationreference.html</a>)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf28845d3b61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Approach to Clean Architecture in Angular Applications — Hands-on]]></title>
            <link>https://medium.com/intive-developers/approach-to-clean-architecture-in-angular-applications-hands-on-35145ceadc98?source=rss-f3df7deeeb40------2</link>
            <guid isPermaLink="false">https://medium.com/p/35145ceadc98</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <dc:creator><![CDATA[Coffee & Cloud ☕️☁️]]></dc:creator>
            <pubDate>Tue, 18 Dec 2018 11:23:46 GMT</pubDate>
            <atom:updated>2018-12-18T11:25:29.688Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zi28LnLlLMRrEyS0pJJlMA.jpeg" /></figure><h3>Approach to Clean Architecture in Angular Applications — Hands-on</h3><p>After we have seen in theory how a web application project can be structured according to Clean Architecture, let us see how we can implement this pattern in practice. If you have missed the introduction article, then you <a href="https://medium.com/@martinstimmzunge/angular-clean-architecture-approach-fcfe32e983a5">can find it here</a>. We will go through all layers and see what’s implemented there. You will find the <strong>whole code </strong><a href="https://github.com/im-a-giraffe/angular-clean-architecture"><strong>here</strong></a><strong>.</strong></p><p>The sample application is a birthday calendar for elephants. It is kept very simple to clarify the usage of Clean Architecture. It takes data from an API or a MockRepository included within the app and displays all Elephants and their birthdays in a table.</p><h3>Project Structure</h3><p>An Angular project could be structured in the following way, starting off with the known structure generated by the angular-cli.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*aaz5CiK3LgRqiyMDBQgEfQ.png" /><figcaption>Example of a project structure using the angular-cli combined with Clean Architecture</figcaption></figure><h3>Core Layer</h3><p>At first, let us have a look at our Core layer. As we know, we should define our core entities, usecases, repository interfaces, and mappers here. To keep the architecture clean and reusable, consider adding inheritance for the usecases and mappers.</p><h4>Core Entities</h4><p>The entities of this application are kept very simple, so an ElephantModel contains the elephant&#39;s name, its family status (mother, father, baby…) and a Date for its birthday. These are all information that’s our core application needs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/365af4b2713f2160a3f270b98ec70cf7/href">https://medium.com/media/365af4b2713f2160a3f270b98ec70cf7/href</a></iframe><h4>Usecase and Mapper Base</h4><p>A Typescript interface is sufficient to keep the mapping process of all entities through the whole project consistent. It has only two functions, one to <em>map from</em> the core entity layer, and one to <em>map to </em>the core entity layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31df63532b38c95935f6da35218993f0/href">https://medium.com/media/31df63532b38c95935f6da35218993f0/href</a></iframe><p>The usecase consists of one main function, that is called when we run our usecase and returns a RxJS observable. We also define an input parameter S to pass parameters during the usecase execution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8751f9ca3417f3d81e05531c77149f3/href">https://medium.com/media/f8751f9ca3417f3d81e05531c77149f3/href</a></iframe><h4>Repository Base and ElephantRepository</h4><p>Read and write operations are handled in this application through repositories. Please notice, that only the interfaces are specified there for each repository and that a repository interface does not have to be an actual repository. This means that these interfaces do not need to talk to a relational database or NoSQL store, but to a restful API for instance. As already mentioned earlier, using repository interfaces for querying APIs is a perfect fit, because a lot of APIs are based on CRUD operations which can be perfectly represented as a repository.</p><p>Our actual interface for our simple elephants birthday API provides queries to search for an elephant by its ID and list all elephants which are stored in the repository.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42e5059328d6a06385c966258a0eb566/href">https://medium.com/media/42e5059328d6a06385c966258a0eb566/href</a></iframe><p><strong>Note:</strong> Because we will later use this class as a base class for dependency injection with Angular, our repository <em>must be an abstract class</em>. This is caused by Typescript, that does not know interfaces at runtime and dependency injection will fail. Interfaces in Typescript are just present in static code checking but are removed during compiling.</p><h4>Usecases</h4><p>Finally, let us have a look at the core of our architecture pattern — the usecases. In our sample application, our usecases more or less duplicate the functionality of the repository but adding some level of abstraction in between. Remember, due to the dependency rule, usecases can only use layers which are lower than their current layer — in this case, that’s very easy because we only have our core layer and nothing underneath.</p><p>But does our usecase need to know where it can find the data? Not necessarily. The only way the usecase can talk to the data source is through the repository interface, which we will provide as a dependency like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/049acf3d2d09064ec0afd77a0165bb9a/href">https://medium.com/media/049acf3d2d09064ec0afd77a0165bb9a/href</a></iframe><p><strong>Note:</strong> As an attentive reader you may wonder why there is an Angular annotation on a core layer where theoretically should only be plain Typescript without any external dependencies to frameworks. The reason is, that Angular only has this @Injectable annotation to provide a module via dependency injection. As you may remember, we talked about a fourth layer that was called configuration. If Angular would have such a functionality like Spring Boot or Dagger does, then the configuration layer could take care of our dependency injection. But for now, we have to stick to this solution as long as we do not want to hack the dependency injection mechanism.</p><h3>Data Layer</h3><p>Moving on to the data layer, we start implementing the actual repository. To show the usage of the Clean Architecture approach, we implement the repository twice. First, a mock repository, secondly with a REST client that talks to a small API hosted <a href="https://www.mockapi.io/">mockAPI</a>.</p><p>Both implementations are very similar and consist of three classes:</p><ul><li>The actual<strong> repository</strong> that implements the repository interface defined in the core layer</li><li>The <strong>other elephant entity</strong> that the repository needs for managing and working with the data on database or API level</li><li>A <strong>mapper</strong> that translates the data objects from data layer representation into core entity representation and back</li></ul><p>This approach creates some overhead through the duplicate code and might seem a bit weird at first. Nevertheless, decoupling business logic entities, data layer entities and presentation layer entities can be very useful, because they often have different or additional fields caused by their usage.</p><p>There are a lot of scenarios in which the abstraction layer can be handy. In our application, the API, for example, is delivering the birthday of an elephant as milliseconds, but our core logic or data structure is more convenient and suitable with the Date format, so using one entity for both could be problematic. So our mapper simply converts the time formats back and forth.</p><h4>WebElephantRepository example</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/469005d4afc07a3eb081c0f1ae2a30f9/href">https://medium.com/media/469005d4afc07a3eb081c0f1ae2a30f9/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72f77dd2cea3869789f23537811cafcc/href">https://medium.com/media/72f77dd2cea3869789f23537811cafcc/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9dbcc0562fb630b6f8dabe3ab0f3af0/href">https://medium.com/media/d9dbcc0562fb630b6f8dabe3ab0f3af0/href</a></iframe><p>The repository implementation uses the standard Angular http client and maps the entities from the API format with the help of the mapper class into our applications core entity format.</p><h3>Presentation Layer</h3><p>Since we are now finished with our core business logic, usecases and the repository implementations, our application is ready to run — we just have to show that the application works. This is handled by the presentation layer. This layer can be as Angular as you want because you only make use of all underlying layers and call the usecases here. Since we defined our repositories as injectables, our usescases automatically know where to search for the right repository and— in addition — the repository can be easily exchanged through our interface!</p><p>But how does Angular know which repository we want to use? As we saw, we have two repositories implemented in this project — mock and web. We simply have to add one line to the module where we want to provide:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bc30eeb578954070841bba5e21ef91d/href">https://medium.com/media/0bc30eeb578954070841bba5e21ef91d/href</a></iframe><p>The “useClass” parameter offers the possibility to specify any class that implements the ElephantRepository interface. So just replace “ElephantMockRepository” with “ElephantWebRepository” and our app is ready to go online!</p><p>The rest of the presentation layer is really straightforward: Each component that has to access our elephant&#39;s list needs to get the right usecase injected and is ready to use the business logic just like it would use a service. Theoretically, the presentation layer should also have its own entity classes to show data on the UI.</p><h3>Conclusion</h3><p>Finally, I want to sum up with the benefits and drawbacks that Clean Architecture has to offer:</p><p>Pros:</p><ul><li>The <strong>architecture is “clean” and “screaming”</strong>: You can easily see what is going on in the project by looking at the usecase folder.</li><li><strong>Separation of concerns:</strong> Each application layer has its own responsibility, so functionality and framework logic is mixed up.</li><li><strong>Modularity:</strong> Since all core business logic is represented by interfaces (or also called contracts), implementation details are not part of the actual business logic. That is why the data is stored can simply be exchanged.</li><li><strong>Portability:</strong> The core module is written in pure Typescript, so theoretically the core logic could be transferred to other applications to share the same code base (e.g. backend).</li><li><strong>Testability:</strong> Even if this article did not (yet) covered testing, you can imagine that testing mockable interfaces and usecases without side effects is much more convenient.</li><li><strong>Universally applicable: </strong>Once the basic concepts of Clean Architecture are understood, it could be applied to any kind of application, ranging from backend to mobile or — as we just have seen — web development. Once all projects are equally structured, it is much easier to get onboarded.</li></ul><p>Cons:</p><ul><li><strong>Overhead:</strong> Separation and modularity are purchased in expense of more classes and interfaces.</li><li><strong>Duplication of code:</strong> Using different entities on each layer is automatically some kind of code duplication. On the one hand, decoupling is great to offer a layer of abstraction, but on the other hand, a new source of failure is introduced.</li><li><strong>Steep learning curve:</strong> For beginners, Clean Architecture does things very different than known form the actual framework.</li></ul><p>I hope you enjoyed my little introduction into the world of Clean Architecture and that it helps you at least with the last mentioned point in cons: Minimize the learning curve! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35145ceadc98" width="1" height="1" alt=""><hr><p><a href="https://medium.com/intive-developers/approach-to-clean-architecture-in-angular-applications-hands-on-35145ceadc98">Approach to Clean Architecture in Angular Applications — Hands-on</a> was originally published in <a href="https://medium.com/intive-developers">intive Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Approach to Clean Architecture in Angular Applications — Theory]]></title>
            <link>https://medium.com/@coffeeandcloud/angular-clean-architecture-approach-fcfe32e983a5?source=rss-f3df7deeeb40------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcfe32e983a5</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <dc:creator><![CDATA[Coffee & Cloud ☕️☁️]]></dc:creator>
            <pubDate>Tue, 18 Dec 2018 11:23:10 GMT</pubDate>
            <atom:updated>2018-12-18T11:26:29.620Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5Dsi3wRX8z9FXb6KssIfA.jpeg" /></figure><h3>Approach to Clean Architecture in Angular Applications — Theory</h3><p>If you are familiar with writing Angular applications, then you know that from early versions the framework supports you in creating and organizing your source files. This was more and more improved as the versions were going on. So why the heck should you care about using a more common architecture pattern for your web apps? Let’s first explain what all the rumors on clean architecture are about. If you’re already familiar with Clean Architecture, you may skip directly to the hands-on article.</p><h4>What is Clean Architecture?</h4><p>In short: Clean Architecture is a pattern for structuring an application architecture in general. It was originally introduced by Robert Martin, also known as Uncle Bob, who also published a lot of articles and books about writing clean and reusable code. His last book, Clean Architecture, sums up his thoughts and suggestions on how to improve your application’s structure on a higher level then clean code.</p><p>He researched about common architecture design and found out, that most popular architecture principles (e.g., just to name a few: Hexagonal Architecture, Onion Architecture or Screaming Architecture) have one main goal: Building some kind of application layers and creating a separation of concerns in this way. He also saw that every architecture tries at least to separate the business logic from the rest of the application and that these architectures produce systems that are</p><ol><li><strong>Independent of Frameworks:</strong> Your application should not be driven by the framework that is used.</li><li><strong>Testable:</strong> Your application and business logic should be testable without any dependencies to the user interface, database or web API.</li><li><strong>Independent of UI:</strong> Your applications user interface should control your business logic, but it should not control how your data flow is structured.</li><li><strong>Independent of Database:</strong> Your application should not be designed by the type of database that you are using. Your business logic does not care if its data entities are stored in a document store, relational database or in-memory.</li><li><strong>Independent of any external agency:</strong> Your business rules should only care about its own task and not anything else which possibly lives in your application.</li></ol><p>For detailed information, you can refer to his article on 8thlight [1]. So what does this mean for our web app development with Angular? Let’s try to apply these points to our beloved framework:</p><ol><li><strong>Independent of Frameworks:</strong> Our business logic and rules should not be affected by any functionality or structure of the Angular framework. This achieves more flexibility when updating to new versions (which may introduce new “architecture”/project structure) or switching to a completely different framework — because we don’t have to rely on any framework specific stuff. And also heads to the next point: Testability!</li><li><strong>Testable:</strong> Naively considered, we only have to test our business logic and rules, that makes testing a lot easier. So to test the core functionality of our application, no Angular specific tests like Karma are needed.</li><li><strong>Independent of UI:</strong> The business rules don’t care about how they are triggered or controlled. So no business logic should be placed inside of any UI controllers.</li><li><strong>Independent of Database:</strong> In general, web apps don’t care a lot about using databases, because they are mostly fed through APIs. But looking at the pattern of repositories, most apps do some kind of CRUD operations at some point. These can also be abstracted to repositories. Later in the article, you will see how repositories and APIs integrate perfectly.</li><li><strong>Independent of any external agency:</strong> As already mentioned, our core application logic should not be dependent on Angular framework functionality.</li></ol><h4>Structuring the project — in theory</h4><p>If you already read about building applications with the Clean Architecture pattern, then you should have definitely seen the following diagram that explains the general structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*B7LkQDyDqLN3rRSrNYkETA.jpeg" /><figcaption>Classic diagram of Clean Architecture [1]</figcaption></figure><p>Just to sum up the basic concepts, the spirit of clean architecture is based on building application layers which and shape, as already mentioned, a separation of concerns. Furthermore, there are some rules on how these layers should interact with each other:</p><ol><li>Core entities: These are plain data models which are essentially needed to represent our core logic, build a data flow upon and get our business rule working.</li><li>Usecases: These are built on top of the core entities and implement the whole business logic of the application. Usecases should “live in their own world” and only do what they are supposed to do.</li><li>Dependency rule: Each layer should only have access to the underneath layer. So, the usecase layer should only use entities which are specified in the entity layer, and the controller should only use usecases from the usecase layer below. You will get a better understanding in how this is working when you have a look at the hands-on article.</li><li>Interface adapters: To get a working architecture beyond the border of each layer, the best way is to work with interface adapters from the core (entity and usecase layer) to ensure a homogenous structure all over the projects, which fits like a puzzle in the end.</li></ol><h4>Structuring the project — in practice</h4><p>Because the Clean Architecture diagram and the rules are very general, let’s try to break it down and put it more in our context of web application development. At first, I like to straighten out, that Clean Architecture is a general pattern which is supposed to work on different platforms and ranges from backend over mobile up to web applications. That means, there is no best way how to implement it. The shown approach in this article series was primarily inspired by an article on Speakerdeck by Marko Milos [2].</p><p>The best way to map the layer principle into a project and code structure is by using some kind of packages and bundle all layer related classes and interfaces together. Remember, only higher layers are allowed to access lower layers, not vice versa. To guaranty the interoperability between the layers, it is also a good idea to specify interfaces (e.g. repositories) in a very low layer.</p><p>Most web applications are some kind of CRUD applications, thus we will focus on CRUD repositories/APIs in this series. So let’s assume we have the following package layers:</p><ol><li><strong>Core: </strong>The core package aggregate core entities, usecases, and interface definitions, because these are tied together closely. Usecases access entities directly and also have to work with interfaces within the business logic like saving data into repositories. Since our core package — according to the dependency rule — should not have any knowledge about the actual repository logic, but has to know how to call an interaction with a repository, it should be represented as an independent interface.</li><li><strong>Data: </strong>This layer deals with implementing the actual data interfaces and links the framework specific data saving logic (e.g. saving data into a local storage or sending them to an API) to an interactable adapter for our usecase specified in the underlying layer.</li><li><strong>Presentation: </strong>The presentation layer contains the classic angular structure with components and views as you already know them. Each component can now make use of the previously defined usecases to fill the components with business logic.</li><li><strong>Configuration:</strong> In non-angular contexts, we could make use of a configuration layer, which provides an abstraction of dependency injection and other configurable elements. But since we want to keep things simple in this introduction, we will directly use Angular modules for structuring our application and handling dependency injection.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*__dVBSYpbgHwdkIB4IiM-A.png" /><figcaption>Distribution of classes and entities over three layers.</figcaption></figure><h4>Layer-specific data objects and mappers</h4><p>So far so good, we know now about how our project can be structured. One last thing to mention is the importance of data objects over the whole architecture: Since our core package abstracts the business logic through usecases and entities, each application layer has to handle these. But the data objects on the data or presentation layer are mostly not the same which are used in the business logic. This is because APIs often provide more information, data repositories need some mapping functionality for object members or presentation data objects need some more fields to display the data as needed. To deal with this, it’s highly recommended to make use of layer-specific data objects and map these from and to the core entities when transferring data from usecases to repositories or presentation layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OFGygdA-FUx_MUkQeHyLOg.png" /><figcaption>Mapping process when saving and reading an entity from the presentation layer into a database or API.</figcaption></figure><p>The <a href="https://medium.com/@martinstimmzunge/approach-to-clean-architecture-in-angular-applications-hands-on-35145ceadc98">next article</a> shows in a hands-on manner how this theoretical approach will look like in practice.</p><ul><li>[1] The Clean Architecture, Uncle Bob <a href="https://8thlight.com/blog/uncle-bob/2012/08/13/the-clean-architecture.html">https://8thlight.com/blog/uncle-bob/2012/08/13/the-clean-architecture.html</a></li><li>[2] Clean Architecture on Android, Marko Milos <a href="https://speakerdeck.com/markomilos/clean-architecture-on-android">https://speakerdeck.com/markomilos/clean-architecture-on-android</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcfe32e983a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>