<?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 Vinay Avasthi on Medium]]></title>
        <description><![CDATA[Stories by Vinay Avasthi on Medium]]></description>
        <link>https://medium.com/@vavasthi?source=rss-10ababa9ca66------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nOa6R8J-9axij0yr2PIgjA.png</url>
            <title>Stories by Vinay Avasthi on Medium</title>
            <link>https://medium.com/@vavasthi?source=rss-10ababa9ca66------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:34:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vavasthi/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[Database Schema Version Control]]></title>
            <link>https://medium.com/@vavasthi/database-schema-version-control-5c6dcb2550e7?source=rss-10ababa9ca66------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c6dcb2550e7</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[scheme-versioning]]></category>
            <category><![CDATA[database-schema]]></category>
            <category><![CDATA[flyway]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Vinay Avasthi]]></dc:creator>
            <pubDate>Tue, 25 Aug 2020 06:44:45 GMT</pubDate>
            <atom:updated>2020-08-25T06:44:45.862Z</atom:updated>
            <content:encoded><![CDATA[<p>Most of the times when we have a service in production, we might make changes to the database schema. We want to make sure of two things here.</p><ol><li>Database changes are version controlled</li><li>Changes to actual database are done in a controlled fashion.</li></ol><p>I am not very comfortable with some CI/CD job going on its own and making changes to database schema. Deployments that need schema changes are done as part of planned maintenance cycles and need to be monitored by actual humans.</p><p>So, what do I expect from a solution that takes care of schema versioning.</p><ul><li>The service should not be allowed to start if the schema is not in sync with the in-memory entities and code that is designed to use them</li><li>An easy mechanism should be provided for migration of schema version. This is generally done through different phases of development like dev/stage/test and then to production., We want to automate it in the sense that there should be scripts that are tested and validated through previous phases of development lifecycle but still has an option of actual user triggering it in production.</li></ul><p>With above two goals, let’s try to define a database schema versioning system. I am going to use <a href="https://flywaydb.org/">flywaydb</a> as the primary tool that does it with configurations that make it useful for my usecase. First let’s define a configuration file that takes defines database connectivity option for my database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76d9d398ceb1858717976699953f5067/href">https://medium.com/media/76d9d398ceb1858717976699953f5067/href</a></iframe><p>You would remember since ours is a multi-tenant application, we have three databases and we have define configurations for all the three databases.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b0c85f3564871a7fc5ac83b47f2a905/href">https://medium.com/media/3b0c85f3564871a7fc5ac83b47f2a905/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/898c1827703e71801bf64499a698924c/href">https://medium.com/media/898c1827703e71801bf64499a698924c/href</a></iframe><p>Here we have all the three database configurations defined. Now let’s make changes to pom.xml for dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c053f068448cccc917d50d9ebb21d82/href">https://medium.com/media/8c053f068448cccc917d50d9ebb21d82/href</a></iframe><p>If you are just creating your application, then your life is easy, just create the initial <em>sql file</em> and add it to your <em>src/resources/db/migration</em> directory. Be sure to name it something like V1.0__Initial_Schema.sql. You need to make sure the first character is V, U, or R for version, undo, repeatable respectively. After that you have a version number, you can follow any version number strategy but it should be in the form of the dotted notation of <em>ver.major.minor</em>. For more details on this, please <a href="https://flywaydb.org/documentation/migrations#sql-based-migrations">read here</a> on how this can be effectively used. What we need to understand is that flyway will consider a version 1.1 to be a version later than version 1.0.</p><p>Now that we have the existing SQL stored in the file, we can baseline our current schema so that any future changes could be incorporated using this mechanism.</p><pre>$ mvn flyway:baseline -Dflyway.configFiles=./tutorials/config/default.config</pre><pre>[INFO] Scanning for projects...<br>[INFO] <br>[INFO] -----------------&lt; in.springframework.blog:tutorials &gt;------------------<br>[INFO] Building tutorials 0.0.1-SNAPSHOT<br>[INFO] --------------------------------[ jar ]---------------------------------<br>[INFO] <br>[INFO] --- flyway-maven-plugin:6.5.5:baseline (default-cli) @ tutorials ---<br>Loading class `com.mysql.jdbc.Driver&#39;. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver&#39;. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.<br>[INFO] Flyway Community Edition 6.5.5 by Redgate<br>[INFO] Database: jdbc:mysql://localhost:3306/tutorial (MySQL 8.0)<br>[INFO] Creating Schema History table `tutorial`.`flyway_schema_history` with baseline ...<br>[INFO] Successfully baselined schema with version: 1.0<br>[INFO] ------------------------------------------------------------------------<br>[INFO] BUILD SUCCESS<br>[INFO] ------------------------------------------------------------------------<br>[INFO] Total time:  1.285 s<br>[INFO] Finished at: 2020-08-25T10:14:53+05:30<br>[INFO] ------------------------------------------------------------------------</pre><p>Make sure the pathname of the configuration file is appropriate for your scenario. Also like in my case, since I have multiple databases due to multi-tenancy, I will need to do this for each of the databases. Once done, I can check the status of schema using the <em>info</em> command.</p><pre>$ mvn flyway:info -Dflyway.configFiles=./tutorials/config/default.config</pre><pre>[INFO] Scanning for projects...<br>[INFO] <br>[INFO] -----------------&lt; in.springframework.blog:tutorials &gt;------------------<br>[INFO] Building tutorials 0.0.1-SNAPSHOT<br>[INFO] --------------------------------[ jar ]---------------------------------<br>[INFO] <br>[INFO] --- flyway-maven-plugin:6.5.5:info (default-cli) @ tutorials ---<br>Loading class `com.mysql.jdbc.Driver&#39;. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver&#39;. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.<br>[INFO] Flyway Community Edition 6.5.5 by Redgate<br>[INFO] Database: jdbc:mysql://localhost:3306/tutorial (MySQL 8.0)<br>[INFO] Schema version: 1.0<br>[INFO] <br>[INFO] +----------+---------+----------------+----------+---------------------+----------+<br>| Category | Version | Description    | Type     | Installed On        | State    |<br>+----------+---------+----------------+----------+---------------------+----------+<br>|          | 1.0     | Base Migration | BASELINE | 2020-08-25 10:13:12 | Baseline |<br>+----------+---------+----------------+----------+---------------------+----------+</pre><pre>[INFO] ------------------------------------------------------------------------<br>[INFO] BUILD SUCCESS<br>[INFO] ------------------------------------------------------------------------<br>[INFO] Total time:  1.247 s<br>[INFO] Finished at: 2020-08-25T10:13:26+05:30<br>[INFO] ------------------------------------------------------------------------</pre><p>Now our existing database is baselined and we can start using the flyway versioning mechanism. We still have one issue to resolve, since we want to make sure our application doesn’t start till the time we have appropriate code backing appropriate schema. The first step is to disable any kind of migration being started by our application. So we define a null migration strategy that will not do anything.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af5e1b20c302651c6c1ae62f3d2d33c0/href">https://medium.com/media/af5e1b20c302651c6c1ae62f3d2d33c0/href</a></iframe><p>This will ensure that no automatic migration is executed. We still want to make sure that the application exits if the schema can’t be validated. For this we need to go to the method where we are creating the datasource. We add the validation of the datasource there.</p><p>In our example, since we are using Multi-tenant datasource, we add this validation there.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f85639fe8ff4a858e51e54fca1b78552/href">https://medium.com/media/f85639fe8ff4a858e51e54fca1b78552/href</a></iframe><p>Look at <em>validateDatasource</em> method, it takes a dataSource as input and raises a SpringApplication exit if the database can’t be validated. Now, let’s test it. We will take our entity <em>Profile</em> and add a new field in, let’s call it <em>maritalStatus</em>.</p><p>We now create a <em>sql</em> file that alters the table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b40ce21f2c1ee24aff4555fb7f4c27a5/href">https://medium.com/media/b40ce21f2c1ee24aff4555fb7f4c27a5/href</a></iframe><p>Now if we try to run this application, let’s see what happens.</p><pre>2020-08-25 11:53:54.652 ERROR 40041 --- [           main] o.s.boot.SpringApplication               : Application run failed</pre><pre>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name &#39;flywayInitializer&#39; defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Unsatisfied dependency expressed through method &#39;flywayInitializer&#39; parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name &#39;flyway&#39; defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.flywaydb.core.Flyway]: Factory method &#39;flyway&#39; threw exception; nested exception is org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name &#39;dataSource&#39;: Could not bind properties to &#39;DataSource&#39; : prefix=spring.datasource, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is java.lang.IllegalStateException: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@ba2f4ec has been closed already<br>	at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:797) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]</pre><p>Now let’s run the migration for this sql.</p><pre>$ mvn flyway:migrate -Dflyway.configFiles=./tutorials/config/default.config</pre><pre>[INFO] Scanning for projects...<br>[INFO] <br>[INFO] -----------------&lt; in.springframework.blog:tutorials &gt;------------------<br>[INFO] Building tutorials 0.0.1-SNAPSHOT<br>[INFO] --------------------------------[ jar ]---------------------------------<br>[INFO] <br>[INFO] --- flyway-maven-plugin:6.5.5:migrate (default-cli) @ tutorials ---<br>Loading class `com.mysql.jdbc.Driver&#39;. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver&#39;. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.<br>[INFO] Flyway Community Edition 6.5.5 by Redgate<br>[INFO] Database: jdbc:mysql://localhost:3306/tutorial (MySQL 8.0)<br>[INFO] Successfully validated 3 migrations (execution time 00:00.017s)<br>[INFO] Current version of schema `tutorial`: 1.1<br>[INFO] Migrating schema `tutorial` to version 1.2 - Add Marital Status<br>[INFO] Successfully applied 1 migration to schema `tutorial` (execution time 00:00.075s)<br>[INFO] ------------------------------------------------------------------------<br>[INFO] BUILD SUCCESS<br>[INFO] ------------------------------------------------------------------------<br>[INFO] Total time:  1.323 s<br>[INFO] Finished at: 2020-08-25T11:56:25+05:30<br>[INFO] ------------------------------------------------------------------------</pre><pre>$ mvn flyway:info -Dflyway.configFiles=./tutorials/config/default.config</pre><pre>[INFO] Scanning for projects...<br>[INFO] <br>[INFO] -----------------&lt; in.springframework.blog:tutorials &gt;------------------<br>[INFO] Building tutorials 0.0.1-SNAPSHOT<br>[INFO] --------------------------------[ jar ]---------------------------------<br>[INFO] <br>[INFO] --- flyway-maven-plugin:6.5.5:info (default-cli) @ tutorials ---<br>Loading class `com.mysql.jdbc.Driver&#39;. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver&#39;. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.<br>[INFO] Flyway Community Edition 6.5.5 by Redgate<br>[INFO] Database: jdbc:mysql://localhost:3306/tutorial (MySQL 8.0)<br>[INFO] Schema version: 1.2<br>[INFO] <br>[INFO] +-----------+---------+---------------------------+----------+---------------------+----------+<br>| Category  | Version | Description               | Type     | Installed On        | State    |<br>+-----------+---------+---------------------------+----------+---------------------+----------+<br>|           | 1.0     | Base Migration            | BASELINE | 2020-08-25 10:15:00 | Baseline |<br>| Versioned | 1.1     | Remove AuthToken FromUser | SQL      | 2020-08-25 10:49:27 | Success  |<br>| Versioned | 1.2     | Add Marital Status        | SQL      | 2020-08-25 11:56:25 | Success  |<br>+-----------+---------+---------------------------+----------+---------------------+----------+</pre><pre>[INFO] ------------------------------------------------------------------------<br>[INFO] BUILD SUCCESS<br>[INFO] ------------------------------------------------------------------------<br>[INFO] Total time:  1.226 s<br>[INFO] Finished at: 2020-08-25T11:56:30+05:30<br>[INFO] ------------------------------------------------------------------------</pre><p>As we can see now, the database schema is migrated. So, if we make sure all the database migration SQL files are properly made part of the project, we can eliminate schema mismatch issues to a large extent. We also have an option to make it fully automated or a single command migration with manual verification.</p><p>The hibernate ORMs are just in-memory representations of actual database schema and the schema is owned by the database, ORM changes have to be done by the programmers.</p><p>The complete code supporting this tutorial is available at my <a href="https://github.com/vavasthi/springblog/tree/v1.8">spring blog</a> tagged as v1.8</p><p>This post first appeared on my blog <a href="https://www.springframework.in/2020/08/database-schema-version-control.html">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c6dcb2550e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Microservices with Kubernetes on Google, Ribbon, Feign and Spring Cloud Gateway]]></title>
            <link>https://medium.com/@vavasthi/spring-microservices-with-kubernetes-on-google-ribbon-feign-and-spring-cloud-gateway-67c2c8700d94?source=rss-10ababa9ca66------2</link>
            <guid isPermaLink="false">https://medium.com/p/67c2c8700d94</guid>
            <category><![CDATA[feign]]></category>
            <category><![CDATA[ribbon]]></category>
            <category><![CDATA[gke]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[spring-cloud-gateway]]></category>
            <dc:creator><![CDATA[Vinay Avasthi]]></dc:creator>
            <pubDate>Sun, 05 Jul 2020 16:58:22 GMT</pubDate>
            <atom:updated>2020-07-05T16:58:22.064Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://www.varahamihir.com/2020/07/building-jwt-authorization-server.html">previous post</a>, we built a JWT authentication server. Now we will build on that server and create an initial instance of the application that I am working on. I have been working on a education engine called <em>Varahamihir</em>. We will talk about this engine at a later date, but for the scope of this post, we will define this engine as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*bLYiKeotyuaBYLJ4jnHDrg.png" /><figcaption>Three micro-services with single external load balancer</figcaption></figure><p>The engine consists of an authorization and routing service. We have taken our <a href="https://www.varahamihir.com/2020/07/building-jwt-authorization-server.html">authorization server from the last post</a> and added the spring cloud gateway routing functionality to that. This will be the only micro-service in our architecture that will be exposed to internet while all other micro-services will be strictly internal services.</p><p>The authorization services maintains all the users that exist in the system but these users are provided access to different resources based on their role. When designing micro-services based solutions, people have following two options.</p><ol><li>Authorization server performs necessary authentication and authorization and then for communication between micro-services specific client tokens are used.</li><li>The authorization token received from the user is passed to each of the micro-services. This requires us to make sure the token is passed around for completing the life-cycle of the request.</li></ol><p>I always prefer option 2 for better audit and tracing capabilities. Let’s look all the things that we need to make this solution work.</p><h3>Gateway Changes</h3><p>As we have already mentioned, we are re-purposing our authorization server to also double up as routing gateway.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/671ef6d75be3c321cdab7c9c679b099c/href">https://medium.com/media/671ef6d75be3c321cdab7c9c679b099c/href</a></iframe><p>As we can see in the <em>yaml</em> file, we define two routes, one for our <em>student-service</em>, and another for our <em>guardian-service</em>. Since we are going to use <em>Kubernetes Service Discovery, </em>these names have to match the service names declared in our pod configuration. Please be careful to only used exposed service names.</p><p>In the <em>yaml</em> file above, we see two filters defined. These are the hooks to add/remove something to all the requests that are being handled by <em>Spring Cloud Gateway.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcd82abeaa3ab60794e2d7a38bd3e648/href">https://medium.com/media/dcd82abeaa3ab60794e2d7a38bd3e648/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b83e58acafdb67013e227a4ca3458020/href">https://medium.com/media/b83e58acafdb67013e227a4ca3458020/href</a></iframe><p>For now these filters are just printing the request headers and are not performing anything useful. We also need to make changes to our <em>SpringApplication</em> to enable discovery for the services.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1a9b0daac3006a8ae3c988c590e0add/href">https://medium.com/media/e1a9b0daac3006a8ae3c988c590e0add/href</a></iframe><p>Look at the annotations on the class. The most important annotation is <em>@EnableDiscoveryClient.</em> Since we have to build a number of micro-services and many of the functions are common, we have created couple of modules which we will include in all micro services. The authentication path for <em>identity-server</em> is different than other micro-services because other micro-services will just validate the <em>JWT </em>token received from the gateway.</p><p>Spring does not recursively import all the <em>application.properties </em>files from child modules, we have to collect really required properties from any child module and manually import them to the application. That is the reason, we have <em>@PropertySource(“classpath:jwt.properties”)</em>, in the application because this is the properties file where some required properties are stored in one of the child modules. I would have liked if there was some way to instruct Spring to import all the child module’s <em>application.properties</em> files recursively.</p><p>Apart from these changes, the gateway application is very similar to what we saw in previous post, we have to just pay attention to list of whitelisted URLs in VarahamihirWebServerSecurityConfig. We have basically whitelisted actuator and user registration URLs.</p><h3>Micro-services</h3><p>The gateway service (identity-server) is sitting on the edge and is the only entity exposed to internet. It performs complete authentication and authorization cycle. Once the request is accepted by the gateway and is being passed on the other micro-services, they only verify the token and install a security context so that appropriate role based access control can be applied on the endpoints.</p><p>We have following roles defined in our system.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dae43de255710d287af05d7957c0469f/href">https://medium.com/media/dae43de255710d287af05d7957c0469f/href</a></iframe><p>Most of the roles defined in the system are self-explanatory. Some of the roles of interest are as below.</p><ul><li><strong>ADMIN</strong> — This is like the super-user of the system, will have complete access to all the functions of the system</li><li><strong>TENANT_ADMIN</strong> — This is like the above role but will only have access to resources of a tenant. This is the admin of a particular tenant</li><li><strong>REFRESH</strong> — This is an internal role that is assigned to the refresh token issued by the Authorization Server. This role is only allowed to call the refresh endpoint.</li><li><strong>AUTHENTICATE</strong> — This is the role that is assigned when the user requests a new token using the username and password.</li></ul><p>There are other specific roles for specific types of users and provide them access to their resources.</p><h3>Authentication</h3><p>The authentication flow of the microservice starts with few initial filters. Let’s look at the order in the security config code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed1433dbbf3497dd7676515522492476/href">https://medium.com/media/ed1433dbbf3497dd7676515522492476/href</a></iframe><p>The code is self-explanatory, we first whitelist a bunch of URLs and options and then we add three filters. The first is our good old <em>TenantHeaderFilter</em> that extracts and installs tenant into the <em>SecurityContext</em>. This is very similar to what we saw in previous post as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91a42db2a85a207ccdbbc860b4740eb4/href">https://medium.com/media/91a42db2a85a207ccdbbc860b4740eb4/href</a></iframe><p>The next filter is the <em>AuthorizationHeaderFilter, </em>which extracts the <em>Authorization</em> header from the request and installs it into the <em>SecurityContext.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80566db8b37f6af805352449bb5190b4/href">https://medium.com/media/80566db8b37f6af805352449bb5190b4/href</a></iframe><p>Now the <em>AuthenticationWebFilter</em> provided by <em>Spring</em> is called which triggers the authentication. This filters requires a authentication manager, for which we use a standard <em>UserDetailsRepositoryReactiveAuthenticationManager</em>. We need to provide a <em>UserDetailService</em> to instantiate the authentication manager.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a7f035d8dbea960f6ecc8bbde603160/href">https://medium.com/media/9a7f035d8dbea960f6ecc8bbde603160/href</a></iframe><p>A standard implementation of <em>UserDetailService</em> requires one to fetch <em>username</em> and <em>password</em> from some persistent store. In our scenario, we already have an authenticated token, so we just provide a dummyPassword that is defined in the above class. All the other parameters to construct a proper <em>UseDetails</em> object can be extracted from the existing token and authentication can proceed.</p><p>In this flow, we are only worried about decoding and verifying the JWT token.</p><p>The main authentication function is handled by <em>VarahamihirJWTClientAuthWebFilter</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4010a3d3aba1ab9f4b030f7b447e8ebf/href">https://medium.com/media/4010a3d3aba1ab9f4b030f7b447e8ebf/href</a></iframe><p>This class uses a class <em>VarahamihirJWTClientAuthConverters</em> to perform the actual authentication. Both these classes are below. The filter function in <em>VarahamihirJWTClientAuthWebFilter</em> decided if the authentication needs to be done and then <em>authenticate</em> function performs actual authentication.</p><p>We use a utility class <em>VarahamihirJWTBaseUtil</em>. In the previous post, we had talked about <em>VarahamihirJWTUtil.</em> Since then, the class is refactored into two classes where the base class has all the decoding related functions and the child class has additional functionality. Many of the beans that we need to create a token are not needed when we want to validate and decode it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b1886dd785b7b4b09445978d293c434/href">https://medium.com/media/8b1886dd785b7b4b09445978d293c434/href</a></iframe><p>We use a utility class <em>VarahamihirJWTBaseUtil</em>. In the previous post, we had talked about <em>VarahamihirJWTUtil.</em> Since then, the class is refactored into two classes where the base class has all the decoding related functions and the child class has additional functionality. Many of the beans that we need to create a token are not needed when we want to validate and decode it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5dd17364ddb29b676f9073b97a1f864/href">https://medium.com/media/f5dd17364ddb29b676f9073b97a1f864/href</a></iframe><h3>Communication</h3><p>Since we will be using <em>OpenFeign</em> for communication across micro-services, we define this in this common module as well.</p><p>We have three micro-services and we expose the interfaces related to each of them that are required for communication.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18c4e1134d4868f06b75125de20c3968/href">https://medium.com/media/18c4e1134d4868f06b75125de20c3968/href</a></iframe><p>This the interface to identity server and provides two services, given a username, it can get you the details of that user and it can create a user. The second is required because when the other micro-services need to create a student or a guardian, they first need to create a user and then create student or guardian. The other micro-services also make sure appropriate roles are applied to users based on their function. The external endpoint doesn’t allow one to provide roles.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a462bd18fa0d343d75ef78a56c3b8cd/href">https://medium.com/media/5a462bd18fa0d343d75ef78a56c3b8cd/href</a></iframe><p>The <em>student service</em> interface provides two interfaces, one to get the details of a student and another to create a student. This will be called from the guardian endpoint since we envisage that a guardian will create students.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcd8f004dc4173639f3d77d10e143392/href">https://medium.com/media/fcd8f004dc4173639f3d77d10e143392/href</a></iframe><p>The <em>guardian service</em> just provides a single interface and that allows one to query details of a guardian.</p><p>We also need to provide a config for all the <em>Feign</em> clients.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0048fbccb3e4a4e958dab1620653789/href">https://medium.com/media/f0048fbccb3e4a4e958dab1620653789/href</a></iframe><h3>Implementing micro-service</h3><p>Now that we have the common module completed, we can create our micro-services modules and implement the actual business logic. Here I present one sample of how the micro-service looks like. We take the example of <em>Student</em> micro-service.</p><p>We first define an endpoint class, in this class our endpoint has two interfaces, a GET and a POST.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b9f55ecac203e1a4d6dadb20a8d3145/href">https://medium.com/media/7b9f55ecac203e1a4d6dadb20a8d3145/href</a></iframe><p>Now we define a service layer that will implement the functionality required by the endpoint.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/425a9cba78c6b5b0a91c474bc7ecca49/href">https://medium.com/media/425a9cba78c6b5b0a91c474bc7ecca49/href</a></iframe><p>Next, we define a repository.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab8fa7776ad10e1afd9aad74078f76e8/href">https://medium.com/media/ab8fa7776ad10e1afd9aad74078f76e8/href</a></iframe><p>Next we define a mapper class that can convert entities to Pojo. This is not really required but is useful if what is exposed over JSON is remarkably different than what is stored in database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/347468c10276d4e66d13bfccc5f60768/href">https://medium.com/media/347468c10276d4e66d13bfccc5f60768/href</a></iframe><p>Finally, our application. Make sure all the annotations are in place.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bc55b8bd23fdf427fb567ea965f2e82/href">https://medium.com/media/8bc55b8bd23fdf427fb567ea965f2e82/href</a></iframe><h3>Deployment</h3><p>First thing we need to do is the bundle the application in docker images. We need to make sure our <em>pom.xml</em> has following directive.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/604b25cc1e0a58105fe23c389738a552/href">https://medium.com/media/604b25cc1e0a58105fe23c389738a552/href</a></iframe><p>The <em>build-image</em> goal in <em>spring-boot-maven-plugin</em> makes sure that on <em>mvn clean package -DskipTests</em> command creates a docker image. We have prefixed the image with <em>gcr.io</em> because we want to use google cloud and if we push that image, it will be available in google container registery.</p><p>Now we need to generate <em>yaml</em> files for each of our applications. Even though I used <em>dekorate</em> to automatically generate <em>yaml</em> files, I always had to manually modify them. So I finally decided to create my own <em>yaml</em> files.</p><p>Since I am using <em>Google Cloud SQL</em>, I am using the sidecar approach to deploy the cloud sql proxy. Since the database requires authentication, I am using the <em>kubernetes secret</em> to define that.</p><p>We use <em>Workload Identity</em> method for the application to work in google cloud. Here are the steps that need to be followed for that.</p><p>Go to <a href="https://console.cloud.google.com/kubernetes">google cloud container page</a> and create a cluster for yourself. You will also need to create a google project before that. Make a note of the cluster name.</p><p>Set your google cloud project in your shell and create a service account.</p><pre>$ gcloud iam service-accounts create my_gsa_name<br>$ kubectl create namespace my_namespace<br>$ kubectl create serviceaccount --namespace my_namespace my_ksa</pre><p>Now associate policy bindings and annotate the account</p><pre>$ gcloud config set project my_project<br>$ gcloud iam service-accounts add-iam-policy-binding \<br>  --role roles/iam.workloadIdentityUser \<br>  --member &quot;serviceAccount:cluster_project.svc.id.goog[my_namespace/my_ksa]&quot; \<br>  my_gsa_name@gsa_project.iam.gserviceaccount.com</pre><p>You can leave my_namespace to <em>default</em> if you wish. <em>my_ksa</em> is your kubernetes service account which is tied to your <em>my_gsa_name</em> google account. Since we are going to use <em>Cloud SQL</em>, you need to make sure the <em>my_gsa_name</em> has one of the Cloud roles into it. Otherwise you will get errors related to permissions for using <em>Cloud SQL</em>.</p><p>Now we need to complete the binding between KSA and GSA.</p><pre>$ kubectl annotate serviceaccount \<br>  --namespace my_namespace \<br>   my_ksa \<br>   iam.gke.io/gcp-service-account=my_gsa_name@gsa_project.iam.gserviceaccount.com</pre><p>You also need to create a secret for database that the <em>yaml</em> file will use to authenticate with cloud sql. This secret is used within the <em>yaml</em> file for service deployment.</p><pre>$ kubectl create secret generic my-secret \<br>  --from-literal=username=my-db-user \<br>  --from-literal=password=MyDbPassword \<br>  --from-literal=database=my-db-name</pre><p>Here is the <em>yaml</em> file for one of the micro-services. Similarly, one can write for other micro-services as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0715e4d429d6391a63f2a389edaa8ca0/href">https://medium.com/media/0715e4d429d6391a63f2a389edaa8ca0/href</a></iframe><p>Now that we are ready with all the stuff, we just need to call <em>mvn clean package -DskipTests</em>. This will create all the docker images. Now we need to push these docker images to <em>Google Container Registry</em>. For this, we need to call <em>docker push</em> on each of the images. I use following script to automate the complete deployment operation.</p><pre>#!/bin/bash<br>IMAGES=`docker images --format &quot;table {{.Repository}},{{.ID}},{{.Repository}},{{.Tag}},{{.Size}}&quot; | grep &#39;identity-server\|student\|guardian&#39; |cut -d &#39;,&#39; -f 2`<br>[ $? -eq 0 ]  || exit 1<br>docker image rm -f $IMAGES<br>mvn clean package -DskipTests<br>[ $? -eq 0 ]  || exit 1<br>docker push gcr.io/varahamihir-cloud/student<br>[ $? -eq 0 ]  || exit 1<br>docker push gcr.io/varahamihir-cloud/guardian<br>[ $? -eq 0 ]  || exit 1<br>docker push gcr.io/varahamihir-cloud/identity-server<br>[ $? -eq 0 ]  || exit 1<br>kubectl -n service rollout restart --namespace=varahamihir-k8s-ns deployment student<br>[ $? -eq 0 ]  || exit 1<br>kubectl -n service rollout restart --namespace=varahamihir-k8s-ns deployment guardian<br>[ $? -eq 0 ]  || exit 1<br>kubectl -n service rollout restart --namespace=varahamihir-k8s-ns deployment identity-server<br>[ $? -eq 0 ]  || exit 1</pre><p>Now that the servers are deployed, we can check the condition of all the pods.</p><pre>$ kubectl get pods --namespace=my-namespace<br>NAME                               READY   STATUS    RESTARTS   AGE<br>guardian-7c75fcb9c8-txg4q          2/2     Running   0          3h6m<br>identity-server-67d7878db8-47lqq   2/2     Running   0          3h6m<br>student-68485fb749-l65gc           2/2     Running   1          3h6m</pre><p>As we can see, each of the pods are running two workloads because the <em>cloud_sql_proxy</em> is running as a sidecar for each of the pods. The benefit of this is that we can use the <em>cloud sql</em> database as localhost. We can see the logs of any of the processes by following command.</p><pre>$ kubectl logs --namespace=varahamihir-k8s-ns pods/student-5bf4ccd6cc-5g29q --container student <br>Error from server (NotFound): pods &quot;student-5bf4ccd6cc-5g29q&quot; not found<br>vavasthi@VinayLinux-Desktop:~/work/varahamihir$ kubectl logs --namespace=varahamihir-k8s-ns pods/student-68485fb749-l65gc --container student                         <br>Container memory limit unset. Configuring JVM for 1G container.<br>Calculated JVM Memory Configuration: -XX:MaxDirectMemorySize=10M -XX:MaxMetaspaceSize=216643K -XX:ReservedCodeCacheSize=240M -Xss1M -Xmx524732K (Head Room: 0%, Loaded Class Count: 35835, Thread Count: 50, Total Memory: 1073741824)<br>Adding 127 container CA certificates to JVM truststore</pre><pre>  .   ____          _            __ _ _<br> /\\ / ___&#39;_ __ _ _(_)_ __  __ _ \ \ \ \<br>( ( )\___ | &#39;_ | &#39;_| | &#39;_ \/ _` | \ \ \ \<br> \\/  ___)| |_)| | | | | || (_| |  ) ) ) )<br>  &#39;  |____| .__|_| |_|_| |_\__, | / / / /<br> =========|_|==============|___/=/_/_/_/<br> :: Spring Boot ::        (v2.3.1.RELEASE)</pre><p>Now that we are ready, we can see our micro-services in action. First let’s create a guardian in the system.</p><pre>$ curl --request POST --url <a href="http://35.225.145.174/default/registration/guardian">http://35.225.145.174/default/registration/guardian</a> --header cache-control: no-cache --header content-type: application/json --header x-tenant: default --data {&quot;username&quot; : &quot;testguardian&quot;,&quot;password&quot; : &quot;testguardian1123&quot;,&quot;fullname&quot; : &quot;My Guardian&quot;,&quot;email&quot;:&quot;testguardian1@varahamihir.com&quot;}<br>{<br>    &quot;tenantId&quot;: &quot;738f6863-32dc-4a92-9f3a-cad3ef38fe6f&quot;,<br>    &quot;user&quot;: {<br>        &quot;email&quot;: &quot;testguardian1123&quot;,<br>        &quot;grantedAuthorities&quot;: [<br>            &quot;GUARDIAN&quot;,<br>            &quot;USER&quot;<br>        ],<br>        &quot;id&quot;: &quot;5d6a6e08-0a88-4c5f-9bc1-b220ece79397&quot;,<br>        &quot;mask&quot;: 0,<br>        &quot;tenantId&quot;: &quot;738f6863-32dc-4a92-9f3a-cad3ef38fe6f&quot;,<br>        &quot;username&quot;: &quot;testguardian&quot;<br>    },<br>    &quot;userId&quot;: &quot;5d6a6e08-0a88-4c5f-9bc1-b220ece79397&quot;<br>}</pre><p>Now we can authenticate using this guardian.</p><pre>$ curl --request POST \<br>  --url <a href="http://35.225.145.174/default/oauth/token">http://35.225.145.174/default/oauth/token</a> \<br>  --header &#39;authorization: Basic c3VwZXJzZWNyZXRjbGllbnQ6c3VwZXJzZWNyZXRjbGllbnQxMjM=&#39; \<br>  --header &#39;cache-control: no-cache&#39; \<br>  --header &#39;content-type: application/x-www-form-urlencoded&#39; \<br>  --header &#39;postman-token: 26951e8d-bbe2-f617-896d-9a31658fe142&#39; \<br>  --header &#39;x-tenant: default&#39; \<br>  --data &#39;username=testguardian&amp;password=testguardian1123&amp;audience=self&amp;grant_type=password&#39;<br>  {<br>    &quot;auth_token&quot;: &quot;eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiZGlyIn0..6p7meCoT0JyW9dKjeM_h3w.1bjKuj_5nVS_a7tC8zX6euEXyarrrQNCm62ImgrTxCw68oc7leQsAPh5TYyNpyGSE3pdsKCAie67c8WW13dBpRcw22BbitGTKdabpo8L3z5Y51YB7wWx_lQuSfXkTfd9haa2OmnpUjYyNMdHlu6QqGx4fI7iIOC0a4Ir4SkeF6jLMlpxyqpMkPyeZuQZHZDyjT9Cyo8bTFkaNZ8wPy_PX-nCWZROjQiXUQ33ChQ5Uy3QkBz0CCvAOMUjDyIuIA-yH2O35HkCsX44yZ2w-DDjzNyYe5WJIF1iuTpSQfLtkG0jvqkZUp5HyD6wwB5WcvbDzj-wOV7cuVEvY1BoFfUXEjfeZ-pH45_WWV05PeKyiCA.2xBZDLa9VQqiOUGK_pESuA&quot;,<br>    &quot;expiry&quot;: 500,<br>    &quot;refreshToken&quot;: &quot;eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiZGlyIn0..FttlYRPM4nwViMyZELXnsQ.ZRklt6EClyJCI3lxaIr_W84mtMfdoZUlzWVkM-85tDz8-IwhRjtzieRfErzcuWJB1MB2Y2m4QtVRuLMagilWqc_CbLYb31SOLlMDfHN6TOJck-qpFg_qziaofFOFVY6idlUP9GO2-nuDjROXJLhjFC47mbwOrfqdGoWXAqoaBJzhgKRnKcWJKG_COjN5uXhnirCYM_bc3bI8HJG_1i_Ca_7wgDadSOIyXwS9-DqpqMjMBLZUyIe9S_jqwG7RZox1Ll_MWv7DZvYvhk8ouFZSkB5tL7qI2tNoEPNre_rICfSxNIgJmx_YeI-4IgvQyAbG6SanEDqEfEmRowjbQJ9GCw.-QPY9_YOFllm9yqb-B1WuQ&quot;,<br>    &quot;refreshTokenExpiry&quot;: 1000,<br>    &quot;scope&quot;: &quot;,&quot;,<br>    &quot;tokenType&quot;: &quot;Bearer&quot;<br>}</pre><p>Now using the auth_token, the guardian can add one student to himself.</p><pre>$ curl --request POST \<br>  --url <a href="http://35.225.145.174/default/guardian/testguardian/student">http://35.225.145.174/default/guardian/testguardian/student</a> \<br>  --header &#39;authorization: Bearer eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiZGlyIn0..6p7meCoT0JyW9dKjeM_h3w.1bjKuj_5nVS_a7tC8zX6euEXyarrrQNCm62ImgrTxCw68oc7leQsAPh5TYyNpyGSE3pdsKCAie67c8WW13dBpRcw22BbitGTKdabpo8L3z5Y51YB7wWx_lQuSfXkTfd9haa2OmnpUjYyNMdHlu6QqGx4fI7iIOC0a4Ir4SkeF6jLMlpxyqpMkPyeZuQZHZDyjT9Cyo8bTFkaNZ8wPy_PX-nCWZROjQiXUQ33ChQ5Uy3QkBz0CCvAOMUjDyIuIA-yH2O35HkCsX44yZ2w-DDjzNyYe5WJIF1iuTpSQfLtkG0jvqkZUp5HyD6wwB5WcvbDzj-wOV7cuVEvY1BoFfUXEjfeZ-pH45_WWV05PeKyiCA.2xBZDLa9VQqiOUGK_pESuA&#39; \<br>  --header &#39;cache-control: no-cache&#39; \<br>  --header &#39;content-type: application/json&#39; \<br>  --header &#39;postman-token: 2e9901da-ef01-a3bb-ba28-1f0dff5f7381&#39; \<br>  --header &#39;x-tenant: default&#39; \<br>  --data &#39;{\n	&quot;username&quot; : &quot;teststudent1&quot;,\n	&quot;password&quot; : &quot;teststudent123&quot;,\n	&quot;fullname&quot; : &quot;Test Student&quot;,\n	&quot;email&quot;:&quot;teststudent@varahamihir.com&quot;,\n	&quot;guardianName&quot;:&quot;testguardian&quot;\n}&#39;<br>      &quot;userId&quot;: &quot;45fe4888-2a64-48bd-bea7-ad512f0ef724&quot;,<br>    &quot;tenantId&quot;: &quot;738f6863-32dc-4a92-9f3a-cad3ef38fe6f&quot;,<br>    &quot;guardianId&quot;: &quot;5d6a6e08-0a88-4c5f-9bc1-b220ece79397&quot;,<br>    &quot;user&quot;: {<br>        &quot;id&quot;: &quot;45fe4888-2a64-48bd-bea7-ad512f0ef724&quot;,<br>        &quot;tenantId&quot;: &quot;738f6863-32dc-4a92-9f3a-cad3ef38fe6f&quot;,<br>        &quot;fullname&quot;: &quot;Test Student&quot;,<br>        &quot;username&quot;: &quot;teststudent1&quot;,<br>        &quot;email&quot;: &quot;teststudent@varahamihir.com&quot;,<br>        &quot;mask&quot;: 0,<br>        &quot;grantedAuthorities&quot;: [<br>            &quot;STUDENT&quot;,<br>            &quot;USER&quot;<br>        ]<br>    }<br>}</pre><p>So we can see the system coordinating across three micro-services. The communication can also be effective since the communication is happening across local ip addresses and doesn’t have to go across the external load balancer. Each of the micro-services are also not aware of the ip addresses of each of the pieces and <em>Kubernetes Discovery Service</em> takes care of it.</p><p>Complete code synchronized with this blog post is available in <a href="https://www.blogger.com/u/1/blog/post/edit/317807127276403222/5282696699307214813#">my repository tagged as v1.1</a>.</p><p>This post first appeared on my blog <a href="https://www.varahamihir.com/2020/07/spring-microservices-with-kubernetes-on.html">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67c2c8700d94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a JWT Authorization Server]]></title>
            <link>https://medium.com/@vavasthi/building-a-jwt-authorization-server-db571254c5c4?source=rss-10ababa9ca66------2</link>
            <guid isPermaLink="false">https://medium.com/p/db571254c5c4</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[authorization-server]]></category>
            <category><![CDATA[webflux]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Vinay Avasthi]]></dc:creator>
            <pubDate>Wed, 01 Jul 2020 09:28:20 GMT</pubDate>
            <atom:updated>2020-07-01T09:29:47.191Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2jIR3MNk_CXHdqrkVsPFrg.png" /><figcaption>An artist’s impression of Varahamihir</figcaption></figure><p>I have playing with the idea of Spring Cloud Gateway, micro-services and deploying the service on Google Cloud. As I was ready to deploy the initial version on google cloud server. I saw following error on the logs of the server that I had built.</p><pre>Spring MVC found on classpath, which is incompatible with Spring Cloud Gateway at this time. Please remove spring-boot-starter-web dependency.</pre><p>Then I started on a path of discovery and following message in a <a href="https://spring.io/blog/2019/11/14/spring-security-oauth-2-0-roadmap-update">spring security documentation</a> kind of crushed my hopes.</p><pre>Spring Security’s Authorization Server support was never a good fit. An Authorization Server requires a library to build a product. Spring Security, being a framework, is not in the business of building libraries or products. For example, we don’t have a JWT library, but instead we make Nimbus easy to use. And we don’t maintain our own SAML IdP, CAS or LDAP products.</pre><p>So, as they say, the writing was on the wall. I was using Authorization Server provided by Spring and they have stopped supporting that in spring security 5, the spring cloud needed dependency on WebFlux which was supported with spring security 5. All in all I got totally confused with the dependencies and concluded that I will have to build a Authorization Server from scratch. This post is about my effort towards that and some learnings on the way.</p><p>First step, I cleaned up all the code that had anything to do with Filters, Authentication, Converters in the old server. WebFlux just doesn’t play nicely with any of that. Then I read a primer on reactive programming, I think if you read this blog and look at my code, you will realize that from reactive programming point of view, I am still not very fluent. In any case, I learnt enough to make this work.</p><p>The next challenge was database. Any of the relational databases are not reactive and I was stuck with MySQL. For the time being I have left it at that. In future, I will replace it with a backend that is reactive. For now, the interface to persistence layer, the repositories etc are all old style <em>JpaRepository.</em></p><p>Let’s get started now. The first step is to look at the primary filter chain. This is equivalent to the <em>WebSecurityConfigurerAdapter</em> in any old style <em>non-WebFlux</em> system.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7b203373ffd65dab8e24856536b2a90/href">https://medium.com/media/f7b203373ffd65dab8e24856536b2a90/href</a></iframe><p>Let’s look at all important method <em>securityWebFilterChain</em>, We first define a <em>AuthenticationWebFilter</em>. This class is provided by Spring and we just use it. But this class requires either an implementation of <em>ReactiveAuthenticationManager</em> or an implementation of <em>ReactiveAuthenticationManagerResolver. </em>Since we might need more than authentication server because we are building a authorization server that can handle <em>JWT</em> tokens, we decided to implement a <em>ReactiveAuthenticationManagerResolver that can handle two AuthenticationManager </em>based on specified criteria.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f9a941a9b2f6d95fcf7852c58a0b3dc/href">https://medium.com/media/7f9a941a9b2f6d95fcf7852c58a0b3dc/href</a></iframe><p>As is clear from the <em>resolve </em>method of the class <em>VarahamihirAuthenticationManagerResolver</em>, we have two different <em>ReactiveAuthenticationManager</em> instances, one that will handle <em>Client</em> tokens and the other one that will handle<em> User </em>tokens. To differentiate between the types of tokens, the class <em>UserDetailsRepositoryReactiveAuthenticationManager</em> that is provided by Spring is instantiated with either a <em>VarahamihirReactiveClientUserDetailService</em> which implements <em>ReactiveUserDetailsService</em> for clients or <em>VarahamihirReactiveUserDetailService</em> which implements the same service for normal users. This point, line 58 in <em>VarahamihirWebServerSecurityConfig</em> will make sure that right table from the database is looked up for the identification of client or user. Let’s take a look at two <em>ReactiveUserDetailsService</em> classes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef9e2234541f6e40533b5ec116274874/href">https://medium.com/media/ef9e2234541f6e40533b5ec116274874/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be63ab9d82df4378d4e08c06cc167895/href">https://medium.com/media/be63ab9d82df4378d4e08c06cc167895/href</a></iframe><p>Now we can carefully examine VarahamihirWebServerSecurityConfig which defines the Filter chain for authentication purposes.</p><ul><li>Lines 56 to 59 define the <em>AuthenticationWebFilter</em> which is added in the chain at line line 68.</li><li>Lines 61 to 63 added some filters that I used to extract HTTP parameters into RequestContext so that other methods can have access to them if required. Lots of multi-tenancy code is built around using these variables. For example a path of the URL contains tenant discriminator and it used to identify the tenant. If you want to know the details of it, it is described in detail in my other <a href="https://www.springframework.in/2020/06/building-multitenant-service.html">blog at this location</a>.</li><li>Lines 65 and 66 define the URLs that need to be exempted from authentication mechanism. For example we want new user registration to be outside the authentication flow.</li><li>Lines 67 to 71 define actual authenticated endpoint handling.</li><li>Line 72 adds a filter that will do processing related to JWT tokens.</li></ul><p>We also define another <em>AuthenticationManager</em> to take care authentication using JWT tokens. Here is the class. <strong>Here is a very critical things to note. Once you are confirming authentication success, you should only use one constructor in <em>UsernamePasswordAuthenticationToken</em> class that takes a set of GrantedAuthority as an argument. Otherwise the authentication will always fail. You can not use setAuthentication(true) as an option.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a375c7c559dbf803dc3d616d5e9da0b9/href">https://medium.com/media/a375c7c559dbf803dc3d616d5e9da0b9/href</a></iframe><p>This <em>AuthenticationManager</em> is used from the WebFilter that processing all JWT tokens. Here is the filter code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df90f5d042f1a900d845288b75cf504c/href">https://medium.com/media/df90f5d042f1a900d845288b75cf504c/href</a></iframe><p>The filter is making sure authentication is handled and security context is setup properly. There is a hook provided for any processing that one might want to do on authentication success. We have set it to the method <em>onAuthSuccess</em>. We use <em>VarahamihirJWTAuthConverters</em> to convert HTTP headers into a valid authentication object. Look at <em>apply </em>method below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71562af39470327f57b34472e1bfde9f/href">https://medium.com/media/71562af39470327f57b34472e1bfde9f/href</a></iframe><p>We use <a href="https://connect2id.com/products/nimbus-jose-jwt">Nimbus JOSE+JWT</a> for handling of JWT token itself. The functionality of this library is wrapped around our utility class <em>VarahamihirJWTUtil.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/164f23c032e0fab6b38addc9bd35a00b/href">https://medium.com/media/164f23c032e0fab6b38addc9bd35a00b/href</a></iframe><p>These are the most important bits and your authorization server is ready. The complete code is available on my repository <a href="https://github.com/vavasthi/varahamihir/tree/v1.0">here</a>. The key modules to look for are <em>identity-server</em> and <em>varahamihir-common</em>. This has a working authorization server tagged as <a href="https://github.com/vavasthi/varahamihir/tree/v1.0">v1.0</a>. This post first appeared on my blog <a href="https://www.varahamihir.com/2020/07/building-jwt-authorization-server.html">here</a>.</p><pre>$ curl --request POST \<br>  --url <a href="http://localhost:8081/default/registration/user">http://localhost:8081/default/registration/user</a> \<br>  --header &#39;authorization: Basic c3VwZXJzZWNyZXRjbGllbnQ6c3VwZXJzZWNyZXRjbGllbnQxMjM=&#39; \<br>  --header &#39;cache-control: no-cache&#39; \<br>  --header &#39;content-type: application/json&#39; \<br>  --header &#39;postman-token: 5790c497-8264-f5b3-025f-d9963c5b41a1&#39; \<br>  --header &#39;x-tenant: default&#39; \<br>  --data &#39;{\n	&quot;username&quot; : &quot;admin2&quot;,\n	&quot;password&quot; : &quot;admin2123&quot;,\n	&quot;fullname&quot; : &quot;Adminitrator for a tenant&quot;\n}&#39;</pre><pre>{<br>    &quot;id&quot;: &quot;9af7a442-bc25-4d2c-b5d1-341dcf6fe2da&quot;,<br>    &quot;tenantId&quot;: &quot;a5c8cbe0-bce5-440b-b18e-ffc96d253092&quot;,<br>    &quot;fullname&quot;: &quot;Adminitrator for a tenant&quot;,<br>    &quot;username&quot;: &quot;admin2&quot;,<br>    &quot;mask&quot;: 0<br>}</pre><pre>$ curl --request POST --url <a href="http://localhost:8081/default/oauth/token">http://localhost:8081/default/oauth/token</a> --header authorization: Basic c3VwZXJzZWNyZXRjbGllbnQ6c3VwZXJzZWNyZXRjbGllbnQxMjM= --header cache-control: no-cache --header content-type: application/x-www-form-urlencoded --header postman-token: 6d5facf2-3143-62ea-09d5-86ee08a76310 --header x-tenant: default --data username=admin2&amp;password=admin2123&amp;audience=self&amp;grant_type=password<br>{<br>    &quot;auth_token&quot;: &quot;eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiZGlyIn0..hhAq6K4M2dH4StukQvbH-A.pLREINAeNzvrDuFC03kewv47nVU2_2xqLypkdm_aO2FBWCPDnQNVCva65K1PcMGXpHGZ2hurbex4ELcM4WB9GX93rKn1W9bP1PmWCqPORX43kEPUgV6E9P6GZ0Y0mrvhQcss8M9qOF1gBlTOAD7F8hFEPEE0HQypVGXv1prt-11bSylVJO55-sOHGW-MITaYy8t0eWL8WDdP9msVdrcpjjqEVAaM6snJGPc7xp3l4NM.XUedILH4QfRqRKGliAtgtQ&quot;,<br>    &quot;expiry&quot;: 500,<br>    &quot;refreshToken&quot;: &quot;eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiZGlyIn0..zuO7tVknKsgnM5R37gobRg.TDciaBT-StLDTLjBIeR-rLQgFCG7UOUxHREJ5uK8DgVgCvsNQ4xufTEYxcrUxskF5Gr717-HvIrNsXtTnPQdTpktBfdszNUv8-WFsnG1EV63-t8ZJdo7fWQ_O3DNQY78FvGvvqJoQPs2Besz1P9uDNc4NIb4ivm9Nz51aYMSZYOA-8HzDGlS-0fzQfg5ElUEAjyp0p4KVhpUFifNmZkESGcKfU6tYCbhxGVH1NmD8Ec.ESgaKVnFngNzpYAGDyfq1g&quot;,<br>    &quot;refreshTokenExpiry&quot;: 1000,<br>    &quot;scope&quot;: &quot;read,write&quot;,<br>    &quot;tokenType&quot;: &quot;Bearer&quot;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db571254c5c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a multitenant service]]></title>
            <link>https://medium.com/@vavasthi/building-a-multitenant-service-dd90fcbf6317?source=rss-10ababa9ca66------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd90fcbf6317</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[multitenancy]]></category>
            <category><![CDATA[multi-tenant]]></category>
            <dc:creator><![CDATA[Vinay Avasthi]]></dc:creator>
            <pubDate>Tue, 23 Jun 2020 19:00:57 GMT</pubDate>
            <atom:updated>2020-06-23T19:00:57.843Z</atom:updated>
            <content:encoded><![CDATA[<p>If you build any production service that is valuable, very soon you find a customer who wants to use it but wants it white-labeled for him. You also very quickly find out that there is a need to data isolation, i.e. different customers want their data to be kept in their own databases. Because of these reasons, it is always a good idea to design a service keeping multi-tenancy in mind.</p><p>In this tutorial we will look at some of the important features required for a multi-tenant service and how do we leverage <em>springframework</em> to deliver a service that is truly enabled for a modern multi-tenant service.</p><p>Here are couple of the important aspects of a multi-tenant service.</p><ol><li>Everybody gets their own endpoints</li><li>Everybody can be given their own databases</li></ol><p>Let’s design how our endpoint URLs would look like keeping tenancy in mind. We add a discriminator in the URL that identified a tenant. For example our OAuth URLs would become something like below.</p><pre><a href="http://example.com/tenant1/oauth/token">http://example.com/tenant1/oauth/token</a><br>http://example.com/tenant1/oauth/check_token</pre><p>To accomplish, we define our <em>RequestMapping</em> with an embedded tenant variable that becomes part of each of the URLs.</p><pre>public static final String BASE_ENDPOINT = &quot;/{tenant}&quot;;<br> public static final String USER_ENDPOINT = BASE_ENDPOINT + &quot;/user&quot;;<br> public static final String REGISTRATION_ENDPOINT = BASE_ENDPOINT + &quot;/registration&quot;;</pre><p>As we can see, the first part of the URL defines the tenant. It is not mandatory but I also design the service so that a header is expected that also defines the tenant. This is just to guard against some client mistakenly calling a wrong tenant because the same tenant has to be added in two places. We will use following header.</p><pre>X-tenant:tenant1</pre><p>Every incoming request into the system needs to know the tenant and the authenticated user that is part of the request. We define a sequence of filters for this purpose. Since these filters need to be called in a particular order, we define the order as follow.</p><pre>public static final int TENANT_HEADER_PRECEDENCE = Ordered.HIGHEST_PRECEDENCE;<br>public static final int SEED_DATA_PRECEDENCE = TENANT_HEADER_PRECEDENCE - 1;<br>public static final int TENANT_PRECEDENCE = SEED_DATA_PRECEDENCE - 1;<br>public static final int USER_PRECEDENCE = Ordered.LOWEST_PRECEDENCE;</pre><p>As you can see we are going to define four filters which will perform specific functions.</p><ol><li>TenantHeader filter will extract tenant header from the incoming request, match the URL piece with the header and set it in a ThreadLocal variable.</li><li>SeedData filter is only require to create some seed data to make the service usable. We need a default tenant in the system so that we can start making some requests. This doesn’t do anything most of the time.</li><li>Tenant filter will extract the tenant object and set it into another ThreadLocal variable.</li><li>User filter is the last in the precedence and will extract the current authenticated user and will store it into a ThreadLocal.</li></ol><p>We are using following TutorialRequestContext class to store these thread local variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/359517a7bc528211d0772938414f93f5/href">https://medium.com/media/359517a7bc528211d0772938414f93f5/href</a></iframe><p>Now let’s look at these filters one by one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29d010f210199a145225d6b08460a6b4/href">https://medium.com/media/29d010f210199a145225d6b08460a6b4/href</a></iframe><p>This filter just extracts the X-tenant header stores in the thread local.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c0b77a5efd63f6f0d7d2fa5da7bb8ae/href">https://medium.com/media/6c0b77a5efd63f6f0d7d2fa5da7bb8ae/href</a></iframe><p>This filter checks that there should be at least one tenant in the system, if not found, it inserts a default tenant. This is required so that we can use rest calls.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ce000e90b4e10b6badb463cfff26b72/href">https://medium.com/media/6ce000e90b4e10b6badb463cfff26b72/href</a></iframe><p>This filter extract the complete Tenant object from the database and stores it into the thread local.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/713ccae5f7d24e73c94e42ad01c050a3/href">https://medium.com/media/713ccae5f7d24e73c94e42ad01c050a3/href</a></iframe><p>This filter extract currently authenticate user and populates it in the thread local.</p><p>In the last tutorial, we used the spring provided default <em>ClientDetailsService</em>, we create our own service in this tutorial to make sure we can have a schema that we like. To do that we need a entity, <em>TutorialClientDetails</em> and a service <em>TutorialClientDetailsService</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08a1ff65ea63a516e6b2fba46d8f3c0f/href">https://medium.com/media/08a1ff65ea63a516e6b2fba46d8f3c0f/href</a></iframe><p>This entity just implements the <em>ClientDetails</em> interface</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/653bfc8c90a1eb1a3b9867b54c54be7b/href">https://medium.com/media/653bfc8c90a1eb1a3b9867b54c54be7b/href</a></iframe><p>This service needs to implement a method <em>loadClientByClientId</em>.</p><p>Now that all the foundation work is in place, we get down to making our service multitenant. The first things that we need to do is to remove all the old dataSources that we had defined. We will now define a routing data source that will choose the right data source based on the tenant that we are taking to. This is where our tenant discriminator thread local will be usedful. Take a look at the following class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7028bb76ecb29d969edbcb7342e65ee5/href">https://medium.com/media/7028bb76ecb29d969edbcb7342e65ee5/href</a></iframe><p>Here we implement a method <em>determineCurrentLookupKey</em> which uses thread local to identify the current tenant and returns the key.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29b562abefb8068e5a1bfacbc09ef811/href">https://medium.com/media/29b562abefb8068e5a1bfacbc09ef811/href</a></iframe><p>The bulk of smartness lies in the class <em>TutorialMultitenantConfig,</em> specifically the dataSource bean that returns the default dataSource for the system. What we are assuming that within our resource directory, we will have a tenants subdirectory and within that we will have one properties file per tenant. The property file will look like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/821bb0e2f667f2f6a95b228b22d7aac9/href">https://medium.com/media/821bb0e2f667f2f6a95b228b22d7aac9/href</a></iframe><p>Here we have added usual spring data source properties alongwith a name property which will be the name of the tenant. This name will be matched with the name in the URL and the header.</p><p>In the class <em>TutorialMultitenantConfig,</em> look at the definition of variable <em>TENANT_PROPERTIES_RESOURCE</em>, this basically looks up for all the <em>*.properties</em> file in the tenant directory. Lines 61 through 74, create a data source object for each of the tenants and store these in a map with key being the tenant name. We remember <em>determineCurrentLookupKey</em> method which returned the name of current tenant, that return value is used to fetch appropriate data source object for the request being processed. Line 88 defines a default data source that is used if there is no data source present for the given tenant.</p><p>Now our multi tenanted service is ready and it is time to test. The first thing that we need to do is create couple of more databases with exact same schema as the first database. Please keep in mind that this has to be done manually even if you have defined ddl-auto property. Just take a mysqldump of the first database and import in two other databases.</p><p>We also need to make sure that the system atleast has one tenant defined in each of the databases. This is required in order to make sure we are able to use the rest calls. The best approach is to have a default tenant and then take a dump so that default tenant is also copied in each of the databases. We have created an admin user which has ADMIN role. We call the user endpoint that will return the list of all the users.</p><pre>$ curl --request GET \<br>&gt;   --url <a href="http://localhost:8081/tenant1/user">http://localhost:8081/tenant1/user</a> \<br>&gt;   --header &#39;authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTI5Mzc1MzksInVzZXJfbmFtZSI6ImFkbWluIiwiYXV0aG9yaXRpZXMiOlsiVVNFUiIsIkFETUlOIl0sImp0aSI6IjRmOTdiNThkLTI1NTEtNDA4Yi04ZWM4LWUzZGZmZWQ3MTQ2NiIsImNsaWVudF9pZCI6InN1cGVyc2VjcmV0Y2xpZW50Iiwic2NvcGUiOlsicmVhZCIsImNvZGUiLCJ3cml0ZSJdfQ.fWt_H-ORHP44xOIljoqMfVIeGkqJGQqUBMj8paVxAPM&#39; \<br>&gt;   --header &#39;cache-control: no-cache&#39; \<br>&gt;   --header &#39;content-type: application/json&#39; \<br>&gt;   --header &#39;postman-token: 76b3525e-bc3b-e629-91b6-a75253f657d8&#39; \<br>&gt;   --header &#39;x-tenant: tenant1&#39; |python -m json.tool</pre><pre>[<br>    {<br>        &quot;createdAt&quot;: 1592936869000,<br>        &quot;createdBy&quot;: &quot;UnAuthenticated&quot;,<br>        &quot;email&quot;: &quot;admin@springframework.in&quot;,<br>        &quot;fullname&quot;: &quot;Spring Tutorial Admin&quot;,<br>        &quot;grantedAuthorities&quot;: [<br>            &quot;ADMIN&quot;,<br>            &quot;USER&quot;<br>        ],<br>        &quot;id&quot;: 6,<br>        &quot;mask&quot;: 1,<br>        &quot;tenantId&quot;: 1,<br>        &quot;updatedAt&quot;: 1592936869000,<br>        &quot;updatedBy&quot;: &quot;UnAuthenticated&quot;,<br>        &quot;username&quot;: &quot;admin&quot;<br>    },<br>    {<br>        &quot;createdAt&quot;: 1592904896000,<br>        &quot;createdBy&quot;: &quot;UnAuthenticated&quot;,<br>        &quot;email&quot;: &quot;defaultuser@defaultadmin.com&quot;,<br>        &quot;fullname&quot;: &quot;Default User&quot;,<br>        &quot;grantedAuthorities&quot;: [],<br>        &quot;id&quot;: 2,<br>        &quot;mask&quot;: 0,<br>        &quot;tenantId&quot;: 1,<br>        &quot;updatedAt&quot;: 1592904896000,<br>        &quot;updatedBy&quot;: &quot;UnAuthenticated&quot;,<br>        &quot;username&quot;: &quot;defaultuser&quot;<br>    },<br>    {<br>        &quot;createdAt&quot;: 1592904900000,<br>        &quot;createdBy&quot;: &quot;UnAuthenticated&quot;,<br>        &quot;email&quot;: &quot;vinay@avasthi.com&quot;,<br>        &quot;fullname&quot;: &quot;Vinay Avasthi&quot;,<br>        &quot;grantedAuthorities&quot;: [],<br>        &quot;id&quot;: 3,<br>        &quot;mask&quot;: 1,<br>        &quot;tenantId&quot;: 1,<br>        &quot;updatedAt&quot;: 1592904900000,<br>        &quot;updatedBy&quot;: &quot;UnAuthenticated&quot;,<br>        &quot;username&quot;: &quot;vavasthi&quot;<br>    }<br>]</pre><p>Now we run the same query in tenant2</p><pre>$ curl --request GET   --url <a href="http://localhost:8081/tenant2/user">http://localhost:8081/tenant2/user</a>   --header &#39;authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTI5MzgzMDcsInVzZXJfbmFtZSI6ImFkbWluIiwiYXV0aG9yaXRpZXMiOlsiVVNFUiIsIkFETUlOIl0sImp0aSI6IjJmOWVkOTYxLTk5MjktNDI3Zi1iZGU4LTc5NGIwYWNhMGYzNiIsImNsaWVudF9pZCI6InN1cGVyc2VjcmV0Y2xpZW50Iiwic2NvcGUiOlsicmVhZCIsImNvZGUiLCJ3cml0ZSJdfQ.KNzjB_JqJDaVI5vZNK-OcXDgvM5Uwt4I8tsVCazerpU&#39;   --header &#39;cache-control: no-cache&#39;   --header &#39;content-type: application/json&#39;   --header &#39;postman-token: b1a9651c-e4c0-7b2e-c7b3-e0b3e06fa40e&#39;   --header &#39;x-tenant: tenant2&#39; |python -m json.tool<br>[<br>    {<br>        &quot;createdAt&quot;: 1592904896000,<br>        &quot;createdBy&quot;: &quot;UnAuthenticated&quot;,<br>        &quot;email&quot;: &quot;defaultuser@defaultadmin.com&quot;,<br>        &quot;fullname&quot;: &quot;Default User&quot;,<br>        &quot;grantedAuthorities&quot;: [],<br>        &quot;id&quot;: 2,<br>        &quot;mask&quot;: 0,<br>        &quot;tenantId&quot;: 1,<br>        &quot;updatedAt&quot;: 1592904896000,<br>        &quot;updatedBy&quot;: &quot;UnAuthenticated&quot;,<br>        &quot;username&quot;: &quot;defaultuser&quot;<br>    },<br>    {<br>        &quot;createdAt&quot;: 1592904900000,<br>        &quot;createdBy&quot;: &quot;UnAuthenticated&quot;,<br>        &quot;email&quot;: &quot;vinay@avasthi.com&quot;,<br>        &quot;fullname&quot;: &quot;Vinay Avasthi&quot;,<br>        &quot;grantedAuthorities&quot;: [],<br>        &quot;id&quot;: 3,<br>        &quot;mask&quot;: 1,<br>        &quot;tenantId&quot;: 1,<br>        &quot;updatedAt&quot;: 1592904900000,<br>        &quot;updatedBy&quot;: &quot;UnAuthenticated&quot;,<br>        &quot;username&quot;: &quot;vavasthi&quot;<br>    },<br>    {<br>        &quot;createdAt&quot;: 1592938002000,<br>        &quot;createdBy&quot;: &quot;UnAuthenticated&quot;,<br>        &quot;email&quot;: &quot;ut2@springframework.in&quot;,<br>        &quot;fullname&quot;: &quot;User in T2&quot;,<br>        &quot;grantedAuthorities&quot;: [],<br>        &quot;id&quot;: 6,<br>        &quot;mask&quot;: 1,<br>        &quot;tenantId&quot;: 1,<br>        &quot;updatedAt&quot;: 1592938002000,<br>        &quot;updatedBy&quot;: &quot;UnAuthenticated&quot;,<br>        &quot;username&quot;: &quot;userint2&quot;<br>    },<br>{<br>        &quot;createdAt&quot;: 1592937749000,<br>        &quot;createdBy&quot;: &quot;UnAuthenticated&quot;,<br>        &quot;email&quot;: &quot;admin@springframework.in&quot;,<br>        &quot;fullname&quot;: &quot;Springframework Tenant2 Administrator&quot;,<br>        &quot;grantedAuthorities&quot;: [<br>            &quot;ADMIN&quot;,<br>            &quot;USER&quot;<br>        ],<br>        &quot;id&quot;: 5,<br>        &quot;mask&quot;: 1,<br>        &quot;tenantId&quot;: 1,<br>        &quot;updatedAt&quot;: 1592937749000,<br>        &quot;updatedBy&quot;: &quot;UnAuthenticated&quot;,<br>        &quot;username&quot;: &quot;admin&quot;<br>    }<br>]</pre><p>As we can see, we are seeing two totally different sets of users which are stored in two totally different sets of databases.</p><p>Complete code for this blog post is available in my github repository <a href="https://www.springframework.in/2020/06/building-multitenant-service.html#">here</a>.</p><p>This post first appeared on my blog <a href="https://www.springframework.in/2020/06/building-multitenant-service.html">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd90fcbf6317" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OAuth2 and JWT Tokens Part 1]]></title>
            <link>https://medium.com/@vavasthi/oauth2-and-jwt-tokens-part-1-b6d0df74bc04?source=rss-10ababa9ca66------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6d0df74bc04</guid>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Vinay Avasthi]]></dc:creator>
            <pubDate>Sun, 21 Jun 2020 09:00:42 GMT</pubDate>
            <atom:updated>2020-06-21T09:00:42.203Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post we look at how do we make our spring server become an OAuth2 Authorization server and start producing JWT tokens.</p><p>The first step that we take is disable all the filters that we had added earlier. We don’t want to authorize using old style REST calls.</p><p>Now, the first step is to enable our authorization server. We create a new java configuration file that extends <em>AuthorizationServerConfigurerAdapter.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22359a5df40491fd14724ce1f15e0785/href">https://medium.com/media/22359a5df40491fd14724ce1f15e0785/href</a></iframe><p>In the configuration , we autowire <em>AuthenticationManager, DataSource </em>and a<em> UserDetailsService</em>. There are two types of auth tokens in OAuth2. The first one are the usual tokens that are requested by users by providing their username and password. The second set of tokens are not tied to individual users, these are called client tokens and could be used for services talking to each other.</p><p>We configure <em>ClientDetailsService</em> to use Jdbc client service. We add a password encoder in the configuration and provide a data source that would be used to store persistent data. In our example, we are using <em>SCryptPasswordEncoder</em>. Here we are using spring provided Jdbc client service but one could implement <em>ClientDetailsService</em> and <em>ClientRegistrationService</em> interfaces and provide their own custom implementation for client service.</p><p>The next steps is to enable web security and provide an authentication manager bean for performing authentication.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c355ba1deddc2b6426f0d0c323bbd970/href">https://medium.com/media/c355ba1deddc2b6426f0d0c323bbd970/href</a></iframe><p>We have seen earlier that we used a <em>UserDetailsService</em> to configure the authorization server. We are not going to use the spring provided service but write our own.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84ca78d7b0c3966e8f89f70400432799/href">https://medium.com/media/84ca78d7b0c3966e8f89f70400432799/href</a></iframe><p>In the <em>UserDetailsService,</em> we need to provide our own implementation for a method <em>loadByUsername</em>. In this method, we basically load the user entity from our database and create an object of type <em>UserDetails</em> and return it. The object also requires a list of <em>GrantedAuthority</em>.</p><p><em>UserDetails</em> is an interface provided in <em>springframework</em>, we create our own class that implements the interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35aaf86c2b267a8ccbdfecb9a3b30bbd/href">https://medium.com/media/35aaf86c2b267a8ccbdfecb9a3b30bbd/href</a></iframe><p>Similar to <em>UserDetails</em>, <em>GrantedAuthority</em> is also an interface provided by <em>springframework</em>, we implement that interface to provide our concrete implementation of <em>GrantedAuthority</em>. For a very simple understanding, <em>GrantedAuthority</em> is like a user role. We can use this role later to provide access control on endpoints.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/846019b467db4674837d8f11efa37ea6/href">https://medium.com/media/846019b467db4674837d8f11efa37ea6/href</a></iframe><p>These changes will make the server ready for OAuth2 service. We still have a testing nightmare. Because now all our endpoints are behind this authentication filter, there is no way for us to create new clients and users. We could directly insert values in database, but we still have to worry about how to encrypt the password before inserting into the data. To get out of this situation, I add two endpoints, one for handling clients and another for handling users. These endpoints need to be configured so that they don’t go through the authentication service. These need to be removed before the service goes into production.</p><p>We define a pojo that mimics the <em>OauthClientDetails</em> schema in the database. It looks like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5bb6fdf90a6f6e5f3a7d86b852b4d4a/href">https://medium.com/media/c5bb6fdf90a6f6e5f3a7d86b852b4d4a/href</a></iframe><p>Now we add a repository for handling <em>OauthClientDetails table.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd9bc9c30b0e21a38cdea57889a3704e/href">https://medium.com/media/cd9bc9c30b0e21a38cdea57889a3704e/href</a></iframe><p>We also add a service layer for Client handling.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8dd702a9685742c9b009f92fde047923/href">https://medium.com/media/8dd702a9685742c9b009f92fde047923/href</a></iframe><p>We already had a <em>UserRepository</em>, we change it to encrypt the password before use store the password.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaa9e93a3912e655a4647eb71b3f2b89/href">https://medium.com/media/eaa9e93a3912e655a4647eb71b3f2b89/href</a></iframe><p>We also add a service layer for User.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6e67e36948d23c40dced64e31013566/href">https://medium.com/media/c6e67e36948d23c40dced64e31013566/href</a></iframe><p>Now that we have all the layers required, we add the endpoint for Client.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e76ad0ec3c475725b8d1ccbbfe33cad2/href">https://medium.com/media/e76ad0ec3c475725b8d1ccbbfe33cad2/href</a></iframe><p>The next thing to modify is the endpoint layer for user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0232648f43c4aa1b7d22a57644000382/href">https://medium.com/media/0232648f43c4aa1b7d22a57644000382/href</a></iframe><p>Now we are ready with our code for create new clients and users. We still have the small issue because if we hit these endpoints, we will get unauthorized error. So we need to put these in the exception list. For this we go to our <em>SecurityConfiguration</em> that we had defined in one of the earlier tutorials.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56b750756e3ccc726286f1e7c21a3f61/href">https://medium.com/media/56b750756e3ccc726286f1e7c21a3f61/href</a></iframe><p>Look at the method <em>public void configure(WebSecurity web) throws Exception</em>. We have added following two lines to ignore evaluation of authentication filters for two families of URL.</p><pre>web.ignoring().antMatchers(&quot;/oauth/client/**&quot;);<br>        web.ignoring().antMatchers(&quot;/user/**&quot;);</pre><p>Of course this is very dangerous and we have added it only for testing purpose. In a future tutorial we will have a more elegant solution for this.</p><p>Now we are ready. We can test the service with following curl or equivalent command.</p><pre>curl -X POST \<br>  <a href="http://localhost:8081/oauth/token">http://localhost:8081/oauth/token</a> \<br>  -H &#39;authorization: Basic YW5kcm9pZC1jbGllbnQ6YW5kcm9pZC1zZWNyZXQ=&#39; \<br>  -H &#39;cache-control: no-cache&#39; \<br>  -H &#39;content-type: application/x-www-form-urlencoded&#39; \<br>  -H &#39;postman-token: 3a349bc0-1230-adbe-4b79-9b938728a101&#39; \<br>  -d &#39;grant_type=password&amp;password=mypassword&amp;username=myuser&amp;client_id=my-client&amp;client_secret=my-secret&#39;</pre><p>This is the response that we get</p><pre>{<br>    &quot;access_token&quot;: &quot;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTI3MjI5NTgsInVzZXJfbmFtZSI6InZhdmFzdGhpIiwianRpIjoiOGExZDYxN2ItZDU4OC00Nzc5LThlOTQtYTBiNWZkYzcxOTg2IiwiY2xpZW50X2lkIjoiYW5kcm9pZC1jbGllbnQiLCJzY29wZSI6WyJjb2RlIl19.n7hCnBdnjMC8vuCsHxkOznfd06iJctGNeypx2fXWla4&quot;,<br>    &quot;token_type&quot;: &quot;bearer&quot;,<br>    &quot;refresh_token&quot;: &quot;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTI3MjMwNTgsInVzZXJfbmFtZSI6InZhdmFzdGhpIiwianRpIjoiNGU4ODg3OTYtZWZiZS00ZDc5LTg1YmMtN2EzNzFhM2I4Yzg0IiwiY2xpZW50X2lkIjoiYW5kcm9pZC1jbGllbnQiLCJzY29wZSI6WyJjb2RlIl0sImF0aSI6IjhhMWQ2MTdiLWQ1ODgtNDc3OS04ZTk0LWEwYjVmZGM3MTk4NiJ9.xuElTWYSLscgdcqj0t-4t6prJbVOfHVqM331UUjfPBQ&quot;,<br>    &quot;expires_in&quot;: 99,<br>    &quot;scope&quot;: &quot;code&quot;,<br>    &quot;jti&quot;: &quot;8a1d617b-d588-4779-8e94-a0b5fdc71986&quot;<br>}</pre><p>We can get the refresh token by calling the same endpoint with grant_type refresh_token.</p><pre>curl -X POST \<br>&gt;   <a href="http://localhost:8081/oauth/token">http://localhost:8081/oauth/token</a> \<br>&gt;   -H &#39;authorization: Basic YW5kcm9pZC1jbGllbnQ6YW5kcm9pZC1zZWNyZXQ=&#39; \<br>&gt;   -H &#39;cache-control: no-cache&#39; \<br>&gt;   -H &#39;content-type: application/x-www-form-urlencoded&#39; \<br>&gt;   -H &#39;postman-token: 0adf261f-ed1e-85b3-67a5-21430fee8b38&#39; \<br>&gt;   -d &#39;grant_type=refresh_token&amp;refresh_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTI3MjMxOTAsInVzZXJfbmFtZSI6InZhdmFzdGhpIiwianRpIjoiNGMwNjczOTQtZjllNS00NDVjLTg5MzItMmRiMDM4N2U2ZjIxIiwiY2xpZW50X2lkIjoiYW5kcm9pZC1jbGllbnQiLCJzY29wZSI6WyJjb2RlIl0sImF0aSI6ImE1ZmY5MjhiLWQ1YjEtNDQ5Yy04N2I4LTU3ODgwYzY1NjM3NiJ9.RS2K7N5XCHQNov02WNu1QK1AqOvgc7MuNzeCydt7Ajs&#39;</pre><p>We get following response.</p><pre>{<br>    &quot;access_token&quot;: &quot;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTI3MjMxNzQsInVzZXJfbmFtZSI6InZhdmFzdGhpIiwianRpIjoiY2E1OWU3NzktZDRkZS00NDU1LWFlNjItNDQ2NTAxYzUxZjhmIiwiY2xpZW50X2lkIjoiYW5kcm9pZC1jbGllbnQiLCJzY29wZSI6WyJjb2RlIl19.WgVgpBWuDmdJUk3UG8MTKOBsXn5zbEGO8gyqg2akN8o&quot;,<br>    &quot;token_type&quot;: &quot;bearer&quot;,<br>    &quot;refresh_token&quot;: &quot;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTI3MjMxOTAsInVzZXJfbmFtZSI6InZhdmFzdGhpIiwianRpIjoiNGMwNjczOTQtZjllNS00NDVjLTg5MzItMmRiMDM4N2U2ZjIxIiwiY2xpZW50X2lkIjoiYW5kcm9pZC1jbGllbnQiLCJzY29wZSI6WyJjb2RlIl0sImF0aSI6ImNhNTllNzc5LWQ0ZGUtNDQ1NS1hZTYyLTQ0NjUwMWM1MWY4ZiJ9.3zDqHLSwVLq_Dg8r4Ppf5tfvzxwT_7FEwdTV67l3VYQ&quot;,<br>    &quot;expires_in&quot;: 99,<br>    &quot;scope&quot;: &quot;code&quot;,<br>    &quot;jti&quot;: &quot;ca59e779-d4de-4455-ae62-446501c51f8f&quot;<br>}</pre><p>We can verify a token by accessing <em>oauth/check_token</em> endpoint and providing the token.</p><pre>curl --request POST \<br>&gt;   --url <a href="http://localhost:8081/oauth/check_token">http://localhost:8081/oauth/check_token</a> \<br>&gt;   --header &#39;authorization: Basic YW5kcm9pZC1jbGllbnQ6YW5kcm9pZC1zZWNyZXQ=&#39; \<br>&gt;   --header &#39;cache-control: no-cache&#39; \<br>&gt;   --header &#39;content-type: application/x-www-form-urlencoded&#39; \<br>&gt;   --header &#39;postman-token: ef035580-4cba-a7a1-deaa-dcf5f59e41fc&#39; \<br>&gt;   --data token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTI3MjM2MTEsInVzZXJfbmFtZSI6InZhdmFzdGhpIiwianRpIjoiODZhZjZhYmUtZjA4YS00YzIzLThkYzYtYjY2ZmM3ZWQ0YWRiIiwiY2xpZW50X2lkIjoiYW5kcm9pZC1jbGllbnQiLCJzY29wZSI6WyJjb2RlIl19.Kn284yuxxHSxVtEc3D8H5YjVjPi0yN6oX1hDwEx5bOo</pre><p>We get the following response.</p><pre>{<br>    &quot;client_id&quot;: &quot;android-client&quot;,<br>    &quot;exp&quot;: 1592723611,<br>    &quot;jti&quot;: &quot;86af6abe-f08a-4c23-8dc6-b66fc7ed4adb&quot;,<br>    &quot;scope&quot;: [<br>        &quot;code&quot;<br>    ],<br>    &quot;user_name&quot;: &quot;myuser&quot;<br>}</pre><p>This is all about enabling JWT OAuth tokens with any spring server. We will continue this tutorial in next part with some more important details. The complete code for the working server is <a href="https://github.com/vavasthi/springblog/tree/v1.6">here</a>.</p><p>This post first appeared on my <a href="https://www.springframework.in/2020/06/oauth2-and-jwt-tokens-part-1.html">Springframework blog here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6d0df74bc04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hive and Spark]]></title>
            <link>https://medium.com/@vavasthi/hive-and-spark-e23eadb455ee?source=rss-10ababa9ca66------2</link>
            <guid isPermaLink="false">https://medium.com/p/e23eadb455ee</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[hive]]></category>
            <dc:creator><![CDATA[Vinay Avasthi]]></dc:creator>
            <pubDate>Tue, 18 Feb 2020 09:37:46 GMT</pubDate>
            <atom:updated>2020-02-18T09:37:46.861Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, we take a slight deviation from core issues related to the spring framework and look at an issue that spring programmers might face regularly. Recently I was looking with Spark and found a need to read the data from MySQL, do some processing and write it back to a hive instance. We will look at this issue in this post.<br>We start by making sure our hive instance is backed by a database. To do this, we do the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a95578ae9c901197d3d3bb1bfd20ca23/href">https://medium.com/media/a95578ae9c901197d3d3bb1bfd20ca23/href</a></iframe><p>We can configure the values to suit our needs. But make sure the MySQL username, password, database URL exists and has relevant permissions.<br>Now we create another database in MySQL which will contain the data that we need to process. I am calling this database mystuff, with username mystuff, password mystuff123. We need to run following commands in MySQL to make sure everything exists and permissions are appropriate.</p><pre>create database mystuff;<br>Query OK, 1 row affected (0.00 sec)<br><br>mysql&gt; create user mystuff@localhost identified by &#39;mystuff123&#39;;<br>Query OK, 0 rows affected (0.00 sec)<br><br>mysql&gt; create user mystuff@&#39;%&#39; identified by &#39;mystuff123&#39;;<br>Query OK, 0 rows affected (0.01 sec)<br><br>mysql&gt; grant all on mystuff.* to mystuff@localhost;<br>Query OK, 0 rows affected (0.00 sec)<br><br>mysql&gt; grant all on mystuff.* to mystuff@&#39;%&#39;;<br>Query OK, 0 rows affected (0.00 sec)</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cec35bc4d9481e45923bd33f9953b14f/href">https://medium.com/media/cec35bc4d9481e45923bd33f9953b14f/href</a></iframe><p>Now to look at the problem at hand. We have a table in MySQL with the following structure.</p><pre>mysql&gt; desc mydata;<br>+-------+--------------+------+-----+---------+-------+<br>| Field | Type         | Null | Key | Default | Extra |<br>+-------+--------------+------+-----+---------+-------+<br>| id    | int          | YES  |     | NULL    |       |<br>| k     | varchar(10)  | YES  |     | NULL    |       |<br>| v     | varchar(255) | YES  |     | NULL    |       |<br>+-------+--------------+------+-----+---------+-------+<br>3 rows in set (0.00 sec)</pre><p>We want to flatten this table such that each key gets converted to a column for each id. So assume our current data is as below.</p><pre>mysql&gt; select * from mydata;<br>+------+-------+-------------------+<br>| id   | k     | v                 |<br>+------+-------+-------------------+<br>|    1 | NAME  | John Doe.         |<br>|    1 | EMAIL | jd@example.com    |<br>|    2 | NAME  | Jane Doe          |<br>|    2 | EMAIL | janed@example.com |<br>+------+-------+-------------------+<br>2 rows in set (0.00 sec)</pre><p>We want to load this data and convert it into a flattened table that has three columns i.e. id, name. email. Then we want to populate this into table person into hive with flattened data.</p><pre>hive (default)&gt; select * from person;<br>OK<br>person.id person.email person.name<br>1 jd@example.com.  John Doe<br>2 janed@example.com Jane Doe<br>Time taken: 0.094 seconds, Fetched: 2 row(s)</pre><p>The following code will perform the above conversion.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a535da074ddb83cfc7daf1be6930671/href">https://medium.com/media/1a535da074ddb83cfc7daf1be6930671/href</a></iframe><p>Line numbers 11 through 17 create a SparkSession for hive operations. The key instruction here is enableHiveSupport. Lines 20 through 26 create a SparkSession that will be used for MySQL operations. Lines 29 through 37 load the complete contents of the table. Lines 39 through 42 will group the results by the id and pivot the table on the field K. Line 46 through 49 creates a data frame for hiveSession and writes the contents in a table with named person.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e23eadb455ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The morality of a machine]]></title>
            <link>https://medium.com/geekverse/the-morality-of-a-machine-1ed110d52c38?source=rss-10ababa9ca66------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ed110d52c38</guid>
            <category><![CDATA[self-driving-cars]]></category>
            <dc:creator><![CDATA[Vinay Avasthi]]></dc:creator>
            <pubDate>Wed, 20 Feb 2019 04:47:46 GMT</pubDate>
            <atom:updated>2019-02-20T04:47:46.568Z</atom:updated>
            <content:encoded><![CDATA[<p>It is 2019, everybody is gung-ho on about Artificial Intelligence and/or Machine Learning. If we look around, there are many systems that exist today which incorporate AI/ML in some shape or form. Most systems in product consist of typical classifiers or regression that provides information to make a particular decision. The question of the morality of a machine has not found top consideration because till now the AI/ML is producing output that is used by a human to make actual decision.</p><p>When Google Photo image tagging algorithm misclassifies an image and tags it with somebody else&#39;s’ name, it is not a serious problem because I can personally go ahead and reclassify the photo with the correct name. Still, the algorithm is correctly classifying more than 90% of images accurately and reducing my workload. When Google Mail or <em>Gmail</em> misclassifies one of the important email containing a notice from the income tax department, it is a significant hassle but still something that I can easily fix. The primary point here is that all the input created by AI is brought to the notice of a human who looks at all the available data before making any decision.</p><p>But, the day is not far off when we will reach a situation where machines may be directly handling responses and humans are either not in the loop or they become so unmindful of what the machines are doing for you that just ignore those actions. For example, it is not inconceivable to expect Gmail to automatically respond to any notice received from the income tax department by looking at your financial data that is stored on some Google Drive. It does not have the capability today but the technology exists where this capability can be easily built.</p><p>The problem becomes more compounded where the actions taken by machines may result in serious hazards to humans. Look at all the excitement around self-driving cars. When human’s are driving cars, they are constantly making decisions that are driven by morality rather than plain logic. Take an example where you are driving your car and on one side there is a pedestrian or a cyclist while on the other side of your car there is another car. Most human would err on the side of the car because that is just the material damage. Our morality expects us to value human life higher than material things. If we extend this problem, let’s say the self-driving car AI realizes that it can’t avoid an accident, it has to choose between a child and one aged person. Suddenly the decision becomes extremely difficult. Humans make these decisions instinctively and many are disturbed through decisions for many years down the line.</p><p>Should you value the life of a child higher than a senior citizen? What about when you have to choose between parent and child? What about choosing between the head of state and a normal person? These are complex decisions. We can write code that can make these decisions but the rules have to be defined and agree by society and governments. If every car manufacturer starts making their own moral decisions, that may become anarchy. Governments, Societies, Courts need to define a set of morality rules that every autonomous AI has to follow. I think the time has come when Asimov’s three laws need to be expanded to something like <em>Asimov’s three laws and other morality principles</em>. These principles need to define how a machine can evaluate different outcomes based on a given situation and choose an outcome that is acceptable by courts, societies, and governments. Unless that happens, AI should be relegated to a decision support system and should not become something that has any control.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ed110d52c38" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekverse/the-morality-of-a-machine-1ed110d52c38">The morality of a machine</a> was originally published in <a href="https://medium.com/geekverse">Geekverse</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[12. Adding GIT release information]]></title>
            <link>https://medium.com/springframework/12-adding-git-release-information-8c8bbfa9c05b?source=rss-10ababa9ca66------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c8bbfa9c05b</guid>
            <category><![CDATA[actuator]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[commit-id]]></category>
            <category><![CDATA[releases]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Vinay Avasthi]]></dc:creator>
            <pubDate>Tue, 19 Feb 2019 05:56:49 GMT</pubDate>
            <atom:updated>2019-02-19T05:56:49.901Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous post, we saw how to enable actuator endpoints on our spring server. Once we have done that, it is a good idea to add GIT release information to the server in order to get the information related to the currently deployed server at runtime.<br>We add the <em>git-commit-id-plugin</em> to our <em>pom.xml</em>.</p><pre>&lt;plugin&gt;<br>    &lt;groupid&gt;pl.project13.maven&lt;/groupid&gt;<br>    &lt;artifactid&gt;git-commit-id-plugin&lt;/artifactid&gt;<br>    &lt;version&gt;2.2.1&lt;/version&gt;<br>   &lt;/plugin&gt;</pre><p>The next things to do is to create a git.properties file in the resource directory of the project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cdd2b1e1f5006e9ac678117072e38c2/href">https://medium.com/media/8cdd2b1e1f5006e9ac678117072e38c2/href</a></iframe><p>The git-commit-id is added by the maven plugin so it is a good idea to build the project using maven.</p><pre>$ mvn clean package -DskipTests</pre><p>Now we can run the server and check the <em>/manage/info</em> endpoint using <em>curl</em> command.</p><pre>$ curl -X GET <a href="http://localhost:9091/manage/info">http://localhost:9091/manage/info</a><br>{&quot;git&quot;:{&quot;branch&quot;:&quot;master&quot;,&quot;commit&quot;:{&quot;id&quot;:&quot;6fb94c0&quot;,&quot;time&quot;:1549868235.000000000}}</pre><p>This post first appeared in my <a href="https://www.springframework.in/2019/02/12-adding-git-release-information.html">Spring Framework Blog</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c8bbfa9c05b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/springframework/12-adding-git-release-information-8c8bbfa9c05b">12. Adding GIT release information</a> was originally published in <a href="https://medium.com/springframework">Springframework</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[11. Spring Actuators]]></title>
            <link>https://medium.com/springframework/11-spring-actuators-2d22b8688bed?source=rss-10ababa9ca66------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d22b8688bed</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[actuator]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Vinay Avasthi]]></dc:creator>
            <pubDate>Tue, 19 Feb 2019 05:54:30 GMT</pubDate>
            <atom:updated>2019-02-19T05:54:30.608Z</atom:updated>
            <content:encoded><![CDATA[<p>pring provides actuators that are a helpful set of tools to debug the application on runtime. Here is how to enable them. We first add actuator dependency in the pom.xml</p><pre>&lt;dependency&gt;<br>  &lt;groupid&gt;org.springframework.boot&lt;/groupid&gt;<br>  &lt;artifactid&gt;spring-boot-starter-actuator&lt;/artifactid&gt;<br>&lt;/dependency&gt;</pre><p>Now we define a prefix for all the actuator endpoints. We add the following line into the <em>application.properties</em> file. This enables all the actuator endpoints. We can enable specific endpoints by adding a comma delimited list of endpoints. We also deploy management endpoint on a separate port so that we can block its access from something like ELB.</p><pre>management.endpoints.web.base-path=/manage<br>management.server.port=9091<br>management.endpoints.web.exposure.include=*</pre><p>Since we already have a security filter defined, we need to exempt health and info endpoint from security check. We add the following URLs int he SecurityConfiguration configure method.</p><pre>@Override<br>    public void configure(WebSecurity web) throws Exception {<br>        web.ignoring().antMatchers(&quot;/manage/health&quot;);<br>        web.ignoring().antMatchers(&quot;/manage/info&quot;);<br>        web.ignoring().antMatchers(&quot;/webjars/**&quot;);<br>        web.ignoring().antMatchers(&quot;/error&quot;);<br>        web.ignoring().antMatchers(&quot;/swagger-ui.html&quot;);<br>        web.ignoring().antMatchers(&quot;/v2/api-docs/**&quot;);<br>        web.ignoring().antMatchers(&quot;/swagger-resources/**&quot;);<br>    }</pre><p>Here we have added paths related to <em>error</em>, <em>actuator</em>, and <em>swagger.</em><br>This enables actuator endpoints for our server. We can query these endpoints and following is the sample response.</p><pre>$ curl -X GET <a href="http://localhost:9091/manage/health">http://localhost:9091/manage/health</a><br>{&quot;status&quot;:&quot;UP&quot;}</pre><p>This post first appeared in my <a href="https://www.springframework.in/2019/02/11-spring-actuators.html">Spring Framework blog here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d22b8688bed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/springframework/11-spring-actuators-2d22b8688bed">11. Spring Actuators</a> was originally published in <a href="https://medium.com/springframework">Springframework</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10. Application with multiple data sources]]></title>
            <link>https://medium.com/springframework/10-application-with-multiple-data-sources-95f1b4beed3f?source=rss-10ababa9ca66------2</link>
            <guid isPermaLink="false">https://medium.com/p/95f1b4beed3f</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[multiple-datasources]]></category>
            <dc:creator><![CDATA[Vinay Avasthi]]></dc:creator>
            <pubDate>Tue, 19 Feb 2019 04:22:17 GMT</pubDate>
            <atom:updated>2019-02-19T04:22:17.915Z</atom:updated>
            <content:encoded><![CDATA[<p>Many times it is a practical requirement to have multiple databases for a single application. These databases could be at different locations on the cloud and different entities in your application may be dealing with these databases.<br>Multi-tenancy is a great requirement when multiple data sources are needed. Many tenants may insist on having their own databases. Here we present how we can configure the spring application to interact with multiple databases.<br>The first step is to look at our <em>application.properties</em> file. We have a list of properties defined for the default dataSource which we will need to replicate for our second database. Let’s assume we are going to use two data sources, the first one is called the<em> user</em> and the second one is called <em>other</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4e24497508d01540b8220c20547a5c6/href">https://medium.com/media/a4e24497508d01540b8220c20547a5c6/href</a></iframe><p>As we can see above, we have replicated all the data source properties and given it a new prefix, <em>other</em>. Now, these two databases could have completely independent settings. They could point to totally different databases. Each of these properties could be configured to completely different settings. Here we have just changed the name of the <em>database</em>, <em>username</em>, <em>password</em>.<br>To make this work. we will have to split the repositories and the entity objects for each of the data sources. Here we create the following hierarchy of packages for each of the data sources.</p><pre>src/main/java<br>- in.springframework.blog.tutorials<br> - user<br>    - domain<br>    - repository<br>  - other<br>    - domain<br>    - repository</pre><p>As we can see for each of the data sources, we have a domain package that would contain the entities and a repository package that would contain the repository class. This is needed so that each of the entity managers only searches for its own classes.<br>Now we need to define a configuration of each of the data sources that we have defined. The first data source will contain <em>the user</em> table and will also be the primary data source.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cabc9b00e48c9c0826d8a19e03c81f2/href">https://medium.com/media/4cabc9b00e48c9c0826d8a19e03c81f2/href</a></iframe><p>As we can see in the class above, it uses all the properties prefixed with <em>spring.datasource</em> and scans directories related to the user data source. Now let’s look at the configuration for <em>other</em> data source.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdabbc9d6c8b01ac1f87969dc3324f9c/href">https://medium.com/media/fdabbc9d6c8b01ac1f87969dc3324f9c/href</a></iframe><p>The things to note in the <em>other</em> data source is that the <em>@Primary</em> annotation doesn’t exist because we can have only one set of primary beans of a type. Also, the directories to be searched are for the <em>other</em> data source’s <em>domain</em> and <em>repository</em> objects.<br>At this time we also move the old <em>User</em> and <em>UserRepository</em> classes to their respective subdirectories. We also create <em>Other</em> and <em>OtherRepository</em> classes in their respective subdirectories. We also change <em>CrudRepository</em> to <em>JpaRepository</em> in each of the repository classes.<br>Now, our application is set up to use two different data sources and we can verify that by running the application. Since we have set <em>ddl-auto</em> property to <em>update, </em>it should create a new schedule when the application is run.</p><pre>$ mysql -u tutorial -ptutorial123 tutorial<br>mysql: [Warning] Using a password on the command line interface can be insecure.<br>Reading table information for completion of table and column names<br>You can turn off this feature to get a quicker startup with -A</pre><pre>Welcome to the MySQL monitor.  Commands end with ; or \g.<br>Your MySQL connection id is 115<br>Server version: 8.0.12 Homebrew</pre><pre>Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.</pre><pre>Oracle is a registered trademark of Oracle Corporation and/or its<br>affiliates. Other names may be trademarks of their respective<br>owners.</pre><pre>Type &#39;help;&#39; or &#39;\h&#39; for help. Type &#39;\c&#39; to clear the current input statement.</pre><pre>mysql&gt; show tables;<br>+--------------------+<br>| Tables_in_tutorial |<br>+--------------------+<br>| hibernate_sequence |<br>| user               |<br>+--------------------+<br>2 rows in set (0.00 sec)</pre><pre>mysql&gt; desc user;<br>+------------+--------------+------+-----+---------+-------+<br>| Field      | Type         | Null | Key | Default | Extra |<br>+------------+--------------+------+-----+---------+-------+<br>| id         | bigint(20)   | NO   | PRI | NULL    |       |<br>| email      | varchar(255) | YES  | UNI | NULL    |       |<br>| fullname   | varchar(255) | YES  |     | NULL    |       |<br>| password   | varchar(255) | YES  |     | NULL    |       |<br>| username   | varchar(255) | YES  | UNI | NULL    |       |<br>| auth_token | varchar(255) | YES  | UNI | NULL    |       |<br>| expiry     | datetime     | YES  |     | NULL    |       |<br>| mask       | bigint(20)   | NO   |     | NULL    |       |<br>| authToken  | varchar(255) | YES  |     | NULL    |       |<br>+------------+--------------+------+-----+---------+-------+<br>9 rows in set (0.00 sec)</pre><pre>$ mysql -u other -pother123 other<br>mysql: [Warning] Using a password on the command line interface can be insecure.<br>Reading table information for completion of table and column names<br>You can turn off this feature to get a quicker startup with -A</pre><pre>Welcome to the MySQL monitor.  Commands end with ; or \g.<br>Your MySQL connection id is 116<br>Server version: 8.0.12 Homebrew</pre><pre>Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.</pre><pre>Oracle is a registered trademark of Oracle Corporation and/or its<br>affiliates. Other names may be trademarks of their respective<br>owners.</pre><pre>Type &#39;help;&#39; or &#39;\h&#39; for help. Type &#39;\c&#39; to clear the current input statement.</pre><pre>mysql&gt; show tables;<br>+--------------------+<br>| Tables_in_other    |<br>+--------------------+<br>| hibernate_sequence |<br>| other              |<br>+--------------------+<br>2 rows in set (0.00 sec)</pre><pre>mysql&gt; desc other<br>    -&gt; ;<br>+-----------+--------------+------+-----+---------+-------+<br>| Field     | Type         | Null | Key | Default | Extra |<br>+-----------+--------------+------+-----+---------+-------+<br>| id        | bigint(20)   | NO   | PRI | NULL    |       |<br>| otherData | varchar(255) | YES  |     | NULL    |       |<br>+-----------+--------------+------+-----+---------+-------+<br>2 rows in set (0.00 sec)</pre><p>The source code for this tutorial is available at git repository as <a href="https://github.com/vavasthi/springblog/tree/v1.2">v1.2</a>. This post first appeared on my <a href="https://www.springframework.in/2019/02/10-application-with-multiple-datasources.html">Spring Framework blog here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95f1b4beed3f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/springframework/10-application-with-multiple-data-sources-95f1b4beed3f">10. Application with multiple data sources</a> was originally published in <a href="https://medium.com/springframework">Springframework</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>