<?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 Pradeep Maiya on Medium]]></title>
        <description><![CDATA[Stories by Pradeep Maiya on Medium]]></description>
        <link>https://medium.com/@pradeep.maiya?source=rss-907ae7805304------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5J10HN3_IFhx52ZDNqiFgw.jpeg</url>
            <title>Stories by Pradeep Maiya on Medium</title>
            <link>https://medium.com/@pradeep.maiya?source=rss-907ae7805304------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 19:21:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pradeep.maiya/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[DB Migrations Using Liquibase]]></title>
            <link>https://medium.com/version-1/db-migrations-using-liquibase-8cecf0209118?source=rss-907ae7805304------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cecf0209118</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[liquibase]]></category>
            <dc:creator><![CDATA[Pradeep Maiya]]></dc:creator>
            <pubDate>Wed, 20 Sep 2023 15:21:40 GMT</pubDate>
            <atom:updated>2023-09-20T15:21:40.993Z</atom:updated>
            <content:encoded><![CDATA[<p>This documentation will explain how to achieve DB migrations to different environments with the help of the most reliable Java library “Liquibase”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vyYlkDXStQekZSOZ" /><figcaption>Photo by <a href="https://unsplash.com/@ikukevk?utm_source=medium&amp;utm_medium=referral">Kevin Ku</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>Table of contents :</strong></h4><ol><li>What is meant by DB migration &amp; its use cases</li><li>What is Liquibase?</li><li>How to implement Liquibase in Sprint Boot</li><li>Pros &amp; Cons of Liquibase</li><li>Conclusion</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*ybhmB5bCfzLP0494GXUjVA.jpeg" /><figcaption>High-level representation of Liquibase</figcaption></figure><h4><strong><em>What is meant by DB migration &amp; its use cases</em></strong></h4><p>Database migration involves transferring data from one or multiple source databases to one or multiple target databases through the utilization of a dedicated database migration service. This includes the lift &amp; shift of database schema, tables &amp; data (if any).</p><p>The major use cases for DB migration include system upgrades, cloud migration, and merging data from multiple systems. It&#39;s a lift &amp; shift of data from one database server to another.</p><p>There are many libraries available in the market to achieve DB migration, one of which is using <a href="https://medium.com/p/7d48e5e18738">Flyway</a> which was explained in detail in my previous blog. This documentation will briefly explain how to do DB migration using Liquibase &amp; pros/cons of using it.</p><h4>What is Liquibase?</h4><p>Liquibase is an open-source database schema change management solution that enables you to manage revisions of your database changes easily. Which has built-in support for a variety of databases &amp; can be integrated with major industry tools like Maven, Ant, Gradle, Spring Boot, and other CI/CD, etc.</p><p><strong>Benifits of using Liquibase :</strong></p><ol><li>Liquibase helps in the elimination of errors &amp; delays during database releases.</li><li>Liquibase helps in the smooth deploy/rollback of specific version changes without needing to know what has already been deployed.</li><li>Liquibase will help keep the code base &amp; respective environment always up to date with the latest schema changes, which makes it less error-prone during deployments.</li></ol><h4>How to implement Liquibase in Spring Boot?</h4><p>This section will guide how to add Liquibase dependencies to your “pom.xml” file, and how to configure it in your “applications.properties” file, with a few more important Liquibase commands.</p><p>Adding Liquibase dependency to the “pom.xml” file :</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.liquibase&lt;/groupId&gt;<br>    &lt;artifactId&gt;liquibase-core&lt;/artifactId&gt;<br>    &lt;version&gt;${liquibase.version}&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Once the above dependency has been added, it is necessary to include configuration within the plugins section.</p><pre>&lt;plugin&gt;<br>    &lt;groupId&gt;org.liquibase&lt;/groupId&gt;<br>    &lt;artifactId&gt;liquibase-maven-plugin&lt;/artifactId&gt;<br>    &lt;version&gt;${liquibase.version}&lt;/version&gt;<br>    &lt;configuration&gt;<br>        &lt;propertyFile&gt;/src/main/resources/application.properties&lt;/propertyFile&gt;<br>    &lt;/configuration&gt;<br>&lt;/plugin&gt;</pre><p>For “<strong>${liquibase.version}</strong>” always use the latest from the maven central repository.</p><p>Once the above dependencies are added successfully, the next step would be to add Liquibase configurations, add these configurations under the “application.properties” file :</p><pre>spring.liquibase.enabled=true<br>spring.liquibase.defaultSchema=public<br>spring.liquibase.change-log=classpath:db/changelog/changelog-master.xml</pre><p><strong>spring.liquibase.change-log </strong>points to a key file that will have all the required SQL scripts file details which are part of the migration process. Create a folder under classpath/resources/db/changelog to hold all DB migrations-related files.</p><p>We need to add Liquibase plugin configurations under the “<strong>application.properties”</strong> file to apply changes against the connected database.</p><pre>#mvn-liquibase<br>changeLogFile=src/main/resources/db/changelog/changelog-master.xml<br>url=jdbc:postgresql://{url}<br>username=<br>password=<br>driver=CONNECTED_DB_DRIVER_URL</pre><p>Let’s configure the changelog-master file :</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br><br>&lt;databaseChangeLog<br>        xmlns=&quot;http://www.liquibase.org/xml/ns/dbchangelog/1.9&quot;<br>        xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>        xsi:schemaLocation=&quot;http://www.liquibase.org/xml/ns/dbchangelog/1.9<br>        http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-1.9.xsd&quot;&gt;<br>    &lt;!-- We add a new feature to the application that requires a database change, we can create a new changelog file,<br>         add it to version control, and include it in the master changelog--&gt;<br>    &lt;include file=&quot;&quot;/&gt;<br>&lt;/databaseChangeLog&gt;</pre><p><strong>&lt;include file=”/&gt;</strong> tag is held responsible for adding a new entry in the “<strong>changelog-master.xml</strong>” file to hold newly added SQL scripts under the application, for every new DB schema change, there will be a new SQL file will be created with the below-given syntax. Which will have all the required DB schema changes in it.</p><p>Then a new &lt;include&gt; tag entry should be added under the above “<strong>changelog-master.xml</strong>” file to pick up &amp; execute the newly added schema changes before the application starts.</p><p>The below content shows the basic syntax of adding schema changes “schema_table.sql” file :</p><pre>--liquibase formatted sql<br>--changeset smithj:create_sample_table<br>--preconditions onFail:MARK_RAN, onError:MARK_RAN<br>--precondition-sql-check expectedResult:0 SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = &#39;public&#39; AND table_name =&#39;sample_table&#39;<br><br>CREATE TABLE sample_table (<br>    a_column VARCHAR(255)<br>);<br><br>--rollback drop table sample_table</pre><p>In the sample above, we have defined a changeset with a unique identifier of smithj:create_sample_table (author:id). We are using the precondition-sql-check attribute to ensure that the SQL script is executed only if the defined check passes. In the event of a failure, we have chosen to mark the changeset as already executed using the MARK_RAN flag. You can learn more about preconditions <a href="https://docs.liquibase.com/concepts/changelogs/preconditions.html?Highlight=preconditions">here</a>.</p><p>It is important to include the line --liquibase formatted sql at the beginning of the changelog file. This line helps Liquibase correctly parse the content of the file, including essential instructions like the changeset ID and preconditions. If this line is omitted, Liquibase may not detect the format of the file correctly, resulting in errors or unexpected behavior during execution.</p><p>Including --rollback statements are recommended to facilitate the reversal of changes if necessary.</p><p>This newly added file was then added under “changelog-master.xml” like below :</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br><br>&lt;databaseChangeLog<br>        xmlns=&quot;http://www.liquibase.org/xml/ns/dbchangelog/1.9&quot;<br>        xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>        xsi:schemaLocation=&quot;http://www.liquibase.org/xml/ns/dbchangelog/1.9<br>        http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-1.9.xsd&quot;&gt;<br>    &lt;!-- We add a new feature to the application that requires a database change, we can create a new changelog file,<br>         add it to version control, and include it in the master changelog--&gt;<br>    &lt;include file=&quot;db/changelog/changes/schema_table.sql&quot;/&gt;<br>&lt;/databaseChangeLog&gt;</pre><p>Once all the above-mentioned steps were added to the code base, When the application starts up “schema_table.sql” script will get executed first, and then after successful schema updation application boot up is initiated.</p><p><strong>Note: </strong>Always make sure not to update an already executed “.sql” file, as there is an entry created whenever a new “.sql” file is being executed under the “<strong>databasechangelog</strong>” table with checksum associated with it. If an already executed file is altered then a checksum error will be thrown at the application boot time.</p><p>If any changes need to be done to the already executed file first remove the “<strong>databasechangelog</strong>” table entry by running the below rollback command.</p><pre>mvn liquibase:rollback &#39;-Dliquibase.rollbackCount=COUNT_NUMBER&#39;</pre><p><strong>COUNT_NUMBER </strong>is the number of previously executed SQL scripts that you want to roll back with. In the above case, we have only one “.sql” file present, so if it needs to be removed from the “<strong>databasechangelog</strong>” table, <strong>COUNT_NUMBER </strong>will be “1”.</p><p><strong>Note: </strong>Editing the already executed “.sql” file is not a best practice. If any changes need to be performed to the already executed file either rollback the changes and create a new “.sql” file or keep the existing one and create an altogether new “.sql” file for updating the changes.</p><h4>Pros &amp; Cons of using Liquibase</h4><h4>Pros :</h4><ol><li>Liquibase helps in keeping track of all the DB changes that occur to the application with the help of a special table called “<strong>databasechangelog</strong>”.</li><li>Easy Rollback.</li><li>Database <a href="https://docs.liquibase.com/commands/change-tracking/history.html">history</a> documentation can be generated using Liquibase.</li></ol><p><strong>Cons :</strong></p><ol><li>One of the biggest cons of using Liquibase is that if any change needs to be done for the already executed “.sql” file not straightforward. Since there is a database entry (checksum) for a newly executed “.sql” file under “<strong>databasechangelog</strong>” table, whenever an already executed file gets updated. Due to the updation, the checksum associated with that file gets updated which leads to a checksum error while booting up the service.</li></ol><h4><strong>Conclusion</strong></h4><p>Having a feature to cumulatively address DB schema change makes an application more de-coupled with the added advantage of easy lift &amp; shift of application for different various systems/environments. Implementation of Liquibase in any application will increase easy development, evolve, and ship the application which is less effort.</p><p>This documentation will demonstrate the real-world implementation of Liquibase using the Spring Boot application.</p><h4><strong>References</strong></h4><ol><li><a href="https://www.liquibase.com/">https://www.liquibase.com/</a></li><li><a href="https://docs.liquibase.com/commands/change-tracking/history.html">https://docs.liquibase.com/commands/change-tracking/history.html</a></li><li><a href="https://gitlab.version1.com/shared/foundations/accelerators/cloud-migration-discovery-tool/accelerator-cloud-migration-discovery-api/-/blob/master/docs/schema-migration.md">https://gitlab.version1.com/shared/foundations/accelerators/cloud-migration-discovery-tool/accelerator-cloud-migration-discovery-api/-/blob/master/docs/schema-migration.md</a></li></ol><p><strong>About the Author:<br></strong>Pradeep Maiya is a Java Developer at Version 1.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cecf0209118" width="1" height="1" alt=""><hr><p><a href="https://medium.com/version-1/db-migrations-using-liquibase-8cecf0209118">DB Migrations Using Liquibase</a> was originally published in <a href="https://medium.com/version-1">Version 1</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swagger 3.0 (OAS) With Spring Boot and Azure AD]]></title>
            <link>https://medium.com/version-1/swagger-3-0-oas-with-spring-boot-and-azure-ad-702a96d5d159?source=rss-907ae7805304------2</link>
            <guid isPermaLink="false">https://medium.com/p/702a96d5d159</guid>
            <category><![CDATA[openapi-specification]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[azure-ad]]></category>
            <category><![CDATA[swagger3]]></category>
            <dc:creator><![CDATA[Pradeep Maiya]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 14:08:22 GMT</pubDate>
            <atom:updated>2023-03-31T14:13:57.635Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*jMOvDYJMxTN4BycGoAPa_g.png" /><figcaption>Swagger 3.0 (OpenAPI Specification) + Spring Boot integration</figcaption></figure><blockquote>This blog will discuss how to configure Swagger UI to include a Token-based authorization when it calls our API.</blockquote><p>Points to be covered in this documentation:</p><ol><li><strong>Introduction</strong></li><li><strong>What is meant by Swagger documentation?</strong></li><li><strong>Advantages of using Swagger</strong></li><li><strong>How to achieve it in Spring Boot</strong></li><li><strong>Conclusion</strong></li></ol><h3><strong><em>Introduction</em></strong></h3><p>In the REST API world, whatever APIs are designed should be documented in a good format so that it would be helpful to quickly understand what this API is for and its use cases. Creating API documentation manually is a time-consuming and tedious process. Swagger provides an option to generate the API documentation automatically and it also ensures that any changes to the API are available to the customer immediately. In this document, we will learn to integrate Swagger with the Spring Boot application along with Azure AD security.</p><h3>What is meant by Swagger documentation?</h3><p>Swagger provides you with a platform to create more meaningful descriptions of your APIs, an easy-to-use suite of API development tools for developers, enabling development across the entire API life cycle, which includes design, documentation, testing, and deployment. It provides data in JSON format and a UI using the Swagger-UI. In this post, we will use Springfox.</p><p>Springfox is a Java library that is used to generate API specifications for Spring Boot projects. It will examine an application once at runtime to fetch API semantics based on Spring annotations that were used in the project class structure.</p><h3>Advantages of using Swagger</h3><p>Adding Swagger documentation will provide lots of advantages as well, these are a few:</p><ol><li>Swagger allows us to generate REST API documentation and provides a platform to interact with those listed APIs as well.</li><li>Swagger is not language specific, meaning it can be across languages like Java, .Net, HTML5, etc.</li><li>This will act as a contract document that can be used to fasten the software development process.</li><li>Since Swagger UI provides Interface for documenting &amp; testing API endpoints, this will be an added advantage for using Swagger documentation.</li></ol><h3>How to achieve it in Spring Boot</h3><p>The initial step will help you to configure the Azure AD Authentication mechanism to your Spring Boot application. If you haven’t configured it already, here is <a href="https://medium.com/version-1/azure-ad-integration-in-spring-boot-application-81d66ffd4739">documentation</a> that will provide you with the detailed steps for achieving the same.</p><p>Once you configured Azure AD with your project as shown in the above documentation, following the below steps will explain how to set up a configuration class for Swagger and to make sure all the API endpoints present in the project are secured, whenever anyone tries to hit API endpoints through swagger.</p><p>Assuming you are done with Azure AD integration of your project, now let us look at how to access secured/Authenticated API endpoints from Swagger UI and integration of Swagger UI with your project/solution.</p><p>Follow the below steps:</p><ol><li>Adding “springfox” dependency under pom.xml file:</li></ol><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;io.springfox&lt;/groupId&gt;<br>    &lt;artifactId&gt;springfox-boot-starter&lt;/artifactId&gt;<br>    &lt;version&gt;3.0.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Once the above dependency has been added under “pom.xml”, then it’s time to configure our Swagger Configuration class.</p><p>2. Create a new class called “SwaggerConfig” under the “Configuration” package present in your “src” package. File contents are as shown below:</p><pre>@Configuration<br>@EnableSwagger2<br>public class SwaggerConfig implements  WebMvcConfigurer{<br><br>  public static final String AUTHORIZATION_HEADER = &quot;Authorization&quot;;<br><br>  private ApiInfo apiInfo() {<br>    return new ApiInfoBuilder()<br>               .title(&quot;PROJECT_NAME&quot;)<br>               .version(&quot;1.0.0&quot;)<br>               .description(&quot;THIS_WILL_PROVIDE_BRIEF_DESCRIPTION_ABOUT_YOUR_PROJECT.&quot;)<br>               .termsOfServiceUrl(&quot;https://PROJECT_TERMS_AND_CONDITION_PAGE/&quot;)<br>               .build();<br>  }<br><br>  @Bean<br>  public Docket api() {<br>    return new Docket(DocumentationType.OAS_30)<br>               .useDefaultResponseMessages(false)<br>               .securityContexts(Arrays.asList(securityContext()))<br>               .securitySchemes(Arrays.asList(apiKey()))<br>               .apiInfo(apiInfo())<br>               .select()<br>               .apis(RequestHandlerSelectors.any())<br>               .paths(PathSelectors.any())<br>                .build();<br>    <br>  }<br><br>  private ApiKey apiKey() {<br>    return new ApiKey(AUTHORIZATION_HEADER, &quot;JWT&quot;, &quot;header&quot;);<br>  }<br><br>  private SecurityContext securityContext() {<br>    return SecurityContext.builder().securityReferences(defaultAuth()).build();<br>  }<br><br>  List&lt;SecurityReference&gt; defaultAuth() {<br>    AuthorizationScope authorizationScope = new AuthorizationScope(&quot;global&quot;, &quot;accessEverything&quot;);<br>    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];<br>    authorizationScopes[0] = authorizationScope;<br>    return Arrays.asList(new SecurityReference(AUTHORIZATION_HEADER, authorizationScopes));<br>  }<br><br>  @Override<br>  public void addResourceHandlers( ResourceHandlerRegistry registry ) {<br>     registry.addResourceHandler( &quot;/swagger-ui/**&quot; ).addResourceLocations( &quot;classpath:/META-INF/resources/swagger-ui.html&quot; );<br>     registry.addResourceHandler( &quot;/webjars/**&quot; ).addResourceLocations( &quot;classpath:/META-INF/resources/webjars/&quot; );<br>  }<br><br>  @Bean<br>  public InternalResourceViewResolver defaultViewResolver() {<br>     return new InternalResourceViewResolver();<br>  }<br><br></pre><p>Now let’s analyse the above code added:</p><blockquote>1.<strong> @EnableSwagger2</strong> annotation enables swagger 2 in our project.</blockquote><blockquote>2. Method<strong> apiInfo() </strong>is to add brief information about the project, which will be shown on Swagger documentation.</blockquote><blockquote>3. Method <strong>api()</strong> is used to add security context, project information written in <strong>apiInfo()</strong>, <strong>PathSelectors.any()</strong> ensure that all the API documentation is available.</blockquote><blockquote>4. Method <strong>apiKey()</strong> is to include a Token generated as a successful Azure AD authentication as an authorization header.</blockquote><blockquote>5. Method <strong>securityContext() </strong>is to configure &amp; build Token SecurityContext with a global levelAuthorizationScope.</blockquote><blockquote>6. Method <strong>defaultAuth() </strong>is to set to setup AuthoizationScopes which were used in <strong>securityContext() </strong>for building the context.</blockquote><blockquote>7. Once we have all the above methods in place, we need to make sure to overwrite the existing resource handler to make sure Swagger URLs are added properly under META-INF/resources/ folder, and logic has been implemented under the <strong>addResourceHandlers() </strong>method<strong>.</strong></blockquote><p>Once we successfully added SwaggerConfiguration class as discussed above, one last thing that we need to make sure to add is to allow in security level.</p><p>3. Allow Security Level for Swagger APIs</p><p>Now we need to extend WebSecurityConfigurerAdapter which defines rules to specify what URIs to protect or pass through. This provides us with a configuration method. Add the below method in your “SecurityConfig” class where we configure Azure AD security for the project.</p><pre>@Override<br>public void configure(WebSecurity web) throws Exception {<br>    web.ignoring().antMatchers(&quot;/authenticate&quot;,<br>            &quot;/swagger-resources/**&quot;,<br>            &quot;/swagger-ui/**&quot;,<br>            &quot;/v3/api-docs&quot;,<br>            &quot;/webjars/**&quot;);<br>}</pre><p>That’s pretty much it for adding Swagger 3.0 to your application. Run your application and navigate to <a href="http://localhost:8080/swagger-ui/#"><em>http://localhost:8080/swagger-ui/#</em></a><em> </em>in the browser. Swagger UI will be seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*TdqQrsCmf7igTDaPxuHeqw.png" /><figcaption>Home page of Swagger documentation</figcaption></figure><p>Now when you click on the Authorize button, Swagger UI will ask for the Token. Then we need to input our token along with the “Bearer” string and click on Authorize, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*ii7X_08Wi040p91TnPav5g.png" /><figcaption>Authorize section where we need to add Token generated from successful ADlogin</figcaption></figure><p>This above step makes sure all the requests made to our API will automatically contain the token in the HTTP headers.</p><p>4. API Request through Swagger using Token:</p><p>Below is an example of a successful response(HTTP Status code- 200) from the authorized API endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*jdnLyuL8LxcNNVws_g92eg.png" /><figcaption>After successfully Authorizing in the above step, 200 responses for the API call</figcaption></figure><p>If the Token is not added/invalid under the “Authorize” section, you will get an unauthorized response with HTTP Status code- 401.</p><p>Below is an example of an unsuccessful API request with the response(HTTP Status code- 401) from API endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*-l2uDgp-zLaJoTAWhZGdkQ.png" /><figcaption>Unauthorized error for invalid/no token being added</figcaption></figure><h3><strong>Conclusion</strong></h3><p>In this document, we get to know how to set up Swagger 3.0 with Spring Boot along with Azure AD security in place, which can be helpful when dealing with our application authorization. After authorizing in Swagger UI, all the requests will automatically include our Token based Authorization.</p><h3><strong>About the author</strong></h3><p>Pradeep Maiya is a Java Developer at <a href="http://version1.com/">Version 1</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=702a96d5d159" width="1" height="1" alt=""><hr><p><a href="https://medium.com/version-1/swagger-3-0-oas-with-spring-boot-and-azure-ad-702a96d5d159">Swagger 3.0 (OAS) With Spring Boot and Azure AD</a> was originally published in <a href="https://medium.com/version-1">Version 1</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DB migrations in Spring boot]]></title>
            <link>https://medium.com/version-1/db-migrations-in-spring-boot-7d48e5e18738?source=rss-907ae7805304------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d48e5e18738</guid>
            <category><![CDATA[db-migration]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Pradeep Maiya]]></dc:creator>
            <pubDate>Fri, 20 Jan 2023 17:45:05 GMT</pubDate>
            <atom:updated>2023-01-20T17:45:05.662Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*vVGRN8MZ_QaeIRP2GwJeoQ.jpeg" /></figure><blockquote>In this document, let&#39;s discuss one of the ways to achieve DB migrations in Spring Boot. Follow the below pointers for implementation :</blockquote><p>· <strong>What is meant by DB migration</strong></p><p>· <strong>Use cases for DB migration</strong></p><p>. <strong>What is FlyWay?</strong></p><p>· <strong>How to Achieve it in Spring boot</strong></p><p>· <strong>Conclusion</strong></p><h3>What is meant by DB migration<strong>?</strong></h3><p>If the Application running in the PROD environment requires a data model update, it asks for data type changes at the schema level. Due to the default behaviour of hibernate &amp; Spring data, the JPA update will include truncation of existing data, where it will erase all the existing data present in the PROD environment (if any). This will cause severe data loss in the PROD environment.</p><p>We need to make sure we have a lift &amp; shift of schema changes to PROD without having any data loss. To achieve this we have good support as a form of DB migrations, which included the first schema change to get executed before running the application. This will make sure of running of “.sql” files before the application start which will basically run all the SQL commands present in the “.sql” file. This won’t include a data loss in a table as it will directly deal with SQL commands but not Spring JPA update of schema.</p><h3><strong>Use cases for DB migration</strong></h3><p>As explained in the above section there might be scenarios where we need to update the existing DB schema without losing any data, The only way to do that was by running SQL commands in the DB client. This section will explain to you how to achieve that, meaning how to make sure a smooth DB changes migration by running SQL commands in a spring boot application.</p><p>We have several solutions to achieve that in Spring boot: Flyway &amp; Liquibase libraries. This section will address one of those solutions which are using Flyway.</p><h3><strong>What is Flyway?</strong></h3><p>Flyway is a java library that will provide a way to migrate all schema changes by running SQL scripts as part of the Spring boot application. Flyway can be executed as part of the command line, as part of the application build process, etc.</p><h4><strong>Why we are adding Flyway</strong></h4><p>We have a couple of options to support DB migrations, Flyway and Liquibase. Why Flyway because both Flyway and Liquibase support the same functionalities but Flyway is very strict regarding migration file changes. Considering every new change in schema we have to create new versions of the .sql file because the older version already has its entry in the Flyway table.</p><p>Flyway also has paid subscription for supporting multiple updating of the same .sql file. This is one of the USPs for using Flyway as it provides more features.</p><h3><strong>How to Achieve it in Spring boot</strong></h3><p>1. Add Flyway dependency to the pom.xml file.</p><pre>&lt;dependency&gt;<br><br>  &lt;groupId&gt;org.flywaydb&lt;/groupId&gt;<br><br>  &lt;artifactId&gt;flyway-core&lt;/artifactId&gt;<br><br>&lt;/dependency&gt;</pre><p>2. Make sure to create a folder under <em>“PROJECT_FOLDER/src/resources/db/migration/YOUR_DATABASE_NAME”.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*hqqA24kskPYgBdC0w2E3BA.png" /><figcaption>Filepath and Filename example</figcaption></figure><p><em>“</em><strong><em>YOUR_DATABASE_NAME</em></strong><em>”</em> is the name of the database client which you are using in your application.</p><p>Here we are using “postgresql” so this will be my URL <em>“PROJECT_FOLDER/src/resources /db/migration/ postgresql”.</em></p><p>3. Add the below properties under “application.properties” file.</p><pre>spring.jpa.hibernate.ddl-auto=none<br><br>#Flyway properties<br>spring.flyway.enabled=true<br>spring.flyway.url=YOUR_DB_URL<br>spring.flyway.password= YOUR_DB_PASSWORD<br>spring.flyway.user= YOUR_DB_USERNAME<br>spring.flyway.schemas=migrations<br>spring.flyway.locations=classpath:db/migration/postgresql</pre><p>4. Next step is to create a SQL script that holds all the SQL commands which are required for DB migrations.</p><p>Create a new .sql file under above mentioned folder which is under <em>“../db/migrations/postgresql/”</em>, this file should contain a specific naming format that will be acceptable by Flyway. <br> <br>Syntax: <strong>V&lt;VERSION&gt;__&lt;NAME&gt;.sql</strong></p><p>“V__&lt;VERSION&gt;”: will be a specific version of migration meaning V1, V2, V3… etc. <br>“&lt;NAME&gt;”: will specify what migration does this specific SQL file contains.</p><h4>Note:</h4><p>1. we haven’t added a version. Since Spring boot will automatically download the version based on the Spring boot version present in the current application.</p><p>2. Make sure always you create a new migration SQL file as flyway keeps a DB entry for each new migration (.sql files created before) if we update the already existing migration SQL file changes will not occur.</p><p>3. Make sure you have double underscores present after the version of a file, i.e “V1__FILENAME.sql”, if you provide a single underscore after the version file is skipped when starting the application by Flyway, i.e “V1_FILENAME.sql”.</p><p>4. We can have N number of SQL commands differentiated by semicolon present in a single .sql file, but once we execute an application, Flyway will make an entry of file based on the version in DB. If you need to run a different set of SQL commands in the next run we have to create a new file with an “updated” version under the above folder only then we will be able to run a new set of SQL commands. We can’t update the existing file contents.</p><p>Example .sql file: <strong>“V1__first_migration_script.sql”</strong></p><p>That’s it we have now configured Flyway for creating new DB migrations. Once you have completed all the processes mentioned above and created a .sql file, push the changes and start an application to check all the updated DB schema present in the newer environment.</p><h3><strong>Conclusion</strong></h3><p>Version-based database migration is the recommended approach to implement reliable and reproducible database updates. Flyway is one the most popular libraries in the market that helps to make the DB migration process much simpler. You only need to define the update operations and integrate one of the libraries into your application.</p><p>Spring Boot then provides a default configuration and triggers the migration. If you want to use a different configuration, you can add your configuration parameters to the application.properties file.</p><p><strong>Sources &amp; for more information:</strong></p><p><a href="https://thorben-janssen.com/flyway-getting-started">https://thorben-janssen.com/flyway-getting-started</a></p><p><a href="https://www.baeldung.com/database-migrations-with-flyway">https://www.baeldung.com/database-migrations-with-flyway</a></p><p><a href="https://www.tutorialspoint.com/spring_boot/spring_boot_flyway_database.htm">https://www.tutorialspoint.com/spring_boot/spring_boot_flyway_database.htm</a></p><p><strong>About the author:</strong><br>Pradeep Maiya is a Junior Java Developer here at Version 1.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d48e5e18738" width="1" height="1" alt=""><hr><p><a href="https://medium.com/version-1/db-migrations-in-spring-boot-7d48e5e18738">DB migrations in Spring boot</a> was originally published in <a href="https://medium.com/version-1">Version 1</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure AD Integration in Spring Boot Application]]></title>
            <link>https://medium.com/version-1/azure-ad-integration-in-spring-boot-application-81d66ffd4739?source=rss-907ae7805304------2</link>
            <guid isPermaLink="false">https://medium.com/p/81d66ffd4739</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[identity]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[azure-ad]]></category>
            <dc:creator><![CDATA[Pradeep Maiya]]></dc:creator>
            <pubDate>Tue, 07 Jun 2022 11:20:27 GMT</pubDate>
            <atom:updated>2022-06-07T11:20:27.604Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VBkB9YsZg_0kpxrN_7mnbg.jpeg" /></figure><blockquote>This document explains how to enable scope and role-based authorization using Azure Active Directory as Identity Provider/Authentication Server (IdP) whereas Spring boot will act as a resource server that will validate the access token generated by the IdP and passed by the client application (Angular UI).</blockquote><p><strong><em>Prerequisites needed before implementing this: </em><br></strong>1. Azure subscription<br>2. Java JDK 8 or higher version (installed locally)<br>3. Apache Maven 3 or higher (installed locally)<br>4. An application should be registered under Azure portal &gt; Azure Active Directory &gt; App registration (will be discussed later in the documentation)</p><h3><strong><em>What is Azure AD?</em></strong></h3><p>Azure Active Directory (Azure AD) is a cloud-based identity and access management service. This service helps your employees access external resources, such as Microsoft 365, the Azure portal, and thousands of other SaaS applications. Azure Active Directory also allows them to access internal resources like apps on your corporate intranet network and any cloud apps developed for your own organization.</p><p>With the help of Azure AD, this article will discuss how to secure a Spring Boot Application with the use of scope-based authentication. This will use Azure AD as an authentication server &amp; Spring Boot Application acts as a resource server. Spring boot will validate the token received from the client application which is the Angular APP.</p><h4><strong><em>How does authorization code flow work?</em></strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*Ag4qtYzTHFTePfsJ3JGXJQ.png" /><figcaption>Token flow happens when a user logs into the system.</figcaption></figure><p><strong>User-Agent</strong>: Is the end-user who accesses the application</p><p><strong>Client Application: </strong>An application that uses tokens from the authorization server to access the resource server on behalf of the resource owner. It orchestrates the process of obtaining and renewing these tokens</p><p><strong>Authorization Server: </strong>The server which validates your credentials. Generates tokens to registered clients, in our case it’s Azure AD</p><p><strong>Resource Server: </strong>It’s a server where our APIs reside, in our case, it’s a Spring Boot Application</p><p><em>The resource server will be having four main components:</em></p><ol><li><strong>API</strong> — a REST controller to expose the resource</li><li><strong>Security Configuration</strong> — a class to define access control for the protected resource that the API exposes</li><li><strong>application.properties</strong> — a config file to declare properties, including information about the authorization server</li><li><strong>pom.xml — </strong>all dependencies which are required to associate Java Spring boot application as a resource server</li></ol><h4><strong><em>How to set up an Authorization Server?</em></strong></h4><p>To set up an Azure AD tenant we need to have one Azure subscription in place. If you already have a tenant, then follow the following steps to configure the App registration:</p><ol><li>Navigate to the search bar in the Azure portal and search for “Azure Active Directory”</li><li>Click on “App registrations” and click on the “New registration” option on the top</li><li>Provide a unique name for the registration that defines what does your application does and click on the “Register” button</li><li>Now let’s add different scopes required for accessing APIs Initially, click on the “Set” button to set “Application ID” which will be the base URL used in Scopes. Then click on the “Add a scope” button to add new scope &gt; provide “Scope name” (which will be used in the backend to access scope), add consents as “Admins &amp; users”, provide “Admin consent display name” and “Admin consent description” details and click on “Add scope”</li><li>That’s it, this is pretty much everything that you need to configure the resource server, which will validate the access token generated by a client application (angular application) with the help of the Authorization server (Azure active directory)</li></ol><h4><strong><em>How to set up a Resource Server?</em></strong></h4><p>The role of the Resource server is to validate the token generated after a successful login in the Client Application. It also provides scope/role-based authorized access to the APIs which are hosted on the server.</p><p>Dependencies to be added in the pom.xml file</p><pre>&lt;dependency&gt;</pre><pre>&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</pre><pre>&lt;artifactId&gt;spring-boot-starter-oauth2-resource-server&lt;/artifactId&gt;</pre><pre>&lt;version&gt;4.0.0&lt;/version&gt;</pre><pre>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;</pre><pre>&lt;groupId&gt;com.azure.spring&lt;/groupId&gt;</pre><pre>&lt;artifactId&gt;azure-spring-boot-starter-active-directory&lt;/artifactId&gt;</pre><pre>&lt;version&gt;3.14.0&lt;/version&gt;</pre><pre>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;</pre><pre>&lt;groupId&gt;com.azure.spring&lt;/groupId&gt;</pre><pre>&lt;artifactId&gt;spring-cloud-azure-starter-active-directory&lt;/artifactId&gt;</pre><pre> &lt;version&gt;4.0.0&lt;/version&gt;</pre><pre>&lt;/dependency&gt;</pre><p>Once we add the above dependency, let&#39;s create a new configuration class that will specify the security configuration for the API to secure endpoints.</p><p>The <strong>AADResourceServerWebSecurityConfigurerAdapter</strong> base class contains the necessary web security configuration for the resource server.</p><p>The <strong>DefaultAADResourceServerWebSecurityConfigurerAdapter</strong> class is configured automatically if you don’t provide a configuration. <br>To provide a configuration, extend the <strong>AADResourceServerWebSecurityConfigurerAdapter</strong> class and call <strong>super.configure(http)</strong> in the <strong>configure(HttpSecurity http)</strong> function.</p><pre>import com.azure.spring.aad.webapi.AADResourceServerWebSecurityConfigurerAdapter;<br>import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;<br>import org.springframework.security.config.annotation.web.builders.HttpSecurity;<br>import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;</pre><pre>@EnableWebSecurity<br>@EnableGlobalMethodSecurity(prePostEnabled = true)<br>public class SecurityConfig extends AADResourceServerWebSecurityConfigurerAdapter {</pre><pre>@Override<br>protected void configure(HttpSecurity http) throws Exception {<br>super.configure(http);<br>http.authorizeRequests((requests) -&gt; requests.anyRequest().authenticated());<br>}<br>}</pre><p>The above <strong>security config.</strong>class requires that any calls made to the API endpoints in the Spring Boot Application have to be authenticated.</p><p>Scopes are typically used when an external application wants to gain access to the user’s data via an exposed API. They determine what the client application can do. Since APIs are secured under particular scopes, only users with these particular scopes can access those respective APIs.</p><p>To secure APIs using a scope, add the below the line on top of every controller method signature.</p><pre>@PreAuthorize(&quot;hasAuthority(&#39;SCOPE_{SCOPE_NAME}&#39;)&quot;)</pre><pre>Public String METHOD_NAME(){</pre><pre>--------------------------------</pre><pre>--------------------------------</pre><pre>}</pre><p>{SCOPE_NAME} &gt;&gt; replace this with the actual scope name which is created under “Expose an API” under “App registration”.</p><p>Roles are typically used when an external application needs to make calls to an API without a user present, in these cases the applications are assigned roles to define which endpoints of the API the particular application has access to.</p><p>To secure APIs using a role, add the below line on top of every controller method signature.</p><pre>@PreAuthorize(&quot;hasAuthority(APPROLE_{ROLE_NAME}&#39;)&quot;)</pre><pre>Public String METHOD_NAME(){</pre><pre>--------------------------------</pre><pre>--------------------------------</pre><pre>}</pre><p>{ROLE_NAME} &gt;&gt; replace this with the actual scope name which is created under “Expose an API” under “App registration”.</p><p>One last thing we need to add is properties that will say which App registration our app is associated with, meaning we need to add “client-id” and “scope” details in the <strong>application.properties</strong> file. This is used to associate the current Spring Boot Application with that <strong>App registration</strong>.</p><pre>spring.cloud.azure.active-directory.enabled=true</pre><pre>spring.cloud.azure.active-directory.credential.client-id=CLIENT_ID</pre><pre>spring.cloud.azure.active-directory.app-id-uri=APPLICATION_ID_URL</pre><p>Where “CLIENT_ID” is the “Application (client) ID” present under the “Overview” section in App registration, “APPLICATION_ID_URL” is the “Application ID URI” present under the “Expose an API” section under App registration.</p><p>That’s it, those are the required steps to be performed to make Spring Boot Application a resource server. The Azure active directory will act as an Authorization server which will be held responsible for providing access tokens for requests made from the angular client application.</p><h4><strong><em>How to Test?</em></strong></h4><p>To test this, we will be using the Postman application, which will be responsible for getting access by making an API call to get tokens from the Authorization Server.</p><p>For testing authorization from Postman need to set up these under “App registration”:</p><ol><li>Navigate to the newly created App registration and select “Certificates &amp; secrets” to generate a new client secret for the App registration, make sure you save the “Value” of the newly created “Certificates &amp; secrets” since it will be hidden</li><li>One last step is to add what will be the call-back URL once Authentication is successful, for that we need to add an Authentication URL under the “Authentication” section. Click on the “Add a platform” button and since our client application is Postman, select “Web” &gt; under “Redirect URIs” provide the Postman call back URL which is <a href="https://version1-my.sharepoint.com/personal/frank_lorespenalver_version1_com/Documents/%E2%80%9C">“</a>https://oauth.pstmn.io/v1/callback” and click “Configure” then click on “Save” to save the configuration</li><li>That’s it, now follow the below steps in order to test the Authorization flow using Postman as a client application</li></ol><p>Create a new folder under a collection in Postman for which will need to add auth details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*abK6vEGYf_mDOoIE9sgLHw.png" /><figcaption>create a new folder inside a collection</figcaption></figure><p>Once the folder is created, add Auth details as per the details which are present under “endpoints” in the “overview” section of “App registration”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*P226JR5roNz36jH16LFBaQ.png" /><figcaption>Under “Endpoint” where you will get all token URLs associated with App registration</figcaption></figure><p>Copy “OAuth 2.0 authorization endpoint (v2)” &amp; “OAuth 2.0 token endpoint (v2)” which were present under “endpoints” and add the exact auth details under a newly created folder in Postman.</p><p><strong><em>Note: </em></strong>To make Postman a client application, add <a href="https://oauth.pstmn.io/v1/callback">https://oauth.pstmn.io/v1/callback</a> URL under “Authentication” as a Web URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0AYyJHnG0VUlxWHbHXkvJA.png" /><figcaption>Adding of postman URL as a client in App registration</figcaption></figure><p>Then in postman under “Configure New Token” add the below details</p><ol><li>Grant Type: Authorization code (with PKCE)</li><li>Auth URL: “OAuth 2.0 authorization endpoint (v2)”</li><li>Access Token URL: “OAuth 2.0 token endpoint (v2)”</li><li>Client ID: copy “Application (client) ID” under “overview” in “App registration”</li><li>Client Secret: The “Value” which is present under “client secrets” in the “Certificates &amp; secrets” section</li><li>Scope: add the scope which is created earlier under “App registration”</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nE7clWLYYKdxMIMHEh4UdA.png" /><figcaption>After adding all the above details to the postman</figcaption></figure><p>Once all these details are created, click on the save and click on the “Get New Access Token” button this will open a new window in the browser and once user credentials are validated then it will navigate back to Postman, where you will get a new token. Click on “Proceed” to Get Access Token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*7L5UOc3gTDWPOWk8FEJ19w.png" /><figcaption>On successful authentication from the Postman</figcaption></figure><h4><strong><em>Conclusion</em></strong></h4><p>That’s it, these are the steps which need to be performed in order to secure a Spring Boot Application using the Azure active directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6PntD3DmJjpkzInfmaN-eg.jpeg" /></figure><p><strong>About the Author: <br></strong>Pradeep Maiya is a Junior Java Developer here at Version 1.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81d66ffd4739" width="1" height="1" alt=""><hr><p><a href="https://medium.com/version-1/azure-ad-integration-in-spring-boot-application-81d66ffd4739">Azure AD Integration in Spring Boot Application</a> was originally published in <a href="https://medium.com/version-1">Version 1</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>