<?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"><channel><title><![CDATA[Himanshu Pareek]]></title><description><![CDATA[I graduated from IIT Kharagpur and working as Software Engineer. I love to solve problems and to share the knowledge.]]></description><link>https://blog.javarush.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 07 Nov 2026 07:05:23 GMT</lastBuildDate><atom:link href="https://blog.javarush.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Creating Docker Image of Spring Boot Application using Buildpacks]]></title><description><![CDATA[Learn how to build Docker images for Spring Boot applications using basic Dockerfiles, layered jars, and Cloud Native Buildpacks]]></description><link>https://blog.javarush.dev/creating-docker-image-of-spring-boot-application-using-buildpacks</link><guid isPermaLink="true">https://blog.javarush.dev/creating-docker-image-of-spring-boot-application-using-buildpacks</guid><category><![CDATA[Docker]]></category><category><![CDATA[Spring]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[buildpacks]]></category><category><![CDATA[gradle]]></category><category><![CDATA[maven]]></category><category><![CDATA[spring-boot]]></category><dc:creator><![CDATA[Himanshu Pareek]]></dc:creator><pubDate>Sun, 08 Sep 2024 10:37:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/jQ6bMceL4Gw/upload/55c6119f79017703ca332a9da9170308.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>You have created a <a target="_blank" href="https://spring.io/projects/spring-boot">Spring Boot</a> application. It is working great on your local machine and now, you need to deploy the application somewhere else. On some platforms, you can directly submit the <code>jar</code> file and it will be deployed. At some places, you can spin up a virtual machine, download the source code there, build it, and run it. But, most of the time you will need to deploy the application using containers. Most of the time, <a target="_blank" href="https://www.docker.com/">Docker</a> is used to build and run the image in a container. Also, when you upload the <code>jar</code> file to some platforms, the application is run inside a container under the hood.</p>
<p>So, in this blog, we will see <code>3</code> different ways to build a Docker image for the given Spring Boot application. Let's start:</p>
<h1 id="heading-basic-container-image">Basic Container Image</h1>
<p>The naive and insufficient way to build the Docker image for any application is to use a simple <a target="_blank" href="https://docs.docker.com/get-started/docker-concepts/building-images/writing-a-dockerfile/">Dockerfile</a> which copies the <code>jar</code> file inside the image and run it using <code>java -jar</code> command.</p>
<h2 id="heading-create-dockerfile">Create Dockerfile</h2>
<p>Here is the <code>Dockerfile</code> which you can put at the root of the project:</p>
<pre><code class="lang-Dockerfile"><span class="hljs-keyword">FROM</span> eclipse-temurin:<span class="hljs-number">21</span>-jre-ubi9-minimal

<span class="hljs-keyword">ARG</span> JAR_FILE

<span class="hljs-keyword">COPY</span><span class="bash"> <span class="hljs-variable">${JAR_FILE}</span> application.jar</span>

<span class="hljs-keyword">ENTRYPOINT</span><span class="bash"> [<span class="hljs-string">"java"</span>, <span class="hljs-string">"-jar"</span>, <span class="hljs-string">"/application.jar"</span>]</span>
</code></pre>
<p>We have specified one argument <code>JAR_FILE</code> which is the location of the <code>jar</code> file to use.</p>
<h2 id="heading-building-docker-image">Building Docker Image</h2>
<p>After creating the above <code>Dockerfile</code>, below steps are used to create the Docker image:</p>
<ol>
<li><p>Build the <code>jar</code> file for Spring Boot project:</p>
<pre><code class="lang-bash"> ./gradlew bootJar <span class="hljs-comment"># For Gradle build system</span>
</code></pre>
<p> OR</p>
<pre><code class="lang-bash"> ./mvnw spring-boot:build-jar <span class="hljs-comment"># For Maven build system</span>
</code></pre>
</li>
<li><p>Use the <code>Dockerfile</code> to build the Docker image using the latest <code>jar</code> file. In the below command replace the <code>{IMAGE_NAME}</code> with the required image name and <code>{JAR_FILE}</code> with the path to the generated <code>jar</code> file. The image name contains a tag as well, like - <code>mycompany/product-service:0.0.1-SNAPSHOT</code>:</p>
<pre><code class="lang-bash"> docker build --build-arg JAR_FILE={JAR_FILE} --tag {IMAGE_NAME} .
</code></pre>
</li>
<li><p>Verify if the Docker image is built using the following command. You should be able to see the image with the name specified in the command above:</p>
<pre><code class="lang-bash"> docker images
</code></pre>
</li>
</ol>
<h1 id="heading-efficient-container-image-using-layered-jar">Efficient Container Image using Layered Jar</h1>
<p>While it is possible and easy to package a Spring Boot uber <code>jar</code> as a Docker image (as mentioned in the previous method), there are many downsides to copying and running the fat <code>jar</code> as-is in the Docker image. For instance,</p>
<ul>
<li><p>There is some extra overhead when running uber <code>jar</code> without unpacking it.</p>
</li>
<li><p>Putting the application's code and all of its dependencies in a single layer is not optimal.</p>
</li>
</ul>
<p>Since we compile our code more often than upgrading the Spring Boot version, it is better to separate things a bit more. If we put those <code>jar</code> files (which are rarely changed) in the layer before the application layer, then Docker often needs to change only the bottom layer and can pick the rest from its cache.</p>
<h2 id="heading-enable-layered-jar">Enable Layered Jar</h2>
<p>To create a layered Docker image, we need to create a <strong>layered jar</strong> first. Nowadays, it is enabled by default in Gradle and Maven. You can enable or disable the layered jar behavior using the following setting:</p>
<pre><code class="lang-java"><span class="hljs-comment">// build.gradle</span>
tasks.named(<span class="hljs-string">"bootJar"</span>) {
    layered {
        enabled = <span class="hljs-keyword">false</span>
    }
}
</code></pre>
<pre><code class="lang-kotlin"><span class="hljs-comment">// build.gradle.kts</span>
tasks.named&lt;BootJar&gt;(<span class="hljs-string">"bootJar"</span>) {
   layered {
      enabled.<span class="hljs-keyword">set</span>(<span class="hljs-literal">false</span>)
   }
}
</code></pre>
<pre><code class="lang-xml"><span class="hljs-comment">&lt;!-- pom.xml --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">project</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">build</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">plugins</span>&gt;</span>
         <span class="hljs-tag">&lt;<span class="hljs-name">plugin</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-maven-plugin<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">configuration</span>&gt;</span>
               <span class="hljs-tag">&lt;<span class="hljs-name">layers</span>&gt;</span>
                  <span class="hljs-tag">&lt;<span class="hljs-name">enabled</span>&gt;</span>true<span class="hljs-tag">&lt;/<span class="hljs-name">enabled</span>&gt;</span>
               <span class="hljs-tag">&lt;/<span class="hljs-name">layers</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">configuration</span>&gt;</span>
         <span class="hljs-tag">&lt;/<span class="hljs-name">plugin</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">plugins</span>&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">build</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">project</span>&gt;</span>
</code></pre>
<p>You can even tune how the layers are created. See the documentation for <a target="_blank" href="https://docs.spring.io/spring-boot/gradle-plugin/packaging.html#packaging-executable.configuring.layered-archives">gradle</a> or <a target="_blank" href="https://docs.spring.io/spring-boot/maven-plugin/packaging.html#packaging.layers">maven</a> configuration.</p>
<h2 id="heading-create-dockerfile-1">Create Dockerfile</h2>
<p>Below is the <code>Dockerfile</code> that can be used to take advantage of layered <code>jar</code> and to create layered Docker images of the Spring Boot application.</p>
<pre><code class="lang-Dockerfile"><span class="hljs-comment"># Perform the extraction in a separate builder container</span>
<span class="hljs-keyword">FROM</span> eclipse-temurin:<span class="hljs-number">21</span>-jre-ubi9-minimal AS builder

<span class="hljs-keyword">WORKDIR</span><span class="bash"> /builder</span>

<span class="hljs-comment"># This points to the built jar file in the target folder</span>
<span class="hljs-comment"># Adjust this to 'build/libs/*.jar' if you're using Gradle</span>
<span class="hljs-keyword">ARG</span> JAR_FILE=target/*.jar

<span class="hljs-comment"># Copy the jar file to the working directory and rename it to application.jar</span>
<span class="hljs-keyword">COPY</span><span class="bash"> <span class="hljs-variable">${JAR_FILE}</span> application.jar</span>

<span class="hljs-comment"># Extract the jar file using an efficient layout</span>
<span class="hljs-keyword">RUN</span><span class="bash"> java -Djarmode=tools -jar application.jar extract --layers --destination extracted</span>

<span class="hljs-comment"># This is the runtime container</span>
<span class="hljs-keyword">FROM</span> eclipse-temurin:<span class="hljs-number">21</span>-jre-ubi9-minimal

<span class="hljs-keyword">WORKDIR</span><span class="bash"> /application</span>

<span class="hljs-comment"># Copy the extracted jar contents from the builder container into the working directory in the runtime container</span>
<span class="hljs-comment"># Every copy step creates a new docker layer</span>
<span class="hljs-comment"># This allows docker to only pull the changes it really needs</span>
<span class="hljs-keyword">COPY</span><span class="bash"> --from=builder /builder/extracted/dependencies/ ./</span>
<span class="hljs-keyword">COPY</span><span class="bash"> --from=builder /builder/extracted/spring-boot-loader/ ./</span>
<span class="hljs-keyword">COPY</span><span class="bash"> --from=builder /builder/extracted/snapshot-dependencies/ ./</span>
<span class="hljs-keyword">COPY</span><span class="bash"> --from=builder /builder/extracted/application/ ./</span>

<span class="hljs-comment"># Start the application jar - this is not the uber jar used by the builder</span>
<span class="hljs-comment"># This jar only contains application code and references to the extracted jar files</span>
<span class="hljs-comment"># This layout is efficient to start up and CDS friendly</span>
<span class="hljs-keyword">ENTRYPOINT</span><span class="bash"> [<span class="hljs-string">"java"</span>, <span class="hljs-string">"-jar"</span>, <span class="hljs-string">"application.jar"</span>]</span>
</code></pre>
<h2 id="heading-building-docker-image-1">Building Docker Image</h2>
<p>The steps to build the layered Docker image are the same as building a basic Docker image. Please refer there.</p>
<h1 id="heading-cloud-native-buildpacks">Cloud Native Buildpacks</h1>
<p>What if I tell you that you can create a Docker image without creating <code>Dockerfile</code>?. We can build docker images directly from the Gralde or Maven plugin using <a target="_blank" href="https://buildpacks.io/">Cloud Native Buildpacks</a>. Some platforms (like <a target="_blank" href="https://www.heroku.com/">Heroku</a> or <a target="_blank" href="https://www.cloudfoundry.org/">Cloud Foundry</a>) use Buildpacks to convert provided <code>jar</code> files into runnable images.</p>
<p>Spring Boot includes buildpack support directly for Maven and Gradle. We don't need to include any additional plugins. Just run the below command:</p>
<pre><code class="lang-bash">./gradlew bootBuildImage <span class="hljs-comment"># For gradle build system</span>
</code></pre>
<p>OR</p>
<pre><code class="lang-bash">./mvnw spring-boot:build-image <span class="hljs-comment"># For maven build system</span>
</code></pre>
<p>The above command generates an image with the default name <code>{PROJECT_NAME}:${PROJECT_VERSION}</code>. If you want to configure the name of the generated image, you can follow the below steps:</p>
<h2 id="heading-configure-image-name-for-gradle-build-system">Configure image name for Gradle build system</h2>
<p>We can configure <code>bootBuildImage</code> task to set the name of the image, like this:</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">// For build.gradle.kts</span>
<span class="hljs-keyword">val</span> imagePrefix = <span class="hljs-string">"javarush"</span>
<span class="hljs-keyword">val</span> dockerImageName = <span class="hljs-string">"docker-example"</span>
tasks.named&lt;BootBuildImage&gt;(<span class="hljs-string">"bootBuildImage"</span>) {
   imageName.<span class="hljs-keyword">set</span>(<span class="hljs-string">"<span class="hljs-subst">${imagePrefix}</span>/<span class="hljs-subst">${dockerImageName}</span>:<span class="hljs-subst">${version}</span>"</span>)
}
</code></pre>
<pre><code class="lang-java"><span class="hljs-comment">// For build.gradle</span>
def imagePrefix = <span class="hljs-string">"javarush"</span>
def dockerImageName = <span class="hljs-string">"docker-example"</span>
tasks.named(<span class="hljs-string">"bootBuildImage"</span>) {
   imageName = <span class="hljs-string">"${imagePrefix}/${dockerImageName}:${version}"</span>
}
</code></pre>
<h2 id="heading-configure-image-name-for-maven-build-system">Configure image name for Maven build system</h2>
<p>We can configure <code>spring-boot-maven-plugin</code> to use another image name, like this:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">properties</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">imagePrefix</span>&gt;</span>javarush<span class="hljs-tag">&lt;/<span class="hljs-name">imagePrefix</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">properties</span>&gt;</span>

...

<span class="hljs-tag">&lt;<span class="hljs-name">project</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">build</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">plugins</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">plugin</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-maven-plugin<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">configuration</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">image</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">name</span>&gt;</span>${imagePrefix}/${project.artifactId}:${project.version}<span class="hljs-tag">&lt;/<span class="hljs-name">name</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">image</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">configuration</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">plugin</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">plugins</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">build</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">project</span>&gt;</span>
</code></pre>
<h2 id="heading-configure-the-image-name-while-running-the-command">Configure the image name while running the command</h2>
<p>We can even define the name of the image while running the command to build the image.</p>
<pre><code class="lang-bash">./gradlew bootBuildImage --imageName=javarush/docker-example:1.0.0 <span class="hljs-comment"># For grade build system</span>

./mvnw spring-boot:build-image -Dspring-boot.build-image.imageName=javarush/docker-example:1.0.0 <span class="hljs-comment"># For maven build system</span>
</code></pre>
<p>You can see the documentation to further configure the <a target="_blank" href="https://docs.spring.io/spring-boot/gradle-plugin/packaging-oci-image.html">Gradle</a> or <a target="_blank" href="https://docs.spring.io/spring-boot/maven-plugin/build-image.html#build-image">Maven</a> plugin. This is my go-to method to create a Docker image for any Spring Boot application.</p>
<h1 id="heading-running-docker-container">Running Docker Container</h1>
<p>Once you create a docker image, you need to make sure that it works as expected. After you make sure that the image is created, you can directly run it using the <code>docker run</code> command. For example,</p>
<pre><code class="lang-bash">docker run -p <span class="hljs-string">"8080:8080"</span> {IMAGE_NAME}
</code></pre>
<p>But, this is not how images are used in production applications. <a target="_blank" href="https://docs.docker.com/compose/">Docker Compose</a> is used to run and manage multiple docker images.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>In this blog, we have seen how to build Docker images for Spring Boot applications using different methods. Being able to build docker images for your apps is a must skill to know because the image is what gets delivered. Thanks for reading the article till the end. I appreciate it. I will meet you in the next one. As always, all feedback and suggestions are welcome.</p>
]]></content:encoded></item><item><title><![CDATA[Dependency Injection in Spring using different annotations]]></title><description><![CDATA[In this article, we will discuss some of the annotations which we can use to create, use or configure beans in the Spring framework.]]></description><link>https://blog.javarush.dev/dependency-injection-in-spring-using-different-annotations</link><guid isPermaLink="true">https://blog.javarush.dev/dependency-injection-in-spring-using-different-annotations</guid><category><![CDATA[Java]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[dependency injection]]></category><category><![CDATA[annotations]]></category><category><![CDATA[bean]]></category><dc:creator><![CDATA[Himanshu Pareek]]></dc:creator><pubDate>Thu, 25 May 2023 14:48:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1685025623071/def236d6-48a2-4e2c-a1c2-2b612a365c94.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the Spring Framework, beans are the fundamental building blocks used for dependency injection and inversion of control. You can work with beans in Spring using various annotations. Here are some commonly used annotations and their purposes:</p>
<h2 id="heading-component">@Component</h2>
<p>This annotation is used to mark a class as a Spring component. Spring will automatically detect and instantiate the beans marked with this annotation. For example:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> org.springframework.stereotype.Component;

<span class="hljs-meta">@Component</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FileService</span> </span>{
    <span class="hljs-comment">// ...</span>
}
</code></pre>
<h2 id="heading-autowired">@Autowired</h2>
<p>This annotation is used to automatically wire beans together by letting Spring resolve and inject the dependencies. It can be used on fields, constructors, or methods. For example:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> org.springframework.stereotype.Component;
<span class="hljs-keyword">import</span> org.springframework.beans.factory.annotation.Autowired;

<span class="hljs-meta">@Component</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ProductService</span> </span>{
    <span class="hljs-keyword">private</span> ProductDB db;
    <span class="hljs-keyword">private</span> SecondService secondService;

    <span class="hljs-comment">// Constructor injection</span>
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ProductService</span><span class="hljs-params">(ProductDB db)</span> </span>{
        <span class="hljs-keyword">this</span>.db = db;
    }

    <span class="hljs-comment">// Method injection</span>
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setSecondService</span><span class="hljs-params">(SecondService s)</span> </span>{
        <span class="hljs-keyword">this</span>.secondService = s;
    }

    <span class="hljs-comment">// Field injection</span>
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> ThirdService s3;
}
</code></pre>
<h2 id="heading-qualifier">@Qualifier</h2>
<p>When there are multiple beans of the same type, this annotation is used along with <code>@Autowired</code> to specify which bean should be injected. You can provide a unique name or identifier to differentiate between the beans. For example:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> org.springframework.stereotype.Component;
<span class="hljs-keyword">import</span> org.springframework.beans.factory.annotation.Qualifier;

<span class="hljs-meta">@Component</span>
<span class="hljs-meta">@Qualifier("gcpfs")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GCPFileService</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">FileService</span> </span>{
    <span class="hljs-comment">// ...</span>
}

<span class="hljs-meta">@Component</span>
<span class="hljs-meta">@Qualifier("awsfs")</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AWSFileService</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">FileService</span> </span>{
    <span class="hljs-comment">// ...</span>
}

<span class="hljs-meta">@Component</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ProductService</span> </span>{
    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-meta">@Qualifier("gcpfs")</span>
    <span class="hljs-keyword">private</span> FileService fileService;

    <span class="hljs-comment">// ...</span>
}
</code></pre>
<h2 id="heading-value">@Value</h2>
<p>This annotation injects values from properties files or environment variables into beans. It can be applied to fields, constructors, or methods. For example:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> org.springframework.stereotype.Component;
<span class="hljs-keyword">import</span> org.springframework.beans.factory.annotation.Value;

<span class="hljs-meta">@Component</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">StorageService</span> </span>{
    <span class="hljs-meta">@Value("${storage.url}")</span>
    <span class="hljs-keyword">private</span> String storageUrl;

    <span class="hljs-comment">// ...</span>
}
</code></pre>
<h2 id="heading-configuration">@Configuration</h2>
<p>This annotation is used to define a configuration class that provides bean definitions. It is often used in conjunction with <code>@Bean</code> annotations. For example:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> org.springframework.context.annotation.Configuration;

<span class="hljs-meta">@Configuration</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DbConfig</span> </span>{
    <span class="hljs-meta">@Bean</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Connection <span class="hljs-title">dbConnection</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> Driver.getConnection(....);
    }

    <span class="hljs-comment">// ...</span>
}
</code></pre>
<p>In addition to the annotations I mentioned earlier, Spring provides specific annotations for certain types of beans. Two commonly used annotations are <code>@Service</code> and <code>@Repository</code>.</p>
<h2 id="heading-service">@Service</h2>
<p>This annotation indicates that a class represents a service in the application's business layer. It typically encapsulates the business logic and performs operations on data received from the presentation layer. For example:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> org.springframework.stereotype.Service;

<span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ProductService</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addProduct</span><span class="hljs-params">(Product product)</span> </span>{
        <span class="hljs-comment">// ...</span>
    }

    <span class="hljs-comment">// ...</span>
}
</code></pre>
<h2 id="heading-repository">@Repository</h2>
<p>This annotation indicates that a class represents a repository or a data access object (DAO) in the persistence layer. It typically handles the storage and retrieval of data from the database or any other data source. For example:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> org.springframework.stereotype.Repository;

<span class="hljs-meta">@Repository</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">ProductRepository</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">JpaRepository</span>&lt;<span class="hljs-title">Product</span>, <span class="hljs-title">Integer</span>&gt; </span>{
    <span class="hljs-comment">// Methods for database operations</span>
}
</code></pre>
<p>These annotations provide additional semantic meaning to the beans in your application, making it easier to understand their purpose and role within the overall architecture. By using <code>@Service</code> and <code>@Repository</code>, you can better organize and categorize your beans based on their responsibilities. Note that both <code>@Service</code> and <code>@Repository</code> are specializations of the <code>@Component</code> annotation. This means they functionally work the same way as <code>@Component</code> but provide more specific context and intention in your codebase. They can be used interchangeably with <code>@Component</code>, but using the appropriate annotation enhances code readability and maintainability.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>These are just a few examples of annotations used in Spring Framework to work with beans. Spring provides many more annotations for different scenarios and use cases. It's important to understand the purpose and usage of each annotation to effectively work with beans in Spring. That's it for now. Thanks for your time. Please give suggestions, like and subscribe to my newsletter. Will meet in the next one.</p>
]]></content:encoded></item><item><title><![CDATA[Understand Recursion & Memoization]]></title><description><![CDATA[Let's understand recursion and memoization with a few examples.]]></description><link>https://blog.javarush.dev/understand-recursion-memoization</link><guid isPermaLink="true">https://blog.javarush.dev/understand-recursion-memoization</guid><category><![CDATA[Recursion]]></category><category><![CDATA[Factorial ]]></category><category><![CDATA[fibonacci]]></category><category><![CDATA[Pascal's Triangle]]></category><category><![CDATA[Memoization]]></category><dc:creator><![CDATA[Himanshu Pareek]]></dc:creator><pubDate>Sat, 20 May 2023 09:56:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/IW-1MgMUvtE/upload/35eff6c2d6c5bba69d0b31fa06d043e7.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Recursion</strong> is a technique to solve problems by</p>
<ol>
<li><p>dividing the original problem into one or more similar sub-problems,</p>
</li>
<li><p>solving the sub-problems by <strong>calling the same method again</strong>, and then</p>
</li>
<li><p>using the solutions of sub-problems to get the solution to the actual problem.</p>
</li>
</ol>
<p>Sometimes, recursion can be slow as we might end up solving the same problem multiple times. To avoid this, we use <strong>memoization</strong>. The concept is to solve the problem once and remember the solution to the problem. And in the future, if we encounter the same problem, we just return the solution, instead of solving it again.</p>
<h2 id="heading-when-to-use-recursion">When to use recursion?</h2>
<p>When you think the problem can be broken down into smaller sub-problems and their solution can be used to solve the actual problem, you can use recursion. And if using recursion is slow (in many cases), you can use memoization with recursion.</p>
<p>Although many problems which can be solved by recursion can be solved without recursion as well, using recursion is more readable and expressive.</p>
<h2 id="heading-how-to-use-recursion">How to use recursion?</h2>
<p>In programming, recursion basically means a function or method calling itself. In general, while calling itself the input to the function is changed, or it might end up calling itself infinite times and you will get the stack-overflow error.</p>
<p>Let's take some examples to understand it better.</p>
<h2 id="heading-factorial-n">Factorial (n!)</h2>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Factorial">Factorial</a> of a non-negative integer <code>n</code>, is the product of all positive integers less than or equal to <code>n</code>. That means,</p>
<p><code>fact(n) = 1 X 2 X ... X (n - 1) X n</code></p>
<p>Let's solve this problem using 2 techniques - iteration and recursion.</p>
<h3 id="heading-factorial-using-iteration">Factorial using iteration</h3>
<p>We can simply iterate from <code>1</code> to <code>n</code> and multiply each number to get the value of <code>fact(n)</code>.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">fact</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span> </span>{
    <span class="hljs-keyword">int</span> answer = <span class="hljs-number">1</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt;= n; i++) {
        answer = answer * i;
    }
    <span class="hljs-keyword">return</span> answer;
}
</code></pre>
<p>This works fine and is readable as well. Still, we can use recursion to calculate <code>fact(n)</code>. That will be more readable.</p>
<h3 id="heading-factorial-using-recursion">Factorial using recursion</h3>
<p>To calculate the value of <code>fact(n)</code> using recursion, we need to break this problem into smaller sub-problem. If we pay close attention, we see that:</p>
<pre><code class="lang-plaintext">fact(n) = n x (n - 1) x ... x 2 x 1
fact(n) = n x fact(n - 1)
</code></pre>
<p>Here, we break down the problem of calculating the factorial of n into calculating the factorial of n - 1, which is a subproblem of the original problem. So, we can use recursion to solve this problem. Let's look at the code:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">fact</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span> </span>{
    <span class="hljs-keyword">return</span> n * fact(n - <span class="hljs-number">1</span>);
}
</code></pre>
<p>Here, we call the <code>fact</code> method again, but with the argument <code>n - 1</code> . We assume that it will give us the correct value <code>(n - 1)!</code> and then we multiply this value with <code>n</code> to get <code>n!</code>. Let's call this method from the <code>main</code> method with <code>n = 5</code>.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">fact</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span> </span>{
        <span class="hljs-keyword">return</span> n * fact(n - <span class="hljs-number">1</span>);
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        System.out.println(fact(<span class="hljs-number">5</span>));
    }
}
</code></pre>
<p>We encountered an error that says:</p>
<pre><code class="lang-java">Exception in thread <span class="hljs-string">"main"</span> java.lang.StackOverflowError
</code></pre>
<p>This is because we are calling <code>fact</code> method infinite times.</p>
<pre><code class="lang-java">fact(<span class="hljs-number">5</span>) = <span class="hljs-number">5</span> * fact(<span class="hljs-number">4</span>)
        = <span class="hljs-number">5</span> * <span class="hljs-number">4</span> * fact(<span class="hljs-number">3</span>)
        = <span class="hljs-number">5</span> * <span class="hljs-number">4</span> * <span class="hljs-number">3</span> * fact(<span class="hljs-number">2</span>)
        = <span class="hljs-number">5</span> * <span class="hljs-number">4</span> * <span class="hljs-number">3</span> * <span class="hljs-number">2</span> * fact(<span class="hljs-number">1</span>)
        = <span class="hljs-number">5</span> * <span class="hljs-number">4</span> * <span class="hljs-number">3</span> * <span class="hljs-number">2</span> * <span class="hljs-number">1</span> * fact(<span class="hljs-number">0</span>)
        = <span class="hljs-number">5</span> * <span class="hljs-number">4</span> * <span class="hljs-number">3</span> * <span class="hljs-number">2</span> * <span class="hljs-number">1</span> * <span class="hljs-number">0</span> * fact(-<span class="hljs-number">1</span>)
        = <span class="hljs-number">5</span> * <span class="hljs-number">4</span> * <span class="hljs-number">3</span> * <span class="hljs-number">2</span> * <span class="hljs-number">1</span> * <span class="hljs-number">0</span> * -<span class="hljs-number">1</span> * fact(-<span class="hljs-number">2</span>)
... and so on
</code></pre>
<p>Since we have not specified when to stop, we end up having too many recursive calls of <code>fact</code> function to be handled by computer memory. We need to tell the <code>fact</code> method when to stop recursion or what is the <strong>base case</strong>. For the factorial function, the base case is <code>n == 0</code>, since <code>0! = 1</code> . Let's rewrite the <code>fact</code> method again so that it returns <code>1</code> for <code>n = 0</code> .</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">fact</span><span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span> </span>{
    <span class="hljs-keyword">if</span> (n == <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
    <span class="hljs-keyword">return</span> n * fact(n - <span class="hljs-number">1</span>);
}
</code></pre>
<p>Now, run the <code>main</code> method and we see the correct output:</p>
<p><code>120</code></p>
<p>Here is how it works:</p>
<pre><code class="lang-java">fact(<span class="hljs-number">5</span>) = <span class="hljs-number">5</span> * fact(<span class="hljs-number">4</span>)
        = <span class="hljs-number">5</span> * (<span class="hljs-number">4</span> * fact(<span class="hljs-number">3</span>))
        = <span class="hljs-number">5</span> * (<span class="hljs-number">4</span> * (<span class="hljs-number">3</span> * fact(<span class="hljs-number">2</span>)))
        = <span class="hljs-number">5</span> * (<span class="hljs-number">4</span> * (<span class="hljs-number">3</span> * (<span class="hljs-number">2</span> * fact(<span class="hljs-number">1</span>))))
        = <span class="hljs-number">5</span> * (<span class="hljs-number">4</span> * (<span class="hljs-number">3</span> * (<span class="hljs-number">2</span> * (<span class="hljs-number">1</span> * fact(<span class="hljs-number">0</span>)))))
        = <span class="hljs-number">5</span> * (<span class="hljs-number">4</span> * (<span class="hljs-number">3</span> * (<span class="hljs-number">2</span> * (<span class="hljs-number">1</span> * <span class="hljs-number">1</span>))))
        = <span class="hljs-number">5</span> * (<span class="hljs-number">4</span> * (<span class="hljs-number">3</span> * (<span class="hljs-number">2</span> * <span class="hljs-number">1</span>)))
        = <span class="hljs-number">5</span> * (<span class="hljs-number">4</span> * (<span class="hljs-number">3</span> * <span class="hljs-number">2</span>))
        = <span class="hljs-number">5</span> * (<span class="hljs-number">4</span> * <span class="hljs-number">6</span>)
        = <span class="hljs-number">5</span> * <span class="hljs-number">24</span>
        = <span class="hljs-number">120</span>
</code></pre>
<p>Now, let's take another example.</p>
<h2 id="heading-fibonacci-sequence">Fibonacci sequence</h2>
<p>The <a target="_blank" href="https://en.wikipedia.org/wiki/Fibonacci_sequence">Fibonacci sequence</a> is a sequence in which each number is the sum of the two preceding ones, that means:</p>
<p><code>fib(n) = fib(n - 1) + fib(n - 2)</code>, where <code>fib(0) = 0</code>, <code>fib(1) = 1</code>.</p>
<p>The task here is to calculate the <code>nth</code> Fibonacci number (<code>fib(n)</code>)We won't look at the iterative way to solve this problem. We directly jump to a recursive solution.</p>
<h3 id="heading-fibonacci-number-using-recursion">Fibonacci Number using recursion</h3>
<p>Since we know the base case and we know how to divide the actual problem into smaller problems, we can easily write the method to do that recursively:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">fib</span> <span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span> </span>{
    <span class="hljs-keyword">if</span> (n == <span class="hljs-number">0</span> || n == <span class="hljs-number">1</span>) <span class="hljs-keyword">return</span> n;
    <span class="hljs-keyword">return</span> fib (n - <span class="hljs-number">1</span>) + fib (n - <span class="hljs-number">2</span>);
}
</code></pre>
<p>The above solution is clean and accurate, but there is a problem with that. Let's look at the calls being made to <code>fib</code> method when we call <code>fib(6)</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684569736956/94f9b540-074b-4b5f-89c6-93a5954b64a2.png" alt="Image showing calls made to fib method to calculate the 6th fibonacci number" class="image--center mx-auto" /></p>
<p>Referring to the above image, let's answer some questions.</p>
<ol>
<li><p>How many times do we calculate the values of <code>fib(6)</code>?</p>
<p> Answer: Once</p>
</li>
<li><p>How many times do we calculate the value of <code>fib(5)</code>?<br /> Answer: Once</p>
</li>
<li><p>How many times do we calculate the value of <code>fib(4)</code>?</p>
<p> Answer: 2 times</p>
</li>
<li><p>How many times do we calculate the value of <code>fib(3)</code>?<br /> Answer: 3 times</p>
</li>
<li><p>How many times do we calculate the value of <code>fib(2)</code>?<br /> Answer: 5 times</p>
</li>
<li><p>How many times do we calculate the value of <code>fib(1)</code>?</p>
<p> Answer: 8 times</p>
</li>
<li><p>How many times do we calculate the value of <code>fib(0)</code>?</p>
<p> Answer: 5 times</p>
</li>
</ol>
<p>As we can see we are calculating <code>fib(x)</code> multiple times for many values of <code>x</code>, which makes the method run very slow. To avoid calculating the same value multiple times, we can use memoization.</p>
<h3 id="heading-fibonacci-number-using-memoization">Fibonacci Number using Memoization</h3>
<p>Basically, we calculate the value once and remember it for the lifetime of the program. And to remember the value, we can use <code>Map</code> or any other similar data structure. While calculating the value of <code>fib(n)</code>, we first check in the map if we have previously calculated the value of <code>fib</code> for the given <code>n</code>. If yes, we return the value. Otherwise, we calculate the value of <code>fib(n)</code> using recursion and store the calculated value in the map. So that, next time we get the value of <code>fib</code> for <code>n</code>. Let's implement it in code:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Map;
<span class="hljs-keyword">import</span> java.util.HashMap;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> Map&lt;Integer, Integer&gt; map = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">fib</span> <span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span> </span>{
        <span class="hljs-keyword">if</span> (n == <span class="hljs-number">0</span> || n == <span class="hljs-number">1</span>) <span class="hljs-keyword">return</span> n;
        <span class="hljs-keyword">if</span> (map.containsKey (n)) <span class="hljs-keyword">return</span> map.get(n);
        <span class="hljs-keyword">int</span> answer = fib (n - <span class="hljs-number">1</span>) + fib (n - <span class="hljs-number">2</span>);
        map.put (n, answer);
        <span class="hljs-keyword">return</span> answer;
    }
    ...
}
</code></pre>
<p>In the above code snippet, we are checking if the <code>map</code> has <code>n</code> as key (if it does, that means, we have calculated <code>fib(n)</code> and it is stored in the <code>map</code>). If yes, then we return the corresponding value. Otherwise, we calculate <code>fib(n)</code> using recursive formula and store the <code>(n, fib(n))</code> key-value pair in the map for future reference.</p>
<p>That's how recursion and memoization work. Let's take a final example and solve it using iteration, recursion, and memoization.</p>
<h2 id="heading-pascals-triangle">Pascal's triangle</h2>
<p>It's hard for me to write the definition of <a target="_blank" href="https://en.wikipedia.org/wiki/Pascal%27s_triangle">Pascal's Triangle</a> formally, so I am attaching 2 images of it from Wikipedia:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684576488713/2d237446-f1b4-4437-bdab-1b52a8d31171.png" alt="Pascal's Triangle" class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684571709527/9574dbcc-f2ea-457b-8bf5-097a81649383.gif" alt="In Pascal's triangle, each number is the sum of the two numbers directly above it." class="image--center mx-auto" /></p>
<p>In programming, it is represented as a matrix or 2-d array:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684572510970/3c0db4ed-6a9b-435b-a785-50fd02d98c2b.png" alt="Pascal's Triangle" class="image--center mx-auto" /></p>
<p>We can see, the value of Pascal's triangle, which can be represented as <code>P(r, c)</code> for row <code>r</code> and column <code>c</code> is (<code>r &gt;= c</code>)</p>
<ul>
<li><p><code>1</code> if <code>c = 0</code></p>
</li>
<li><p><code>1</code> if <code>r = c</code></p>
</li>
<li><p><code>P(r - 1, c - 1) + P(r - 1, c)</code>, else</p>
</li>
</ul>
<p>Now, the problem is that we are given an integer <code>n</code>. And we need to print Pascal's Triangle till the row <code>n</code>. (The first row is considered as row <code>0</code>).</p>
<h3 id="heading-iterative-way-to-pascals-triangle">Iterative way to Pascal's Triangle</h3>
<p>Let's create a 2-d array <code>P</code> with <code>n + 1</code> rows and <code>n + 1</code> columns. For each row <code>r</code> the first column (<code>c = 0</code>) and the last column (<code>c = r</code>) is <code>1</code>. The rest can be calculated using the formula above. Let's write code for it.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">printPascalTriangle</span> <span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span> </span>{
    <span class="hljs-keyword">int</span>[][] P = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[n + <span class="hljs-number">1</span>][n + <span class="hljs-number">1</span>];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> r = <span class="hljs-number">0</span>; r &lt;= n; r++) {
        P[r][<span class="hljs-number">0</span>] = <span class="hljs-number">1</span>;
        P[r][r] = <span class="hljs-number">1</span>;
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> c = <span class="hljs-number">1</span>; c &lt; r; c++) {
            P[r][c] = P[r - <span class="hljs-number">1</span>][c - <span class="hljs-number">1</span>] + P[r - <span class="hljs-number">1</span>][c];
        }
    }
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> r = <span class="hljs-number">0</span>; r &lt;= n; r++) {
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> c = <span class="hljs-number">0</span>; c &lt;= r; c++) {
            System.out.print(P[r][c] + <span class="hljs-string">" "</span>);
        }
        System.out.println();
    }
}
</code></pre>
<p>This method prints Pascal's Triangle from row <code>0</code> to row <code>n</code>. Now, let's solve it using recursion.</p>
<h3 id="heading-iterative-way-to-pascals-triangle-1">Iterative way to Pascal's Triangle</h3>
<p>Let's create a method <code>pascalNumber(int r, int c)</code> that gives the number at the row <code>r</code> and column <code>c</code> in the Pascal's Triangle. We already have a recursive formula to calculate this with base conditions from the definition of Pascal's Triangle. So, it is quite easy to implement this method.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">pascalNumber</span> <span class="hljs-params">(<span class="hljs-keyword">int</span> r, <span class="hljs-keyword">int</span> c)</span> </span>{
    <span class="hljs-keyword">if</span> (c == <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
    <span class="hljs-keyword">if</span> (r == c) <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
    <span class="hljs-keyword">return</span> pascalNumber(r - <span class="hljs-number">1</span>, c - <span class="hljs-number">1</span>) + pascalNumber(r - <span class="hljs-number">1</span>, c);
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">printPascalTriangle</span> <span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span> </span>{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> r = <span class="hljs-number">0</span>; r &lt;= n; r++) {
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> c = <span class="hljs-number">0</span>; c &lt;= r; c++) {
            System.out.print(pascalNumber(r, c) + <span class="hljs-string">" "</span>);
        }
        System.out.println();
    }    
}
</code></pre>
<p>In the above code snippet, we are making some recursive calls to solve sub-problems. But, we will end up solving the same problem again and again and the program will become too slow. So, let's use memoization to improve the performance.</p>
<h3 id="heading-memoization-way-to-pascals-triangle">Memoization way to Pascal's Triangle</h3>
<p>To store the calculated value for <code>(r, c)</code> pair, we can use a 2-d array <code>P</code>. We initialize <code>P</code> in <code>printPascalTriangle</code> method. If the value of <code>P[r][c]</code> is zero, that means we have not calculated the value for <code>(r, c)</code> yet, and we calculate this value using recursion and store it. Otherwise, if it is not zero, we simply return it.</p>
<pre><code class="lang-java"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span>[][] P;
<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">pascalNumber</span> <span class="hljs-params">(<span class="hljs-keyword">int</span> r, <span class="hljs-keyword">int</span> c)</span> </span>{
    <span class="hljs-keyword">if</span> (P[r][c] != <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> P[r][c];
    <span class="hljs-keyword">if</span> (c == <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
    <span class="hljs-keyword">if</span> (r == c) <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
    P[r][c] = pascalNumber(r - <span class="hljs-number">1</span>, c - <span class="hljs-number">1</span>) + pascalNumber(r - <span class="hljs-number">1</span>, c);
    <span class="hljs-keyword">return</span> P[r][c];
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">printPascalTriangle</span> <span class="hljs-params">(<span class="hljs-keyword">int</span> n)</span> </span>{
    P = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[n + <span class="hljs-number">1</span>][n + <span class="hljs-number">1</span>];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> r = <span class="hljs-number">0</span>; r &lt;= n; r++) {
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> c = <span class="hljs-number">0</span>; c &lt;= r; c++) {
            System.out.print(pascalNumber(r, c) + <span class="hljs-string">" "</span>);
        }
        System.out.println();
    }
}
</code></pre>
<p>This way we don't calculate the same value again and again. This improves the time complexity of the method.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope you have learned something new from this article. The source code can be found <a target="_blank" href="https://github.com/java-rush/java10daysChallenge/tree/main/recursion-and-memoization">here</a>. Please, give your suggestions and subscribe to my newsletter. It will be a great help. Thank you for your time. Will meet soon.</p>
]]></content:encoded></item><item><title><![CDATA[Configure Multiple Git Accounts on a Single Computer]]></title><description><![CDATA[Learn how to use configuration files to configure git to use different git accounts and configuration variables for different repositories]]></description><link>https://blog.javarush.dev/configure-multiple-git-accounts-on-a-single-computer</link><guid isPermaLink="true">https://blog.javarush.dev/configure-multiple-git-accounts-on-a-single-computer</guid><category><![CDATA[Git]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[GitLab]]></category><category><![CDATA[configuration]]></category><category><![CDATA[ssh]]></category><dc:creator><![CDATA[Himanshu Pareek]]></dc:creator><pubDate>Tue, 27 Dec 2022 05:20:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1671785968478/15352356-e9d3-41d4-aba1-9c5f76169e90.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Sometimes we need to work with multiple repositories or groups of repositories that use different git accounts on the same computer. Here, a git account refers to an account created on online version control system (VCS) platforms, such as Github, Bitbucket, Gitlab, etc. One way to accomplish this is to change the account information used by git whenever we switch repositories. But, keep changing this information is a tedious and error-prone task. We want to configure git such that, whenever we change repositories, it automatically picks up the correct information. Let's see how to do that...</p>
<h2 id="heading-scenario">Scenario</h2>
<p>In this article, we will consider the following scenario:</p>
<p>We have 3 git accounts (Steps to get SSH User and Hostname are given below):</p>
<ol>
<li><p>First Account</p>
<pre><code class="lang-bash"> <span class="hljs-comment"># Account 1</span>
 Name = John Doe
 Email = johndoe.codeready@gmail.com
 GitLab Username = @johndoe.codeready
 SSH User = git
 SSH Hostname = gitlab.com
</code></pre>
</li>
<li><p>Second Account</p>
<pre><code class="lang-bash"> <span class="hljs-comment"># Account 2</span>
 Name = Jack Smith
 Email = jacksmith.codeready@gmail.com
 Github Username = jack-codeready
 SSH User = git
 SSH Hostname = github.com
</code></pre>
</li>
<li><p>Third Account (Default Account)</p>
<pre><code class="lang-bash"> <span class="hljs-comment"># Account 3</span>
 Name = John Doe
 Email = johndoe.codeready@gmail.com
 Github Username = john-codeready
 SSH User = git
 SSH Hostname = github.com
</code></pre>
</li>
</ol>
<p>To get the value of SSH <code>User</code> and <code>Hostname</code> for any account, do the following:</p>
<ol>
<li><p>Login to the account.</p>
</li>
<li><p>Go to any repository (Create one if there is no repository).</p>
</li>
<li><p>Click on the <strong>Code</strong> button for the GitHub repository or the <strong>Clone</strong> button for the GitLab repository.</p>
</li>
<li><p>Select <strong>SSH as</strong> the clone method.</p>
</li>
<li><p>Copy the SSH URL. It will be in the format of <code>{User}@{Hostname}:{Organization}/{Repository Name}</code> .</p>
</li>
<li><p>And you have the value of SSH <code>User</code> and <code>Hostname</code> for that account.</p>
</li>
</ol>
<p>The following screenshot is taken from Github. Here, SSH User is <code>git</code> and Hostname is <code>github.com</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671640732537/qD2lI3Lfj.png" alt="Image showing SSH User and Hostname for a github repository" class="image--center mx-auto" /></p>
<p>The following screenshot is taken from GitLab. Here, SSH User is <code>git</code> and Hostname is <code>gitlab.com</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671726443218/1b7852af-9a32-46c9-b77a-291b6546fa1e.png" alt="Image showing SSH User and Hostname for a GitLab repository" class="image--center mx-auto" /></p>
<p>In most cases, the SSH User will be <code>git</code>, but it is better to follow the steps to get both the <code>User</code> and the <code>Hostname</code>.</p>
<p>We have 2 directories <code>Projects</code> and <code>Development</code> in home(<code>~</code>) directory.</p>
<p>Our goal is that for any repository inside <code>Projects</code> directory git should use <code>Account1</code> and for any repository inside <code>Development</code> git should use <code>Account2</code>. For all other repositories, which are not in any of these directories, it should use <code>Account3</code>.</p>
<p>We want to use <code>SSH</code> for authentication and authorization and want to sign the commits using the correct GPG keys.</p>
<h2 id="heading-git-config-files">git-config FILES</h2>
<p>By default, git reads configuration options from some pre-defined files. One of them is <code>~/.gitconfig</code>. In this file, we can define some configuration options and can include other configuration files. These files contain information related to the git username, email, GPG sign key, etc. GPG keys are used to sign the commits while committing changes to any branch.</p>
<p>Git uses another file which is <code>~/.ssh/config</code> to make an SSH connection to GitHub (or any other online VCS platform) to authorize the current user. This is used while cloning the repository, pulling/fetching changes from the online repository, pushing changes to the online repository, or any other git operations that include communication with GitHub.</p>
<h2 id="heading-creating-config-files">Creating config files</h2>
<h3 id="heading-create-a-common-default-config-file">Create a common / default config file</h3>
<p>Create a file <code>.gitconfig</code> in the home directory. Update the <code>~/.gitconfig</code> file with the following content:</p>
<pre><code class="lang-apache"><span class="hljs-comment"># ~/.gitconfig</span>
<span class="hljs-comment">######### Common and Default Configuration for Git #########</span>

<span class="hljs-comment"># Congiguration for default user (Account 3, in this scenario)</span>
<span class="hljs-comment"># to be used by git</span>
[<span class="hljs-attribute">user</span>]
    <span class="hljs-comment"># Personal name of the git user</span>
    <span class="hljs-attribute">name</span> = John Doe

    <span class="hljs-comment"># Email Address of the git user</span>
    <span class="hljs-attribute">email</span> = johndoe.codeready@gmail.com

    <span class="hljs-comment"># Signing key to sign the commits by this user</span>
    <span class="hljs-comment"># For now, it is empty</span>
    <span class="hljs-comment"># Later, we will generate it and will update this file</span>
    <span class="hljs-attribute">signingKey</span> = 

<span class="hljs-comment"># Configuration related to Commits</span>
[<span class="hljs-attribute">commit</span>]
    <span class="hljs-comment"># Since, gpgsign = true, git will always sign the commits</span>
    <span class="hljs-comment"># Otherwise, whenever we want to sign the commits, we need</span>
    <span class="hljs-comment"># to use "-S" flag while commiting. Ex - </span>
    <span class="hljs-comment"># git commit -S -m "Commit Message"</span>
    <span class="hljs-comment"># And, often we forget to include this flag and that leads</span>
    <span class="hljs-comment"># to a lot of extra work</span>
    <span class="hljs-attribute">gpgsign</span> = true

<span class="hljs-comment"># This condition check if the current git directory</span>
<span class="hljs-comment"># is inside "~/Projects/" path</span>
[<span class="hljs-attribute">includeIf</span> <span class="hljs-string">"gitdir:~/Projects/"</span>]
    <span class="hljs-comment"># In that case, we also use the configurations specified</span>
    <span class="hljs-comment"># in "~/.gitconfig.projects" file.</span>
    <span class="hljs-comment"># In "~/.gitconfig.projects" file, we can add new config values</span>
    <span class="hljs-comment"># or can updated the existing config values</span>
    <span class="hljs-attribute">path</span> = ~/.gitconfig.projects

[<span class="hljs-attribute">includeIf</span> <span class="hljs-string">"gitdir:~/Development/"</span>]
    <span class="hljs-attribute">path</span> = ~/.gitconfig.development
</code></pre>
<p>In the above file:</p>
<ul>
<li><p>We have specified the name, email, and signing key for the default user.</p>
</li>
<li><p>We have specified that we want every commit to be signed.</p>
</li>
<li><p>We instructed git to read configurations from <code>~/.gitconfig.projects</code> also if the current repository is inside <code>~/Projects</code> directory.</p>
</li>
<li><p>We instructed git to read configurations from <code>~/.gitconfig.development</code> also if the current repository is inside <code>~/Development</code> directory.</p>
</li>
</ul>
<h3 id="heading-create-config-files-for-different-accounts">Create config files for different accounts</h3>
<p>Let's create 2 files (<code>~/.gitconfig.projects</code> and <code>~/.gitconfig.development</code> ) for <code>Account1</code> and <code>Account2</code>, respectively.</p>
<pre><code class="lang-apache"><span class="hljs-comment"># ~/.gitconfig.projects</span>
<span class="hljs-comment">######### Configuration for Account1 #########</span>

<span class="hljs-comment"># Congiguration for Account1 to be used by git when we are inside</span>
<span class="hljs-comment"># "~/Projects/" repository</span>
[<span class="hljs-attribute">user</span>]
    <span class="hljs-comment"># Personal name of the git user</span>
    <span class="hljs-attribute">name</span> = John Doe

    <span class="hljs-comment"># Email Address of the git user</span>
    <span class="hljs-attribute">email</span> = johndoe.codeready@gmail.com

    <span class="hljs-comment"># Signing key to sign the commits by this user</span>
    <span class="hljs-comment"># For now, it is empty</span>
    <span class="hljs-comment"># Later, we will generate it and will update this file</span>
    <span class="hljs-attribute">signingKey</span> =
</code></pre>
<pre><code class="lang-apache"><span class="hljs-comment"># ~/.gitconfig.development</span>
<span class="hljs-comment">######### Configuration for Account2 #########</span>

<span class="hljs-comment"># Congiguration for Account2 to be used by git when we are inside</span>
<span class="hljs-comment"># "~/Development/" repository</span>
[<span class="hljs-attribute">user</span>]
    <span class="hljs-comment"># Personal name of the git user</span>
    <span class="hljs-attribute">name</span> = Jack Smith

    <span class="hljs-comment"># Email Address of the git user</span>
    <span class="hljs-attribute">email</span> = jacksmith.codeready@gmail.com

    <span class="hljs-comment"># Signing key to sign the commits by this user</span>
    <span class="hljs-comment"># For now, it is empty</span>
    <span class="hljs-comment"># Later, we will generate it and will update this file</span>
    <span class="hljs-attribute">signingKey</span> =
</code></pre>
<p>For all 3 accounts, we will generate signing keys later.</p>
<h3 id="heading-create-ssh-config-file">Create SSH config file</h3>
<p>Create a file <code>config</code> inside <code>~/.ssh/</code> directory, if it is not there. And put the following content there:</p>
<pre><code class="lang-apache"><span class="hljs-comment"># SSH Configuration for Account1</span>
<span class="hljs-comment"># John Doe's GitLab Account</span>
<span class="hljs-attribute">Host</span> account<span class="hljs-number">1</span>
    <span class="hljs-attribute">User</span>    git
    <span class="hljs-attribute">Hostname</span>    bitbucket.org
    <span class="hljs-attribute">IdentityFile</span> # Location of identity file for account<span class="hljs-number">1</span> (will update later)
    <span class="hljs-attribute">AddKeysToAgent</span> yes

<span class="hljs-comment"># SSH Configuration for Account2</span>
<span class="hljs-comment"># Jack Smith's GitHub Account</span>
<span class="hljs-attribute">Host</span> account<span class="hljs-number">2</span>
    <span class="hljs-attribute">User</span>    git
    <span class="hljs-attribute">Hostname</span>    github.com
    <span class="hljs-attribute">IdentityFile</span> # Location of identity file for account<span class="hljs-number">2</span> (will update later)
    <span class="hljs-attribute">AddKeysToAgent</span> yes

<span class="hljs-comment"># SSH Configuration for Account3 (Default Account)</span>
<span class="hljs-comment"># John Doe's GitHub Account</span>
<span class="hljs-attribute">Host</span> account<span class="hljs-number">3</span>
    <span class="hljs-attribute">User</span>    git
    <span class="hljs-attribute">Hostname</span>    github.com
    <span class="hljs-attribute">IdentityFile</span> # Location of identity file for account<span class="hljs-number">3</span> (will update later)
    <span class="hljs-attribute">AddKeysToAgent</span> yes
</code></pre>
<p>We are almost done with the configuration files. We need to generate SSH keys and GPG keys for each account and need to update the config files. Let's do that now.</p>
<h2 id="heading-generate-and-configure-ssh-keys">Generate and Configure SSH Keys</h2>
<p>For each account, follow these steps to generate, upload and use the SSH Keys.</p>
<h3 id="heading-generate-ssh-keys">Generate SSH Keys</h3>
<p>Generate SSH Key using the following steps:</p>
<ol>
<li><p>Open Terminal (Mac/Linux) or Git Bash (Windows).</p>
</li>
<li><p>Run the following command with the correct email address:</p>
<pre><code class="lang-bash"> ssh-keygen -t ed25519 -C <span class="hljs-string">"johndoe.codeready@gmail.com"</span>
</code></pre>
</li>
<li><p>If you are asked to enter the file name to save the key, use a different filename for each account (You can include GitHub/GitLab username in the filename to make them unique for each account). In the following code snippet, I am using <code>/c/Users/himan/.ssh/id_ed25519_johndoe.codeready</code> as the filename for <code>Account 1</code>. Here <code>johndoe.codeready</code> is the GitLab username of <code>Account 1</code>.</p>
<pre><code class="lang-bash"> Generating public/private ed25519 key pair.
 Enter file <span class="hljs-keyword">in</span> <span class="hljs-built_in">which</span> to save the key (/c/Users/himan/.ssh/id_ed25519): /c/Users/himan/.ssh/id_ed25519_johndoe.codeready
</code></pre>
</li>
</ol>
<ol>
<li><p>When asked, enter a passphrase for the ssh key. (You will be asked to enter the same passphrase twice). <strong>You must remember the passphrase</strong>.</p>
</li>
<li><p>If we look at the files inside <code>~/.ssh</code> directory, we see 2 files for one ssh key - One without any extension and one with <code>.pub</code> extension.</p>
<p> The file without any extension is <strong>Private Key</strong> and the file with the extension <code>.pub</code> is <strong>Public Key</strong>. Don't share your <em>Private Key</em> with anyone. We will upload the <em>Public Key to GitH</em>ub or GitLab.</p>
</li>
</ol>
<h3 id="heading-upload-public-ssh-key-to-github-gitlab">Upload Public SSH Key to GitHub / GitLab</h3>
<p>Follow these steps to upload the public ssh key (one with <code>.pub</code> extension) to GitHub or GitLab:</p>
<ol>
<li><p>Copy the content from <em>Public SSH Key</em>. The SSH key file has <code>.pub</code> extension.</p>
</li>
<li><p>If the account is related to Github, go to <a target="_blank" href="https://github.com/settings/keys">https://github.com/settings/keys</a> and click on the <strong>New SSH Key</strong> button.<br /> If the account is related to GitLab, go to <a target="_blank" href="https://gitlab.com/-/profile/keys">https://gitlab.com/-/profile/keys</a>.</p>
</li>
<li><p>Give some Title/Label to the key.</p>
</li>
<li><p>If asked for the <strong>Key Type</strong>, select <em>Authentication Key</em>.</p>
</li>
<li><p>Paste the copied content in the <strong>Key</strong> textbox.</p>
</li>
<li><p>Click on <strong>Add Key</strong> button.</p>
</li>
</ol>
<h3 id="heading-configure-the-ssh-config-file-to-use-the-ssh-key">Configure the ssh-config file to use the ssh-key</h3>
<p>Now, add the path of the <strong>Private SSH Key</strong> file for the value of <code>IdentityFile</code> variable in the <code>~/.ssh/config</code> file for the correct account.</p>
<p>After following all the 3 steps for all accounts, we created SSH keys for each account, uploaded public SSH keys to the corresponding online VCS account and we have added the location of private SSH keys inside <code>~/.ssh/config</code> file. The <code>~/.ssh/config</code> should look like this:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># SSH Configuration for Account1</span>
<span class="hljs-comment"># John Doe's GitLab Account</span>
Host account1 <span class="hljs-comment"># ssh -T account1</span>
    User    git
    Hostname    gitlab.com
    IdentityFile    ~/.ssh/id_ed25519_johndoe.codeready
    AddKeysToAgent  yes

<span class="hljs-comment"># SSH Configuration for Account2</span>
<span class="hljs-comment"># Jack Smith's Github Account</span>
Host account2 <span class="hljs-comment"># ssh -T account2</span>
    User    git
    Hostname    github.com
    IdentityFile    ~/.ssh/id_ed25519_jack-codeready-github
    AddKeysToAgent yes

<span class="hljs-comment"># SSH Configuration for Account3 (Default Account)</span>
<span class="hljs-comment"># John Doe's Github Account</span>
Host account3 <span class="hljs-comment"># ssh -T account3</span>
    User    git
    Hostname    github.com
    IdentityFile    ~/.ssh/id_ed25519_john-codeready-github
    AddKeysToAgent yes
</code></pre>
<p>Now, let's test if the SSH configuration is working or not.</p>
<p>Run the following command to authenticate <code>Account 1</code> :</p>
<pre><code class="lang-bash">ssh -T account1
</code></pre>
<p>If it is the first time connecting to this account, it will ask for confirmation, type <code>yes</code> and press Enter.</p>
<p>When asked for a passphrase, enter the passphrase created while generating the corresponding ssh keys.</p>
<p>Then, it will show a message that you are authenticated using ssh.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671727217199/894b3c64-d69a-4212-8eda-8b60a4d6b0a9.png" alt class="image--center mx-auto" /></p>
<p>Thus, we can connect to the git accounts using the correct ssh keys. It's time to configure GPG keys so our commits are signed correctly. Let's do that now.</p>
<h2 id="heading-generate-and-configure-gpg-keys">Generate and Configure GPG Keys</h2>
<p>For each account, do the following to generate, upload and configure the GPG key.</p>
<h3 id="heading-generate-gpg-key">Generate GPG Key</h3>
<ol>
<li><p>Open Terminal / Git Bash.</p>
</li>
<li><p>Run the following command:</p>
<pre><code class="lang-bash"> gpg --full-generate-key
</code></pre>
</li>
<li><p>At the prompt, specify the kind of key you want. Type <code>1</code> and press <code>Enter</code> to accept the default.</p>
</li>
<li><p>When asked for the length of the key, specify <code>4096</code>.</p>
</li>
<li><p>Enter the length of time for which the key should be valid. If you don't want the key to expire, type <code>0</code> and press <code>Enter</code>.</p>
</li>
<li><p>When asked for confirmation, specify <code>y</code>.</p>
</li>
<li><p>When asked, enter your real name.</p>
</li>
<li><p>Then enter the email address related to the account.</p>
</li>
<li><p>Then you need to add a comment to the GPG key. Add something specific to the account so that later you can recall the purpose of the key. For instance, I have specified <code>John Doe - GitLab Account</code> as a comment for <code>Account 1</code>.</p>
</li>
<li><p>Type a secure passphrase (and re-type it).</p>
</li>
<li><p>Run the following command to list the GPG keys:</p>
<pre><code class="lang-bash">gpg --list-secret-keys --keyid-format=long
</code></pre>
<p>The output will be similar to the following (You may have more than one key).</p>
<pre><code class="lang-bash">sec   rsa4096/75BDED420C522BEB 2022-12-22 [SC]
      AE815B28610907D3A31E19BD75BDED420C522BEB
uid                 [ultimate] John Doe (John Doe - GitLab Account) &lt;johndoe.codeready@gmail.com&gt;
ssb   rsa4096/08310F3B00DB38D1 2022-12-22 [E]
</code></pre>
</li>
<li><p>Copy the long form of the GPG key id that you want to use (The comment related to the key can be useful to recognize the key). In the above example, the GPG key Id is <code>75BDED420C522BEB</code>.</p>
</li>
<li><p>Run the following command to get the Public GPG key for the above id (Replace the id with your id):</p>
<pre><code class="lang-bash">gpg --armor --<span class="hljs-built_in">export</span> 75BDED420C522BEB <span class="hljs-comment"># Prints the GPG key ID, in ASCII armor format</span>
</code></pre>
<p>The output will be similar to the following:</p>
<pre><code class="lang-bash">-----BEGIN PGP PUBLIC KEY BLOCK-----

mQINBGOkiMwBEACzHZDQUmibFy3/jBNBROBHG5CridNUorgW8dBzbNyw9hyV5FYL
<span class="hljs-comment"># Some more stuff</span>
=Wci4
-----END PGP PUBLIC KEY BLOCK-----
</code></pre>
<p>Copy the whole output, which is your Public GPG key.</p>
</li>
</ol>
<h3 id="heading-upload-public-gpg-key-to-account">Upload Public GPG Key to Account</h3>
<p>For the GitHub account, go to <a target="_blank" href="https://github.com/settings/keys">https://github.com/settings/keys</a> and click on the <strong>New GPG Key</strong> button.</p>
<p>For the GitLab account, go to https://gitlab.com/-/profile/gpg_keys.</p>
<p>Paste the public GPG key in the text box and click on the <strong>Add Key</strong> button.</p>
<h3 id="heading-update-git-config-file-with-id-of-gpg-key">Update git config file with Id of GPG key</h3>
<p>Paste the id of the GPG key (<code>75BDED420C522BEB</code> in this case) as the value of the <code>signingKey</code> variable in the appropriate git config file, which we created earlier. In this case, since this is for <code>Account 1</code>. So, I will put it in the <code>~/.gitconfig.projects</code> file.</p>
<p>After the above steps, below are the 3 updated config files:</p>
<p><code>~/.gitconfig</code></p>
<pre><code class="lang-bash"><span class="hljs-comment"># ~/.gitconfig</span>
<span class="hljs-comment">######### Common and Default Configuration for Git #########</span>

<span class="hljs-comment"># Congiguration for default user (Account 3, in this scenario)</span>
<span class="hljs-comment"># to be used by git</span>
[user]
    <span class="hljs-comment"># Personal name of the git user</span>
    name = John Doe

    <span class="hljs-comment"># Email Address of the git user</span>
    email = johndoe.codeready@gmail.com

    <span class="hljs-comment"># Signing key to sign the commits by this user</span>
    signingKey = FF650CD14C619C34

<span class="hljs-comment"># Configuration related to Commits</span>
[commit]
    <span class="hljs-comment"># Since, gpgsign = true, git will always sign the commits</span>
    <span class="hljs-comment"># Otherwise, whenever we want to sign the commits, we need</span>
    <span class="hljs-comment"># to use "-S" flag while commiting. Ex -</span>
    <span class="hljs-comment"># git commit -S -m "Commit Message"</span>
    <span class="hljs-comment"># And, often we forget to include this flag and that leads</span>
    <span class="hljs-comment"># to a lot of extra work</span>
    gpgsign = <span class="hljs-literal">true</span>

<span class="hljs-comment"># This condition check if the current git directory</span>
<span class="hljs-comment"># is inside "~/Projects/" path</span>
[includeIf <span class="hljs-string">"gitdir:~/Projects/"</span>]
    <span class="hljs-comment"># In that case, we also use the configurations specified</span>
    <span class="hljs-comment"># in "~/.gitconfig.projects" file.</span>
    <span class="hljs-comment"># In "~/.gitconfig.projects" file, we can add new config values</span>
    <span class="hljs-comment"># or can updated the existing config values</span>
    path = ~/.gitconfig.projects

[includeIf <span class="hljs-string">"gitdir:~/Development/"</span>]
    path = ~/.gitconfig.development
</code></pre>
<p><code>~/.gitconfig.projects</code></p>
<pre><code class="lang-bash"><span class="hljs-comment"># ~/.gitconfig.projects</span>
<span class="hljs-comment">######### Configuration for Account1 #########</span>

<span class="hljs-comment"># Congiguration for Account1 to be used by git when we are inside</span>
<span class="hljs-comment"># "~/Projects/" repository</span>
[user]
    <span class="hljs-comment"># Personal name of the git user</span>
    name = John Doe

    <span class="hljs-comment"># Email Address of the git user</span>
    email = johndoe.codeready@gmail.com

    <span class="hljs-comment"># Signing key to sign the commits by this user</span>
    signingKey = 75BDED420C522BEB
</code></pre>
<p><code>~/.gitconfig.development</code></p>
<pre><code class="lang-bash"><span class="hljs-comment"># ~/.gitconfig.development</span>
<span class="hljs-comment">######### Configuration for Account2 #########</span>

<span class="hljs-comment"># Congiguration for Account2 to be used by git when we are inside</span>
<span class="hljs-comment"># "~/Development/" repository</span>
[user]
    <span class="hljs-comment"># Personal name of the git user</span>
    name = Jack Smith

    <span class="hljs-comment"># Email Address of the git user</span>
    email = jacksmith.codeready@gmail.com

    <span class="hljs-comment"># Signing key to sign the commits by this user</span>
    signingKey = C8A49A252EF556F7
</code></pre>
<h2 id="heading-how-to-use-it">How to use it?</h2>
<p>If you create any git repository inside <code>Projects</code> directory, Git will automatically pick the configurations for <code>Account 1</code> and so on. You can also clone repositories for <code>Account1</code> inside <code>Projects</code> repository using the below command:</p>
<pre><code class="lang-bash">git <span class="hljs-built_in">clone</span> account1:johndoe.codeready/hello-gitlab.git
</code></pre>
<p>And whenever you commit any changes, Git will ask for the passphrase for the GPG key and it will sign the commits with the correct GPG key based on which directory you are in.</p>
<p>That's it for this article. It is a long one, but it can save you a lot of time later if you work on multiple projects involving different accounts on a single machine. You don't need to change configurations for Git whenever you change the project/directory.</p>
]]></content:encoded></item><item><title><![CDATA[Getting started with NestJS]]></title><description><![CDATA[How to get started with NestJS Framework to build efficient, scalable Node.js server-side applications.]]></description><link>https://blog.javarush.dev/getting-started-with-nestjs</link><guid isPermaLink="true">https://blog.javarush.dev/getting-started-with-nestjs</guid><category><![CDATA[nestjs]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Express]]></category><category><![CDATA[fastify]]></category><category><![CDATA[nest]]></category><dc:creator><![CDATA[Himanshu Pareek]]></dc:creator><pubDate>Mon, 17 Oct 2022 10:56:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1665913572792/GpurJzbAZ.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you have ever created server-side apps using NodeJS, you might have used express, fastify or other HTTP framework. Although, these are very easy to get started and perfect for small projects involving small team. But, if you want to create a project which will last longer and has many contributors, you need a good application architecture to align the team. You may create this by yourself or you can use existing framework like <strong>Nest</strong> to accomplish the goal.</p>
<h2 id="heading-what-is-nest">What is Nest</h2>
<p><strong><a target="_blank" href="https://nestjs.com/">Nest(NestJS)</a></strong> is a framework for building efficient, scalable Node.js server-side applications. Nest provides an out-of-the-box application architecture that allows developers and teams to create highly testable, scalable, loosely coupled, and easily maintainable applications. So, let's get started:</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<ol>
<li><a target="_blank" href="https://nodejs.org/en/">Node.js</a> (version &gt;= 12, except version 13)</li>
<li><a target="_blank" href="https://www.npmjs.com/">npm</a>, which is installed along with Node.js</li>
</ol>
<h2 id="heading-install-nest-cli">Install Nest CLI</h2>
<p>To create nest applications, we need <a target="_blank" href="https://docs.nestjs.com/cli/overview">Nest cli</a>. Run the following command to install it</p>
<pre><code>npm install --<span class="hljs-built_in">global</span> @nestjs/cli
</code></pre><h2 id="heading-create-a-new-project">Create a new project</h2>
<p>Let's create a new project <code>nest-blogs</code> using nest cli. Run the below command to create the project</p>
<pre><code>nest <span class="hljs-keyword">new</span> --strict nest-blogs
</code></pre><p>When it asks to select a package manager to use, select any one you want to use. I selected <code>npm</code> and will be using that. It will take some time since it will install the required node modules as well. Here, the optional <code>--strict</code> flag enables the strict mode in TypeScript.</p>
<h2 id="heading-project-structure">Project Structure</h2>
<p>Open the <code>nest-blogs</code> directory in any code editor or IDE. We have the following files in the project</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1665903904225/39WTLWkfQ.png" alt="Project structure of a new project created using nest cli" class="image--center mx-auto" />
Let's take a look at the purpose of each file in brief:</p>
<ol>
<li>The <code>package.json</code> file has information about the project, a list of npm dependencies required for the project, and some useful scripts.</li>
<li>The <code>tsconfig.json</code> and <code>tsconfig.build.json</code> files specify the root files and the compiler options required to compile the project.</li>
<li>The <code>nest-cli.json</code> file is used by the nest to keep the metadata needed to organize, build and deploy the project.</li>
<li>The <code>.prettierrc</code> file is a configuration file used by <a target="_blank" href="https://prettier.io/">Prettier</a> tool to format the code.</li>
<li>The <code>.eslintrc.js</code> file is used by <a target="_blank" href="https://eslint.org/">ESLint</a> to identify and report on patterns found in ECMAScript/Javascript code.</li>
<li>The <code>app.controller.ts</code> is a basic controller with a single route. Controllers are used to map the incoming request to specific functions and to return the response back to the client.</li>
<li>The <code>app.controller.spec.ts</code> is a unit test for the controller.</li>
<li>The <code>app.service.ts</code> is a basic service with a single method. Services are the places where we put the business logic of the application.</li>
<li>The <code>app.module.ts</code> is the root module of the application. Modules are used to divide the application into seperate parts depending on the responsibility.</li>
<li>The <code>main.ts</code> is the entry point of the application which uses the core function <code>NestFactory</code> to create a nest application instance.</li>
</ol>
<h2 id="heading-running-the-application">Running the application</h2>
<p>While creating the application, if required node modules are not installed due to some reason or if you have used <code>--skip-install</code> flag, run the below command to install packages now from the <code>nest-blogs</code> directory</p>
<pre><code>npm install
</code></pre><p>Run the below command to start the applicatin:</p>
<pre><code>npm start
</code></pre><p>Open <code>http://localhost:3000/</code> url in the browser. You should see <strong>Hello World!</strong> on the page. Press <code>Ctrl ^ c</code> in the terminal to stop the app. While developing the app, we want the app to restart automatically as soon as we make any changes. To do that, run the below command in the terminal:</p>
<pre><code>npm run start:dev
</code></pre><p>If we again go to the same link, we see the same text. Now, do the following:</p>
<ol>
<li>Open 'app.service.ts` file in editor.</li>
<li><p>Change <code>getHello</code> method to return <code>Hello Universe</code> instead of <code>Hello World!</code>.</p>
<pre><code><span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;

@Injectable()
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppService</span> </span>{
 getHello(): string {
   <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello Universe'</span>;
 }
}
</code></pre></li>
<li>Save the file.</li>
<li>Go to the same link and reload the page.</li>
<li>We see <strong>Hello Universe</strong> on the page.</li>
</ol>
<p>This way, we don't need to stop and start the server manually. It will restart as soon as it detects changes in any project-related file(s).</p>
<h2 id="heading-platform">Platform</h2>
<p>Nest can work with any Node HTTP framework using adapters. Nest provides out-of-the-box adapters for two HTTP frameworks - <a target="_blank" href="https://expressjs.com/">express</a> and <a target="_blank" href="https://www.fastify.io/">fastify</a>.</p>
<ol>
<li><code>platform-express</code> is the adapter for <code>express</code> and it is used by default in Nest projects. We don't have to do anything additional to use express.</li>
<li><p><code>platform-fastify</code> is the adapter for <code>fastify</code>. To work with <em>fastify</em> instead of <em>express</em>, below steps are required - </p>
<ol>
<li>Install the required package using<pre><code>npm install --save @nestjs/platform-fastify
</code></pre></li>
<li><p>Modify <code>main.ts</code> to use <code>FastifyAdapter</code> to create the application</p>
<pre><code><span class="hljs-keyword">import</span> { NestFactory } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/core'</span>;
<span class="hljs-keyword">import</span> {
FastifyAdapter,
NestFastifyApplication,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/platform-fastify'</span>;
<span class="hljs-keyword">import</span> { AppModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.module'</span>;

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bootstrap</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> app = <span class="hljs-keyword">await</span> NestFactory.create&lt;NestFastifyApplication&gt;(
  AppModule,
  <span class="hljs-keyword">new</span> FastifyAdapter(),
);
<span class="hljs-keyword">await</span> app.listen(<span class="hljs-number">3000</span>);
}
bootstrap();
</code></pre></li>
<li>Restart the application and make sure it works.</li>
</ol>
</li>
</ol>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we have setup a basic Nest project. In the upcoming blogs, we will explore more. You can find the project on <a target="_blank" href="https://github.com/himanshu-pareek/nest-blogs/tree/01_getting_started_with_nestjs">github</a>. Please provide your feedback in the comments. We will meet in the next blog. Until then, happy learning.</p>
]]></content:encoded></item><item><title><![CDATA[8 Console Methods every JavaScript Developer should know]]></title><description><![CDATA[In this article, we will discuss some of the console methods which are available to use and which can increase the productivity of web developers.]]></description><link>https://blog.javarush.dev/8-console-methods-every-javascript-developer-should-know</link><guid isPermaLink="true">https://blog.javarush.dev/8-console-methods-every-javascript-developer-should-know</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[console]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[logging]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Himanshu Pareek]]></dc:creator><pubDate>Sat, 05 Mar 2022 06:45:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1646462469434/FqjE8CNYq.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you are a JavaScript developer, I am sure you have used the <code>console.log()</code> method. But, there are some other methods as well provided by the console that can make your life easier. Let's discuss some of them one by one.</p>
<h1 id="heading-consolelog">console.log()</h1>
<p>The <code>console.log</code> method is used to print a string, number, boolean, object, or any type of data to the console. See the following example:</p>
<pre><code>const person = {
    "id": "123",
    "name": "Bob",
    "age": <span class="hljs-number">25</span>
};
console.log(person); // prints { id: <span class="hljs-string">'123'</span>, <span class="hljs-type">name</span>: <span class="hljs-string">'Bob'</span>, age: <span class="hljs-number">25</span> }
</code></pre><p>This method supports <strong>string substitutions</strong> and <strong>styling</strong>, which we will discuss at the end of this article.</p>
<h1 id="heading-consoleassert">console.assert()</h1>
<p>The <code>console.assert</code> method is used to check for the validation of data. And if the validation fails, it prints the specified error message to the console. This method also supports string substitutions and styling.</p>
<p>Consider the following example:</p>
<pre><code>const person <span class="hljs-operator">=</span> {
    <span class="hljs-string">"id"</span>: <span class="hljs-string">"123"</span>,
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"Bob"</span>,
    <span class="hljs-string">"age"</span>: <span class="hljs-number">25</span>
};
console.assert(person.age <span class="hljs-operator">&gt;</span> <span class="hljs-number">20</span>, <span class="hljs-string">"You are not old enough"</span>);
console.assert(person.<span class="hljs-built_in">name</span>.<span class="hljs-built_in">length</span> <span class="hljs-operator">&gt;</span> <span class="hljs-number">4</span>, <span class="hljs-string">"%s is short name"</span>, person.<span class="hljs-built_in">name</span>);
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646460999073/0Uy4O_txJ.png" alt="Screenshot 2022-02-12 120515.png" /></p>
<h1 id="heading-consolecount">console.count()</h1>
<p>This method logs the number of times this line has been called with the given label. This is useful if you want to check the number of times a particular function is called with the given parameter. Let's take the example of the <a target="_blank" href="https://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci</a> function.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fib</span> (<span class="hljs-params">n</span>) </span>{
    <span class="hljs-keyword">if</span> (n <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
    <span class="hljs-keyword">if</span> (n <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">1</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
    <span class="hljs-keyword">return</span> fib(n <span class="hljs-operator">-</span> <span class="hljs-number">1</span>) <span class="hljs-operator">+</span> fib(n <span class="hljs-operator">-</span> <span class="hljs-number">2</span>);
}
</code></pre><p>Now, we want to know how many times the <code>fib</code> function is called for different values of <code>n</code> when we want to calculate <code>fib(N)</code>. We can call <code>console.count</code> method and can modify the function as shown below:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fib</span> (<span class="hljs-params">n</span>) </span>{
    console.count(<span class="hljs-string">"fib("</span> <span class="hljs-operator">+</span> n <span class="hljs-operator">+</span> <span class="hljs-string">")"</span>);
    <span class="hljs-keyword">if</span> (n <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
    <span class="hljs-keyword">if</span> (n <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">1</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
    <span class="hljs-keyword">return</span> fib(n <span class="hljs-operator">-</span> <span class="hljs-number">1</span>) <span class="hljs-operator">+</span> fib(n <span class="hljs-operator">-</span> <span class="hljs-number">2</span>);
}
</code></pre><p>Let's call the function <code>fib</code> with <code>n = 3</code> and see the output.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646461493898/Pg93IVo4q.png" alt="Screenshot 2022-02-12 143206.png" />
As we can see the final value of label <code>fib(1)</code> is <code>2</code>. It means <code>fib(1)</code> is called twice when we want to compute <code>fib(3)</code>. You can reset the count using <code>console.countReset(label)</code> method, where count of the <code>label</code> will become <code>0</code>.</p>
<h1 id="heading-consolegroup">console.group()</h1>
<p>This method is used to create a group with the given label. All the <code>console</code> statements will be placed under this group. To end the group use <code>console.groupEnd()</code> method. Here is an example:</p>
<pre><code>console.group(<span class="hljs-string">"Group 1"</span>);
console.log(<span class="hljs-string">"Item 1 of Group 1"</span>);
console.group(<span class="hljs-string">"Group 1.1"</span>);
console.log(<span class="hljs-string">"Item 1 of Group 1.1"</span>);
console.log(<span class="hljs-string">"Item 2 of Group 1.1"</span>);
console.groupEnd();
console.log(<span class="hljs-string">"Item 2 of group 1"</span>);
console.groupEnd();
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646461680149/0pPw6IJ63.png" alt="Screenshot 2022-02-12 143817.png" />
You can expand and collapse these groups. By default, all the groups are expanded. If you want a group to be collapsed by default, use <code>console.groupCollapsed()</code> method as shown below:</p>
<pre><code>console.groupCollapsed(<span class="hljs-string">"Group 1"</span>);
console.log(<span class="hljs-string">"Item 1 of Group 1"</span>);
console.log(<span class="hljs-string">"Item 2 of group 1"</span>);
console.groupEnd();
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646461761338/H5lDOFi83.png" alt="Screenshot 2022-02-12 144142.png" /></p>
<h1 id="heading-consoletable">console.table()</h1>
<p>If you want to see the array of objects in tabular form, use this method. For example:</p>
<pre><code><span class="hljs-string">const</span> <span class="hljs-string">students</span> <span class="hljs-string">=</span> [
    { <span class="hljs-attr">id:</span> <span class="hljs-string">"123"</span>, <span class="hljs-attr">name:</span> <span class="hljs-string">"Bob"</span>, <span class="hljs-attr">age:</span> <span class="hljs-number">25</span> },
    { <span class="hljs-attr">id:</span> <span class="hljs-string">"124"</span>, <span class="hljs-attr">name:</span> <span class="hljs-string">"John"</span>, <span class="hljs-attr">age:</span> <span class="hljs-number">23</span>, <span class="hljs-attr">key1:</span> <span class="hljs-string">"Value 1"</span> }
]<span class="hljs-string">;</span>
<span class="hljs-string">console.table(students);</span>
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646461838649/A7GlXwo-Z.png" alt="Screenshot 2022-02-12 144513.png" /></p>
<h1 id="heading-consoletime">console.time()</h1>
<p>This method is used to measure the time taken to execute some piece of code. <code>console.time(label)</code> starts the timer for <code>label</code> and <code>console.timeEnd(label)</code> stops the timer and displays the time taken. Let's say we want to calculate the time taken to compute the 20th Fibonacci number. We can do the following:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fib</span> (<span class="hljs-params">n</span>) </span>{
    <span class="hljs-keyword">if</span> (n <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
    <span class="hljs-keyword">if</span> (n <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">1</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
    <span class="hljs-keyword">return</span> fib(n <span class="hljs-operator">-</span> <span class="hljs-number">1</span>) <span class="hljs-operator">+</span> fib(n <span class="hljs-operator">-</span> <span class="hljs-number">2</span>);
}
console.time(<span class="hljs-string">"fib_20"</span>);
const fib_20 <span class="hljs-operator">=</span> fib(<span class="hljs-number">20</span>);
console.timeEnd(<span class="hljs-string">"fib_20"</span>);
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646461960984/Zd9Zgp2Fm.png" alt="Screenshot 2022-02-12 145104.png" /></p>
<h1 id="heading-consoletrace">console.trace()</h1>
<p>This method prints the stack track of method calls at that point. Take a look at the following example:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bar</span>(<span class="hljs-params">n</span>) </span>{
    console.trace();
    <span class="hljs-keyword">return</span> n <span class="hljs-operator">+</span> <span class="hljs-number">1</span>;
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params">n</span>) </span>{
    <span class="hljs-keyword">return</span> bar(n);
}
foo(<span class="hljs-number">10</span>);
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646462038828/4PMQrFxxJ.png" alt="Screenshot 2022-02-12 145434.png" /></p>
<h1 id="heading-string-substitution">String Substitution</h1>
<p>We can use the following substitution strings which will be replaced by the next set of arguments:</p>
<ol>
<li><code>%o</code> or <code>%O</code> for an object.</li>
<li><code>%d</code> or <code>%i</code> for an integer.</li>
<li><code>%f</code> for a floating-point value.</li>
<li><code>%s</code> for a string.</li>
</ol>
<p>For example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646462184307/ljz3dy8Fk.png" alt="Screenshot 2022-02-12 150559.png" /></p>
<h1 id="heading-styling-the-output">Styling the output</h1>
<p>You can use the <code>%c</code> directive to style the text in the console. The text after the <code>%c</code> directive will be formatted. We can use multiple <code>%c</code> directives as well in a single <code>log</code> statement. For example:</p>
<pre><code>console<span class="hljs-selector-class">.log</span>("This is %cwhite text in green <span class="hljs-attribute">background</span>", "<span class="hljs-attribute">color</span>: white; <span class="hljs-attribute">background-color</span>: green;");
console<span class="hljs-selector-class">.log</span>("This is %cblue text %cred text", "<span class="hljs-attribute">color</span>: blue;", "<span class="hljs-attribute">color</span>: red;", " <span class="hljs-attribute">normal</span> text");
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646462260619/6nFtJwoXZ.png" alt="Screenshot 2022-02-12 151300.png" /></p>
<h1 id="heading-summary">Summary</h1>
<p>There are more methods related to <code>console</code> available. You can see a list of all the methods <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/console">here</a>.</p>
<p>Thank you 🙏 for the time to read this article. If you have any feedback, suggestions or if you want to point out any errors, feel free to comment below. Keep learning 📚...</p>
]]></content:encoded></item><item><title><![CDATA[Serving Angular App from Spring Boot Server for Secure 🔐 OAuth Flow - Part 2 ✌]]></title><description><![CDATA[Learn how to use the client-server as a proxy to make API requests from the angular app to the resource server]]></description><link>https://blog.javarush.dev/serving-angular-app-from-spring-boot-server-for-secure-oauth-flow-part-2</link><guid isPermaLink="true">https://blog.javarush.dev/serving-angular-app-from-spring-boot-server-for-secure-oauth-flow-part-2</guid><category><![CDATA[Springboot]]></category><category><![CDATA[Angular]]></category><category><![CDATA[APIs]]></category><category><![CDATA[Java]]></category><category><![CDATA[authentication]]></category><dc:creator><![CDATA[Himanshu Pareek]]></dc:creator><pubDate>Mon, 03 Jan 2022 11:14:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1641116195773/R0HRg7abX.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In <a target="_blank" href="https://hpareek.hashnode.dev/serving-angular-app-from-spring-boot-server-for-secure-oauth-flow">the previous part</a> of this series, we served an angular app from a Spring Boot server. We also used authentication on the server-side so that all the credentials and the access token are stored at a secure backend. The browser or Angular app does not have access to the access token. So, how do we make API requests to the Resource Server from the angular app which requires access tokens to be present in the request 🤔? Let's discuss it.</p>
<h2 id="heading-what-you-should-have">What you should have? 🛠</h2>
<ol>
<li>Some familiarity with <a target="_blank" href="https://angular.io/"><strong>Angular</strong></a> and <a target="_blank" href="https://spring.io/projects/spring-boot"><strong>Spring Boot</strong></a>.</li>
<li>A <strong>resource server</strong> is running on port <code>8080</code>. If you followed <a target="_blank" href="https://hpareek.hashnode.dev/create-oauth2-api-server-using-spring-boot">the second part</a> and <a target="_blank" href="https://hpareek.hashnode.dev/handling-authentication-and-authorization-failures-in-api-server">the third part</a> of the series, then run that server again. Otherwise, follow these steps:<ul>
<li>Clone / download <a target="_blank" href="https://github.com/himanshu-pareek/OAuth2SPA/tree/05_Serve_Ang_App_from_backend_OAuth2_flow">this repository</a>.</li>
<li>Go to <code>OAuth2DemoResourceServer</code> directory.</li>
<li>Update <code>src/main/resources/application.properties</code> file with the correct values.</li>
<li>Run <code>./mvnw spring-boot:run</code> command to start the server.
The server should be running on port <code>8080</code>.</li>
</ul>
</li>
<li><p>Spring Boot Server created in <a target="_blank" href="https://hpareek.hashnode.dev/serving-angular-app-from-spring-boot-server-for-secure-oauth-flow">the previous part</a>. I call it <strong>Client Server</strong> throughout the article. Or, follow the below steps:</p>
<ul>
<li>Clone / download <a target="_blank" href="https://github.com/himanshu-pareek/OAuth2SPA/tree/05_Serve_Ang_App_from_backend_OAuth2_flow">this repository</a>.</li>
<li>Go to <code>oauth2clientserver</code> directory.</li>
<li>Update <code>src/main/resources/application.properties</code> file with the correct values.</li>
<li>Run <code>./mvnw spring-boot:run</code> command to start the server. In another terminal, run <code>./ng build --watch</code> to build the angular app whenever there is any change in related files.</li>
</ul>
</li>
<li><p>You must have a scope named <code>authors</code> in your Identity Provider. I have already explained how to create scope in Okta in <a target="_blank" href="https://hpareek.hashnode.dev/handling-authentication-and-authorization-failures-in-api-server">this article</a>.</p>
</li>
</ol>
<p>The server should run on port <code>8081</code>. If we try to access <code>http://localhost:8081</code> in a private browser window, we see a page for authentication. After successful authentication, we see a home page created using angular.</p>
<blockquote>
<p>Don't be confused between Resource Server and Client-Server. Both are created using Spring Boot. The Resource Server is the one that holds all the resources and exposes some APIs to be consumed by other applications. The client Server is the one that renders the angular app after successful authentication.</p>
</blockquote>
<h2 id="heading-the-idea-access-token-andamp-cookie">The Idea 💡 - Access Token 🔑 &amp; Cookie 🍪</h2>
<p>First, let's see what happens when we render an angular application using a client-server. When the user tries to access the app, the client-server redirects her to Identity Provider's website to log in since we made it an OAuth2 client. After successful login, the client-server sends another request to the Identity Provider and gets the access token. Then, the server stores the access token within itself and renders the angular application. It also sends an HttpOnly cookie 🍪corresponding to the access token. Since the cookie is HttpOnly, no script can read it. Thus, it is nearly impossible to steal the cookie.</p>
<p>Now, let's see how to send the access token to the resource server? The idea is to use the client-server as a proxy for each request to the resource server. Whatever request we want to send to the resource server from the angular app, we send it to the client-server itself. Since we got a cookie from the client-server, it is sent along with each request to the same client-server. And then the client-server will pick the access token corresponding to the cookie which is received from the angular app. Then, the client-server sends the request to the resource server with the access token. Below image shows the flow:
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640883409785/gfVdeougz.jpeg" alt="OAuth flow with Client, Authorization and Resource Server.jpg" /></p>
<h2 id="heading-authenticated-user">Authenticated User 🧑</h2>
<p>First, let's try to fetch the details of the currently authenticated user. We will create a controller in the client-server and will try to send a request to that endpoint from the angular app. </p>
<h3 id="heading-changes-in-client-server">Changes in Client Server</h3>
<p>We can use <strong><a target="_blank" href="https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/core/annotation/AuthenticationPrincipal.html">AuthenticationPrincipal</a></strong> from spring. <code>AuthenticationPrincipal</code> annotation is used to get the currently authenticated user in spring. Create a new package called <code>user</code> inside the default package of the client-server. Then, create a Java class called <code>UserController.java</code> inside the <code>user</code> package. Replace the content of the <code>UserController.java</code> file with the following code:</p>
<pre><code>package dev.hashnode.hpareek.oauth2clientserver.user;

<span class="hljs-keyword">import</span> <span class="hljs-title">java</span>.<span class="hljs-title">util</span>.<span class="hljs-title">HashMap</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">java</span>.<span class="hljs-title">util</span>.<span class="hljs-title">Map</span>;

<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">security</span>.<span class="hljs-title">core</span>.<span class="hljs-title">annotation</span>.<span class="hljs-title">AuthenticationPrincipal</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">security</span>.<span class="hljs-title">oauth2</span>.<span class="hljs-title">core</span>.<span class="hljs-title">user</span>.<span class="hljs-title">OAuth2User</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">web</span>.<span class="hljs-title">bind</span>.<span class="hljs-title">annotation</span>.<span class="hljs-title">GetMapping</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">web</span>.<span class="hljs-title">bind</span>.<span class="hljs-title">annotation</span>.<span class="hljs-title">RequestMapping</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">web</span>.<span class="hljs-title">bind</span>.<span class="hljs-title">annotation</span>.<span class="hljs-title">RestController</span>;

@RestController
@RequestMapping(<span class="hljs-string">"/users"</span>)
<span class="hljs-keyword">public</span> class UserController {

    @GetMapping(<span class="hljs-string">"/self"</span>)
    <span class="hljs-keyword">public</span> Map<span class="hljs-operator">&lt;</span>String, String<span class="hljs-operator">&gt;</span> getAuthenticatedUser(
        @AuthenticationPrincipal OAuth2User principal
    ) {
        Map<span class="hljs-operator">&lt;</span>String, String<span class="hljs-operator">&gt;</span> map <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> HashMap<span class="hljs-operator">&lt;</span><span class="hljs-operator">&gt;</span>();
        map.put(<span class="hljs-string">"name"</span>, principal.getAttribute(<span class="hljs-string">"given_name"</span>));
        map.put(<span class="hljs-string">"email"</span>, principal.getAttribute(<span class="hljs-string">"email"</span>));
        map.put(<span class="hljs-string">"id"</span>, principal.getName());
        <span class="hljs-keyword">return</span> map;
    }
}
</code></pre><p>Let's break the above code:</p>
<ul>
<li><code>getAuthenticatedUser</code> handles the requests to the <code>/users/self</code> endpoint.</li>
<li><code>AuthenticationPrincipal</code> annotation returns the currently authenticated user. Since we are using <code>OAuth2</code> for authentication, we receive the <code>principal</code> of type <code>OAuth2User</code>.</li>
<li><code>principal</code> has many attributes in it. We are accessing a few of these.</li>
</ul>
<p>That's it. Now, whenever an authenticated user sends a request to the <code>/users/self</code> endpoint, the server responds with her <code>name</code>, <code>email</code>, and <code>id</code>. Now, restart the client-server. Now, let's make changes to the angular app.</p>
<h3 id="heading-changes-in-the-angular-app">Changes in the Angular App</h3>
<p>To make, API calls in any angular app, we need to import <code>HttpClientModule</code>. Add these 2 lines in the <code>app.modules.ts</code> file:</p>
<pre><code><span class="hljs-comment">// ... other imports ... </span>
<span class="hljs-keyword">import</span> { <span class="hljs-title">HttpClientModule</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">"@angular/common/http"</span>;  <span class="hljs-comment">// 1. Import HttpClientModule</span>
@NgModule({
  ...
  imports: [
    ...
    HttpClientModule,  <span class="hljs-comment">// 2. Add HttpClientModule to imports array</span>
    ...
  ],
  ...
})
...
</code></pre><p>Replace the content of the <code>app.component.ts</code> file with the following code:</p>
<pre><code><span class="hljs-keyword">import</span> { <span class="hljs-title">HttpClient</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'@angular/common/http'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title">Component</span>, <span class="hljs-title">OnInit</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'@angular/core'</span>;

@Component({
  selector: <span class="hljs-string">'app-root'</span>,
  templateUrl: <span class="hljs-string">'./app.component.html'</span>,
  styleUrls: [<span class="hljs-string">'./app.component.css'</span>]
})
export class AppComponent implements OnInit {
  title <span class="hljs-operator">=</span> <span class="hljs-string">'My Angular App'</span>;
  authenticatedUser : {email: <span class="hljs-keyword">string</span>, name: <span class="hljs-keyword">string</span>, id: <span class="hljs-keyword">string</span>} <span class="hljs-operator">|</span> undefined;

  <span class="hljs-function"><span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> _httpClient: HttpClient</span>) </span>{}

  ngOnInit(): void {
    <span class="hljs-built_in">this</span>.getUsername();
  }

  getUsername() {
    <span class="hljs-built_in">this</span>._httpClient.get(<span class="hljs-string">"/users/self"</span>).subscribe(response <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
      <span class="hljs-built_in">this</span>.authenticatedUser <span class="hljs-operator">=</span> response <span class="hljs-keyword">as</span> {email: <span class="hljs-keyword">string</span>, name: <span class="hljs-keyword">string</span>, id: <span class="hljs-keyword">string</span>};
    });
  }
}
</code></pre><p><code>ngOnInit</code> method runs on initialization of the component. <code>getUsername</code> method sends a request to the <code>/users/self</code> endpoint and assigns the response to <code>authenticatedUser</code> variable. If you notice, we are not specifying any domain to make an API call. Since we are serving the angular app from the client-server, the domain of the angular app is the same as the client-server. So, we don't need to specify the domain for requests to the client-server. Now, let's change the contents of the <code>app.component.html</code> file to display the user information:</p>
<pre><code><span class="hljs-operator">&lt;</span>h3<span class="hljs-operator">&gt;</span>{{title}}<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>h3<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>div <span class="hljs-operator">*</span>ngIf<span class="hljs-operator">=</span><span class="hljs-string">"authenticatedUser"</span><span class="hljs-operator">&gt;</span>
  Email <span class="hljs-operator">-</span> {{authenticatedUser.email}} <span class="hljs-operator">&lt;</span>br <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
  Name <span class="hljs-operator">-</span> {{authenticatedUser.<span class="hljs-built_in">name</span>}} <span class="hljs-operator">&lt;</span>br <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
  Id <span class="hljs-operator">-</span> {{authenticatedUser.id}} <span class="hljs-operator">&lt;</span>br <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
</code></pre><p>Now, since the <code>./ng build --watch</code> command is running. After saving the above 3 files, the angular app is built automatically. Visit <code>http://localhost:8081</code> in any private browser window. After successful login, we see a page with the following content:
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640942365589/gL-Adkmel.png" alt="Home page with user information" /></p>
<h2 id="heading-making-api-calls-to-the-resource-server">Making API calls to the Resource Server</h2>
<p>Our resource server already exposes an API endpoint <code>/authors/all</code>, which returns a list of <code>3</code> authors. This endpoint needs the incoming request to be authenticated. The request must have an access token with the <code>authors</code> scope. This is accomplished by <code>@PreAuthorize("hasAuthority('SCOPE_authors')")</code> annotation on method <code>getAuthors()</code> in the file <code>controllers/AuthorController.java</code> of the resource server. We can not make the request straight to the resource server from the angular app since the app does not know about the access token. So, the angular app sends requests to the client-server (cookie 🍪 is automatically included), and the client-server sends the request to the resource-server with the access token 🔑. Since the access token must have <code>authors</code> scope in it, add that in the scop list for the client-server. Modify the <code>application.properties</code> file of the client-server as shown below.</p>
<pre><code>spring.security.oauth2.client.registration.okta.scope=openid,profile,email (Remove <span class="hljs-built_in">this</span>)
spring.security.oauth2.client.registration.okta.scope=openid,profile,email,authors (Add <span class="hljs-built_in">this</span>)
</code></pre><p>Now, whenever the user login to the app, she is asked to grant access to the <code>authors</code> scope.
<strong>WebClient</strong> is used to make rest requests from a Spring Boot Server. But, we need to configure the WebClient to include the access token while making API requests to the resource server.</p>
<h3 id="heading-configuring-webclient-on-client-server">Configuring WebClient on Client-Server 🌐</h3>
<p>To use <code>WebClient</code>, add <code>spring-boot-starter-webflux</code> dependency under <code>dependencies</code> section of the client-server.</p>
<pre><code><span class="hljs-operator">&lt;</span>dependencies<span class="hljs-operator">&gt;</span>
        ...
        <span class="hljs-operator">&lt;</span>dependency<span class="hljs-operator">&gt;</span>
            <span class="hljs-operator">&lt;</span>groupId<span class="hljs-operator">&gt;</span>org.springframework.boot&lt;<span class="hljs-operator">/</span>groupId<span class="hljs-operator">&gt;</span>
            <span class="hljs-operator">&lt;</span>artifactId<span class="hljs-operator">&gt;</span>spring<span class="hljs-operator">-</span>boot<span class="hljs-operator">-</span>starter<span class="hljs-operator">-</span>webflux<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>artifactId<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>dependency<span class="hljs-operator">&gt;</span>
        ...
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>dependencies<span class="hljs-operator">&gt;</span>
</code></pre><p>Create a package <code>security</code> inside the default package for the client-server. Create a java class <code>SecurityConfiguration.java</code> inside the <code>security</code> package and replace the code of the file with the following code:</p>
<pre><code>package dev.hashnode.hpareek.oauth2clientserver.security;

<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">context</span>.<span class="hljs-title">annotation</span>.<span class="hljs-title">Bean</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">context</span>.<span class="hljs-title">annotation</span>.<span class="hljs-title">Configuration</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">security</span>.<span class="hljs-title">oauth2</span>.<span class="hljs-title">client</span>.<span class="hljs-title">OAuth2AuthorizedClientManager</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">security</span>.<span class="hljs-title">oauth2</span>.<span class="hljs-title">client</span>.<span class="hljs-title">OAuth2AuthorizedClientProvider</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">security</span>.<span class="hljs-title">oauth2</span>.<span class="hljs-title">client</span>.<span class="hljs-title">OAuth2AuthorizedClientProviderBuilder</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">security</span>.<span class="hljs-title">oauth2</span>.<span class="hljs-title">client</span>.<span class="hljs-title">registration</span>.<span class="hljs-title">ClientRegistrationRepository</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">security</span>.<span class="hljs-title">oauth2</span>.<span class="hljs-title">client</span>.<span class="hljs-title">web</span>.<span class="hljs-title">DefaultOAuth2AuthorizedClientManager</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">security</span>.<span class="hljs-title">oauth2</span>.<span class="hljs-title">client</span>.<span class="hljs-title">web</span>.<span class="hljs-title">OAuth2AuthorizedClientRepository</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">security</span>.<span class="hljs-title">oauth2</span>.<span class="hljs-title">client</span>.<span class="hljs-title">web</span>.<span class="hljs-title">reactive</span>.<span class="hljs-title"><span class="hljs-keyword">function</span></span>.<span class="hljs-title">client</span>.<span class="hljs-title">ServletOAuth2AuthorizedClientExchangeFilterFunction</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">web</span>.<span class="hljs-title">reactive</span>.<span class="hljs-title"><span class="hljs-keyword">function</span></span>.<span class="hljs-title">client</span>.<span class="hljs-title">WebClient</span>;

@Configuration
<span class="hljs-keyword">public</span> class SecurityConfiguration {

    @Bean
    <span class="hljs-keyword">public</span> OAuth2AuthorizedClientManager authorizedClientManager (
        ClientRegistrationRepository clientRegistrationRepository,
        OAuth2AuthorizedClientRepository oAuth2AuthorizedClientRepository
    ) {
        OAuth2AuthorizedClientProvider authorizedClientProvider <span class="hljs-operator">=</span>
            OAuth2AuthorizedClientProviderBuilder.builder()
                .clientCredentials()
                .build();

        DefaultOAuth2AuthorizedClientManager authorizedClientManager <span class="hljs-operator">=</span>
            <span class="hljs-keyword">new</span> DefaultOAuth2AuthorizedClientManager(
                clientRegistrationRepository,
                oAuth2AuthorizedClientRepository
            );
        authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
        <span class="hljs-keyword">return</span> authorizedClientManager;
    }

    @Bean
    WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
        ServletOAuth2AuthorizedClientExchangeFilterFunction oAuth2Client <span class="hljs-operator">=</span>
            <span class="hljs-keyword">new</span> ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
        oAuth2Client.setDefaultClientRegistrationId(<span class="hljs-string">"keycloak"</span>);
        <span class="hljs-keyword">return</span> WebClient.builder()
            .apply(oAuth2Client.oauth2Configuration())
            .build();
    }
}
</code></pre><p>In the above code, we configure an instance of <code>WebClient</code> such that it will send <code>access_token🔑</code> with each request. That's how the resource server gets to know about the user who is sending the requests. In the next step, we use this Bean of <code>WebClient</code> using <code>Autowired</code> annotation.</p>
<h3 id="heading-make-request-from-client-server-to-resource-server">Make Request from Client-Server to Resource Server</h3>
<p>Create another package <code>author</code> for the client-server. Create a file <code>AuthorController.java</code> inside the <code>author</code> package and replace the content of the file with the following code:</p>
<pre><code>package dev.hashnode.hpareek.oauth2clientserver.author;

<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">beans</span>.<span class="hljs-title">factory</span>.<span class="hljs-title">annotation</span>.<span class="hljs-title">Autowired</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">http</span>.<span class="hljs-title">MediaType</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">web</span>.<span class="hljs-title">bind</span>.<span class="hljs-title">annotation</span>.<span class="hljs-title">GetMapping</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">web</span>.<span class="hljs-title">bind</span>.<span class="hljs-title">annotation</span>.<span class="hljs-title">RequestMapping</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">web</span>.<span class="hljs-title">bind</span>.<span class="hljs-title">annotation</span>.<span class="hljs-title">RestController</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">web</span>.<span class="hljs-title">reactive</span>.<span class="hljs-title"><span class="hljs-keyword">function</span></span>.<span class="hljs-title">client</span>.<span class="hljs-title">WebClient</span>;

<span class="hljs-keyword">import</span> <span class="hljs-title">reactor</span>.<span class="hljs-title">core</span>.<span class="hljs-title">publisher</span>.<span class="hljs-title">Mono</span>;

@RestController
@RequestMapping(<span class="hljs-string">"/authors"</span>)
<span class="hljs-keyword">public</span> class AuthorController {

    @Autowired
    <span class="hljs-keyword">private</span> WebClient webClient;

    @GetMapping(<span class="hljs-string">"/all"</span>)
    <span class="hljs-keyword">public</span> Mono<span class="hljs-operator">&lt;</span>Object<span class="hljs-operator">&gt;</span> all() throws Throwable {
        <span class="hljs-keyword">return</span> webClient.get()
                .uri(<span class="hljs-string">"http://localhost:8080/authors/all"</span>)
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .bodyToMono(Object.class);
    }
}
</code></pre><p>Above class <code>AuthorController</code> uses <code>Autowired</code> annotation for <code>WebClient</code>. So, it uses the <code>WebClient</code> which we configured in the previous step because we want to send the access token to the resource server.</p>
<h3 id="heading-make-a-request-from-angular-app-to-client-server">Make a request from Angular App to Client-Server</h3>
<p>Create a new method <code>getAuthors</code> inside <code>app.component.ts</code>, which sends an API request to the <code>/authors/all</code> endpoint and prints the result to the <code>console</code>. Also, in <code>ngOnInit</code> method call the <code>getAuthors</code> method as well along with <code>getUsername</code> method.</p>
<pre><code>...
export class AppComponent implements OnInit {
  ...

  ngOnInit(): void {
    <span class="hljs-built_in">this</span>.getUsername();
    <span class="hljs-built_in">this</span>.getAuthors();
  }
  ...

  getAuthors() {
    <span class="hljs-built_in">this</span>._httpClient.get(<span class="hljs-string">"/authors/all"</span>).subscribe(response <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
      console.log(response);
    });
  }
}
</code></pre><p>Since <code>./ng build --watch</code> command is running, the changes in the above files are picked up by Angular CLI automatically and the angular app is built again.</p>
<h3 id="heading-see-it-in-action">See it in Action 🚀</h3>
<p>Now, visit <code>localhost:8081</code> in a private window. And after successful login, you are presented with a screen to allow the app to use <code>authors</code> scope. Click on <strong>Allow Button</strong>. We can see the details of the user on the screen same as before. Open the <strong>Console</strong> tab and we can see the response from the server printed as below:
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1641113797879/BeVeYW1GF.png" alt="User details in browser window and Author list in Console" /></p>
<h2 id="heading-summary">Summary</h2>
<p>Source code for the tutorial can be found <a target="_blank" href="https://github.com/himanshu-pareek/OAuth2SPA/tree/06-Making-Requests-From-Angular-App-To-Resource-Server">here 💻</a>. In this article, we sent requests from the angular app to the client-server with the cookie 🍪. That's how the client-server recognizes the user of the app. Then it generates the corresponding access token. We configured the <code>WebClient</code> in the client-server to send the access token 🔑 with each API request. And then we sent the request from the client-server to the resource server. That's the overall flow of the requests from the angular app to the resource server. This article is probably the last of the series. But, you never know 😉. Please, consider giving your feedback. Also, you can recommend me on topic for my next article in the comment section. Until then, stay safe 😷 and keep learning.</p>
]]></content:encoded></item><item><title><![CDATA[Serving Angular App from Spring Boot Server for Secure 🔐 OAuth Flow]]></title><description><![CDATA[Learn to use OAuth on Spring Boot Server and to serve Angular app post successful authentication]]></description><link>https://blog.javarush.dev/serving-angular-app-from-spring-boot-server-for-secure-oauth-flow</link><guid isPermaLink="true">https://blog.javarush.dev/serving-angular-app-from-spring-boot-server-for-secure-oauth-flow</guid><category><![CDATA[Springboot]]></category><category><![CDATA[Angular]]></category><category><![CDATA[authentication]]></category><category><![CDATA[Security]]></category><category><![CDATA[Java]]></category><dc:creator><![CDATA[Himanshu Pareek]]></dc:creator><pubDate>Tue, 28 Dec 2021 12:51:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1640681229131/7UR0bm_XA.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In <a target="_blank" href="https://hpareek.hashnode.dev/authentication-using-oauth2-openid-connect-in-angular-single-page-application">the first part</a> of the series, we built an angular app that uses OAuth2 for user authentication. In <a target="_blank" href="https://hpareek.hashnode.dev/potential-risks-of-using-oauth2-in-single-page-applications">the fourth part</a>, we discussed some of the limitations of this approach. In this article, we will create a spring boot server that will authenticate the users using OAuth flow and then will serve the angular application. That way we don't need to store any credentials or access tokens in the browser. Thus, this is a more secure method for OAuth flow. Some familiarity with <a target="_blank" href="https://spring.io/projects/spring-boot">Spring Boot</a> and <a target="_blank" href="https://angular.io/">Angular</a> is required to follow along with this article. If you are using Windows Operating System, then you should use any shell that allows Unix commands inside Windows (<a target="_blank" href="https://git-scm.com/downloads">Git Bash</a> for example). Now, let's start coding 👨‍💻</p>
<h3 id="heading-serve-angular-app-using-spring-boot">Serve Angular App using Spring Boot</h3>
<p>First, let's try to serve an angular application using the spring boot server. After that, we will add security to it. The following steps are mentioned <a target="_blank" href="https://github.com/dsyer/spring-boot-angular">here</a> by <a target="_blank" href="https://github.com/dsyer">Dave Syer</a>.</p>
<h4 id="heading-create-a-spring-boot-application">Create a Spring Boot Application</h4>
<p>First of all, create a spring boot application with <code>web</code> dependency. If your IDE has integration to create it, use that or use the following command:</p>
<pre><code>curl start.spring.io/starter.tgz <span class="hljs-operator">-</span>d dependencies<span class="hljs-operator">=</span>web <span class="hljs-operator">|</span> tar <span class="hljs-operator">-</span>zxvf <span class="hljs-operator">-</span>
./mvnw install
</code></pre><p>Now, we will install <code>npm</code> locally in the project in order to install <a target="_blank" href="https://angular.io/cli">Angular CLI</a>.</p>
<h4 id="heading-install-npm-locally">Install NPM Locally</h4>
<p><a target="_blank" href="https://github.com/eirslett/frontend-maven-plugin">Frontend Maven Plugin</a> lets you install <a target="_blank" href="https://nodejs.org/en/">Node</a> / <a target="_blank" href="https://www.npmjs.com/">NPM</a> locally for your project, install dependencies with NPM, and much more. Add this plugin to the project and specify the related commands in the <code>pom.xml</code> file.</p>
<pre><code>    <span class="hljs-operator">&lt;</span>build<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>plugins<span class="hljs-operator">&gt;</span>
            <span class="hljs-operator">&lt;</span>plugin<span class="hljs-operator">&gt;</span>
                <span class="hljs-operator">&lt;</span>groupId<span class="hljs-operator">&gt;</span>org.springframework.boot&lt;<span class="hljs-operator">/</span>groupId<span class="hljs-operator">&gt;</span>
                <span class="hljs-operator">&lt;</span>artifactId<span class="hljs-operator">&gt;</span>spring<span class="hljs-operator">-</span>boot<span class="hljs-operator">-</span>maven<span class="hljs-operator">-</span>plugin<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>artifactId<span class="hljs-operator">&gt;</span>
            <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>plugin<span class="hljs-operator">&gt;</span>

            <span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span> Frontend Maven Plugin <span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">&gt;</span>
            <span class="hljs-operator">&lt;</span>plugin<span class="hljs-operator">&gt;</span>
                <span class="hljs-operator">&lt;</span>groupId<span class="hljs-operator">&gt;</span>com.github.eirslett&lt;<span class="hljs-operator">/</span>groupId<span class="hljs-operator">&gt;</span>
                <span class="hljs-operator">&lt;</span>artifactId<span class="hljs-operator">&gt;</span>frontend<span class="hljs-operator">-</span>maven<span class="hljs-operator">-</span>plugin<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>artifactId<span class="hljs-operator">&gt;</span>
                <span class="hljs-operator">&lt;</span>version<span class="hljs-operator">&gt;</span><span class="hljs-number">1.6</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>version<span class="hljs-operator">&gt;</span>
                <span class="hljs-operator">&lt;</span>configuration<span class="hljs-operator">&gt;</span>
                    <span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span> Node Version to use <span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">&gt;</span>
                    <span class="hljs-operator">&lt;</span>nodeVersion<span class="hljs-operator">&gt;</span>v14<span class="hljs-number">.17</span><span class="hljs-number">.6</span><span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>nodeVersion<span class="hljs-operator">&gt;</span>
                <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>configuration<span class="hljs-operator">&gt;</span>
                <span class="hljs-operator">&lt;</span>executions<span class="hljs-operator">&gt;</span>
                    <span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span> Command to install node and npm locally in the project <span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">&gt;</span>
                    <span class="hljs-operator">&lt;</span>execution<span class="hljs-operator">&gt;</span>
                        <span class="hljs-operator">&lt;</span>id<span class="hljs-operator">&gt;</span>install<span class="hljs-operator">-</span>npm<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>id<span class="hljs-operator">&gt;</span>
                        <span class="hljs-operator">&lt;</span>goals<span class="hljs-operator">&gt;</span>
                            <span class="hljs-operator">&lt;</span>goal<span class="hljs-operator">&gt;</span>install<span class="hljs-operator">-</span>node<span class="hljs-operator">-</span>and<span class="hljs-operator">-</span>npm<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>goal<span class="hljs-operator">&gt;</span>
                        <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>goals<span class="hljs-operator">&gt;</span>
                    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>execution<span class="hljs-operator">&gt;</span>
                <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>executions<span class="hljs-operator">&gt;</span>
            <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>plugin<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>plugins<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>build<span class="hljs-operator">&gt;</span>
</code></pre><p>And then run the following command to apply the changes.</p>
<pre><code>./mvnw generate<span class="hljs-operator">-</span>resources
</code></pre><p>For the first time, it will take some time. But later on, this step won't take much time.</p>
<h4 id="heading-install-angular-cli">Install Angular CLI</h4>
<p>We use <strong>Angular CLI</strong> to create Angular applications which can be installed using <code>npm</code> which we installed in the previous step. Create a file called <code>npm</code> with the following content:</p>
<pre><code><span class="hljs-meta">#!/bin/sh</span>
<span class="hljs-built_in">cd</span> $(dirname <span class="hljs-variable">$0</span>)
PATH=<span class="hljs-string">"<span class="hljs-variable">$PWD</span>/node/"</span>:<span class="hljs-variable">$PATH</span>
node <span class="hljs-string">"node/node_modules/npm/bin/npm-cli.js"</span> <span class="hljs-string">"<span class="hljs-variable">$@</span>"</span>
</code></pre><p>And then, run the following command to make the file executable:</p>
<pre><code><span class="hljs-keyword">chmod</span> +<span class="hljs-keyword">x</span> npm
</code></pre><p>This wrapper allows us to use local <code>node</code> and <code>npm</code> for the app instead of the ones which are installed on the system. Then, run the following command to install the Angular CLI:</p>
<pre><code>./npm install @angular<span class="hljs-operator">/</span>cli
</code></pre><p>Now, create similar wrappers for Angular CLI as well. Create a file called <code>ng</code> with the following content:</p>
<pre><code><span class="hljs-meta">#!/bin/sh</span>
<span class="hljs-built_in">cd</span> $(dirname <span class="hljs-variable">$0</span>)
PATH=<span class="hljs-string">"<span class="hljs-variable">$PWD</span>/node/"</span>:<span class="hljs-string">"<span class="hljs-variable">$PWD</span>"</span>:<span class="hljs-variable">$PATH</span>
node_modules/@angular/cli/bin/ng.js <span class="hljs-string">"<span class="hljs-variable">$@</span>"</span>
</code></pre><p>Then, run the following command to make it executable:</p>
<pre><code><span class="hljs-keyword">chmod</span> +<span class="hljs-keyword">x</span> ng
</code></pre><p>To test the wrapper, run the following commands:</p>
<pre><code>./ng <span class="hljs-operator">-</span><span class="hljs-operator">-</span>version
</code></pre><p>It prints versions of Node and Angular CLI.</p>
<h4 id="heading-create-an-angular-app">Create an Angular App</h4>
<p>We can either create a new angular app or can pull any existing app. Let's create a new one. We use Angular CLI to create an angular app. Run the following command (inside the spring boot project):</p>
<pre><code>./ng <span class="hljs-keyword">new</span> spa
</code></pre><p>This creates a new angular app inside the spring boot project. Follow these steps to move this app to the root:</p>
<ol>
<li>Copy the content of <code>spa/.gitignore</code> file and paste it at the bottom of <code>.gitignore</code> file.<pre><code>cat spa<span class="hljs-operator">/</span>.gitignore <span class="hljs-operator">&gt;</span><span class="hljs-operator">&gt;</span> .gitignore
</code></pre></li>
<li>Delete <code>spa/node_modules</code>, <code>spa/src/favicon.ico</code>, <code>spa/.git</code> and <code>spa/.gitignore</code>.<pre><code>rm <span class="hljs-operator">-</span>rf spa<span class="hljs-operator">/</span>node<span class="hljs-operator">*</span> spa<span class="hljs-operator">/</span>src<span class="hljs-operator">/</span>favicon.ico spa<span class="hljs-operator">/</span>.gitignore spa<span class="hljs-operator">/</span>.git
</code></pre></li>
<li>Copy everything from <code>spa</code> to root and delete <code>spa</code>.<pre><code>cp -rf spa/<span class="hljs-emphasis">* .
cp spa/.??*</span> .
rm -rf spa
</code></pre></li>
<li>Specify <code>target/classes/static</code> as the output location of <code>ng build</code> command in <code>angula.json</code> file.<pre><code>sed <span class="hljs-operator">-</span>i <span class="hljs-operator">-</span>e <span class="hljs-string">'s,dist/spa,target/classes/static,'</span> angular.json
</code></pre><h4 id="heading-building-the-project">Building the Project</h4>
Add the following execution command in <code>pom.xml</code> to install the required packages:<pre><code><span class="hljs-operator">&lt;</span>execution<span class="hljs-operator">&gt;</span>
 <span class="hljs-operator">&lt;</span>id<span class="hljs-operator">&gt;</span>npm<span class="hljs-operator">-</span>install<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>id<span class="hljs-operator">&gt;</span>
 <span class="hljs-operator">&lt;</span>goals<span class="hljs-operator">&gt;</span>
     <span class="hljs-operator">&lt;</span>goal<span class="hljs-operator">&gt;</span>npm<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>goal<span class="hljs-operator">&gt;</span>
 <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>goals<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>execution<span class="hljs-operator">&gt;</span>
</code></pre>Run <code>./mvnw generate-resources</code> to install the required packages. Now add the following execution as well to compile the angular app during maven build.<pre><code> <span class="hljs-operator">&lt;</span>execution<span class="hljs-operator">&gt;</span>
     <span class="hljs-operator">&lt;</span>id<span class="hljs-operator">&gt;</span>npm<span class="hljs-operator">-</span>build<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>id<span class="hljs-operator">&gt;</span>
     <span class="hljs-operator">&lt;</span>goals<span class="hljs-operator">&gt;</span>
         <span class="hljs-operator">&lt;</span>goal<span class="hljs-operator">&gt;</span>npm<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>goal<span class="hljs-operator">&gt;</span>
     <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>goals<span class="hljs-operator">&gt;</span>
     <span class="hljs-operator">&lt;</span>configuration<span class="hljs-operator">&gt;</span>
         <span class="hljs-operator">&lt;</span>arguments<span class="hljs-operator">&gt;</span>run<span class="hljs-operator">-</span>script build<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>arguments<span class="hljs-operator">&gt;</span>
     <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>configuration<span class="hljs-operator">&gt;</span>
 <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>execution<span class="hljs-operator">&gt;</span>
</code></pre>To stabilize the build, put a <code>^</code> before the version of <code>@angular/cli</code> in <code>package.json</code> file. To build continuously, run <code>./ng build --watch</code> command in a separate terminal window and the angular app will be built whenever any related file changes. We want to run this server on port <code>8081</code>. So, add the following line in <code>application.properties</code> file:<pre><code><span class="hljs-attr">server.port</span>=<span class="hljs-number">8081</span>
</code></pre>Run the Spring Boot app using IDE or <code>./mvnw spring-boot:run</code> command. Then, visit <code>http://localhost:8081</code> in a browser. You should see the Angular starting app.</li>
</ol>
<h4 id="heading-explanation">Explanation</h4>
<p>In <code>angular.json</code> file we have specified <code>target/classes/static</code> as the output path of <code>ng build</code>. We have also defined to run <code>ng build</code> command whenever the spring boot app starts using <strong>Frontend Maven Plugin</strong>. Now, whenever the server starts, it builds the angular app and puts all the files in <code>target/classes/static</code> directory, which is the default directory to be served by the spring application. Now, whenever the user tries to access the spring boot app, <code>index.html</code> file from <code>target/classes/static</code> is served. Let's modify the <code>app.component.html</code> file of the angular app and replace its content with the following code:</p>
<pre><code><span class="hljs-operator">&lt;</span>h3<span class="hljs-operator">&gt;</span>{{title}}<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>h3<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span>div<span class="hljs-operator">&gt;</span>
  Welcome to {{title}}
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
</code></pre><p>Since <code>./ng build --watch</code> command is running. Angular CLI detects the changes in html file and rebuilds the angular app. Now, refresh the browser page and we see the updated page. That's how it works. Now, we are ready to add security 🔐 to the app.</p>
<h3 id="heading-secure-the-app-using-oauth2">Secure the app using OAuth2</h3>
<p>Now, let's make our app an OAuth2 client using <code>spring-boot-starter-oauth2-client</code> dependency. </p>
<h4 id="heading-adding-the-dependency">Adding the dependency</h4>
<p>Add the <code>spring-boot-starter-oauth2-client</code> dependency to the spring boot app by inserting the following lines in the <code>pom.xml</code> file:</p>
<pre><code>    <span class="hljs-operator">&lt;</span>dependencies<span class="hljs-operator">&gt;</span>
        ...other dependencies

        <span class="hljs-operator">&lt;</span><span class="hljs-operator">!</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span> To create OAuth2 Client <span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>dependency<span class="hljs-operator">&gt;</span>
            <span class="hljs-operator">&lt;</span>groupId<span class="hljs-operator">&gt;</span>org.springframework.boot&lt;<span class="hljs-operator">/</span>groupId<span class="hljs-operator">&gt;</span>
            <span class="hljs-operator">&lt;</span>artifactId<span class="hljs-operator">&gt;</span>spring<span class="hljs-operator">-</span>boot<span class="hljs-operator">-</span>starter<span class="hljs-operator">-</span>oauth2<span class="hljs-operator">-</span>client<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>artifactId<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>dependency<span class="hljs-operator">&gt;</span>

        ... other dependencies
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>dependencies<span class="hljs-operator">&gt;</span>
</code></pre><p>Now, our app is an OAuth2 client. We just need to configure it.</p>
<h4 id="heading-creating-app-in-identity-provider">Creating app in Identity Provider</h4>
<p>In <a target="_blank" href="https://hpareek.hashnode.dev/authentication-using-oauth2-openid-connect-in-angular-single-page-application">the first part</a> of this series, we created an OAuth2 client in Authorization Server / Identity Provider. We chose Single Page Application and that is the reason Okta did not provide client secret for the app. But, now we are serving the app from a spring boot backend. And we can securely store credentials and access token in the backend. So, we need to create another app because we need client secrets this time. If you don't know how to create an app in Identity Provider, then read <a target="_blank" href="https://hpareek.hashnode.dev/authentication-using-oauth2-openid-connect-in-angular-single-page-application">the first part</a>  here. Create a new app in Identity Provider, but this time chose <strong>Web Application</strong> as <em>Application Type</em> not <strong>Single Page Application</strong> since authentication and tokens will be managed on the server, not in the browser. Use <code>http://localhost:8081/login/oauth2/code/{IdentityProviderId}</code> as <strong>Sign-in Redirect URI</strong> and <code>http://localhost:8081</code> as <strong>Sign-out Redirect URI</strong> while creating the app. Here <code>IdentityProviderId</code> is the unique id of the identity provider with respect to our Spring Boot App. For example, you can use <code>okta</code> for <strong>Okta</strong>, <code>keycloak</code> for <strong>Keycloak</strong>, etc. At this point, you should have <code>client-id</code>, <code>client-secret</code>, and <code>issuer-uri</code> of the app. In case of Okta, the <code>issuer-uri</code> is <code>https://{OKTA_DOMAIN}/oauth2/default</code>.</p>
<h4 id="heading-configuring-spring-boot-app">Configuring Spring Boot App</h4>
<p>Add the following configurations to the <code>application.properties</code> file of the app:</p>
<pre><code>spring.security.oauth2.client.registration.{IdentityProviderId}.client-id<span class="hljs-operator">=</span>{ClientId}
spring.security.oauth2.client.registration.{IdentityProviderId}.client-secret<span class="hljs-operator">=</span>{ClientSecret}
spring.security.oauth2.client.registration.{IdentityProviderId}.scope=openid,profile,email
spring.security.oauth2.client.registration.{IdentityProviderId}.authorization-grant<span class="hljs-operator">-</span><span class="hljs-keyword">type</span><span class="hljs-operator">=</span>authorization_code
spring.security.oauth2.client.registration.{IdentityProviderId}.redirect-uri<span class="hljs-operator">=</span>{RedirectURI}
spring.security.oauth2.client.provider.{IdentityProviderId}.issuer-uri<span class="hljs-operator">=</span>{IssuerURI}
</code></pre><p>Restart the app and visit <code>http://localhost:8081</code> in a private window of the browser. You are asked to Sign in to the app. Enter the username and password of any user which you created in Identity Provider (Please do so, if you haven't done already). After successful login, we can see our angular app. </p>
<h3 id="heading-summary">Summary</h3>
<p>In this article, we</p>
<p>✅ created a spring boot server, which serves an angular app.</p>
<p>✅ added OAuth2 authentication to the spring boot server to secure the angular app.</p>
<p>Source code can be found <a target="_blank" href="https://github.com/himanshu-pareek/OAuth2SPA/tree/05_Serve_Ang_App_from_backend_OAuth2_flow">here</a> (<code>oauth2clientserver</code> directory). In the next article, I will explain how to use this Spring Boot Server as a proxy while making API requests to the Resource Server. Stay tuned for the next part. Thanks for reading. Keep learning...</p>
]]></content:encoded></item><item><title><![CDATA[Potential risks of using OAuth2 in Single Page Applications]]></title><description><![CDATA[Learn what are some of security risks when we use OAuth2 for authentication and authorization in Single Page Applications]]></description><link>https://blog.javarush.dev/potential-risks-of-using-oauth2-in-single-page-applications</link><guid isPermaLink="true">https://blog.javarush.dev/potential-risks-of-using-oauth2-in-single-page-applications</guid><category><![CDATA[oauth]]></category><category><![CDATA[spa]]></category><category><![CDATA[Angular]]></category><category><![CDATA[Security]]></category><category><![CDATA[cookies]]></category><dc:creator><![CDATA[Himanshu Pareek]]></dc:creator><pubDate>Sun, 26 Dec 2021 08:26:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1639828041004/ii8iYBp-q.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the <a target="_blank" href="https://hpareek.hashnode.dev/authentication-using-oauth2-openid-connect-in-angular-single-page-application">1st part</a> of the series, we developed a Single Page Application using <a target="_blank" href="https://angular.io/">Angular</a> framework. SPAs are common pattern for building web applications now a days. But, there are some unique challenges when using OAuth with SPAs. I will try my best to explain some of them. The reason of the following challenges is that the code of single page application is kept inside browser. So, all the data which the application needs also lives inside the browser.</p>
<h3 id="heading-issue-with-credentials">Issue with credentials</h3>
<p>One simple limitation of JavaScript applications is that there is no way to have any sort of credentials in the app. In OAuth terms, these apps are considered <a target="_blank" href="https://auth0.com/docs/configure/applications/confidential-public-apps#public-applications"><strong>Public Clients</strong></a>. If we put any kind of secret or API key in the source code, the user can easily click on <em>View Page Source</em> and can access the secret. There is no way to hide it from the user.</p>
<p>To solve this issue we need some mechanism for OAuth flow without needing client secret. That's exactly what <strong><a target="_blank" href="https://oauth.net/2/pkce/">PKCE extension</a></strong> provides. Some Identity Providers do not even generate client secret for single page applications. When we built the Angular app, we used <code>angular-oauth2-oidc</code> package to handle OAuth login flow, which uses PKCE extension by default.</p>
<h3 id="heading-cross-site-scripting-attack">Cross Site Scripting Attack</h3>
<p>Cross-site scripting attack or <a target="_blank" href="https://owasp.org/www-community/attacks/xss/">XSS</a> is one of the most dangerous attack. In this attack, attacker is able to run code within our application which looks just like legitimate code. They are able to access any data the app is storing itself like some sensitive data or access token. They are able to make API calls with the access token even if they can't see it.</p>
<p>Having strong  <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP">Content Security Policy</a>  is one of the best way to defend against XSS attack. Using CSP, we can tell browser which domains are allowed to load the JavaScript from in our app. Thus, attacker won't be able to inject JavaScript from any other domain. There are some limitations to this approach. For example, if we use any CSS frameworks, analytics or advertisements in our app, then we need to allow these domains to load JavaScript from (otherwise app won't work properly). But, what if the JavaScript code downloaded from these sources is already attacked. In that case, our app will also be compromised. But that doesn't mean we should not use any third-party libraries. We need to be mindful of potential security risks associated with them.</p>
<h3 id="heading-browser-extensions">Browser Extensions</h3>
<p>Users of our web app may have installed some <a target="_blank" href="https://en.wikipedia.org/wiki/Browser_extension">browser extensions</a> which may also access the page. So, even if we have secured the app using strong content security policy, the user can still load external JavaScript using browser extensions. So, we never know what code is running inside our web app.</p>
<h3 id="heading-storing-tokens-in-browser">Storing tokens in browser</h3>
<p>We have seen that it is nearly impossible to hide client secret and access token from external JavaScript code in a web app. To handle the issue with client secret, we can use PKCE extension and can get access token from Authorization server. Now, we need a way to securely storing received access token in the browser. Access token can be stored at one of the 3 places: <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage"><strong>Local Storage</strong></a>, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage"><strong>Session Storage</strong></a> and <a target="_blank" href="https://en.wikipedia.org/wiki/HTTP_cookie"><strong>Cookies</strong></a>. But, if our app's code can access the token from these locations, then external JavaScript also can. So, we need some way to restrict 3rd party JavaScript from accessing the token. Some possible workarounds are the following:</p>
<ol>
<li>Don't store access token at all. Keep this in app memory. This makes it much harder for an attacker to extract access token. But then, the access token can't be shared among multiple tabs or page refreshes.</li>
<li>Another option is to store token in <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API"><strong>Service Worker</strong></a>. The storage used by Service Worker is completely isolated from browser storage. So, external JS won't be able to extract token from it. But then, even our main app won't be able to access the token. We need to make Service Worker an OAuth Client itself. It is very complicated to build. We can only ask Service Worker what to do, but we can not access the information inside it. And if our app can ask Service Worker to make some API call using token, then external JavaScript also can.</li>
</ol>
<h3 id="heading-securing-web-app-using-backend">Securing Web App using Backend</h3>
<p>We have seen in the previous sections that it is very difficult to secure the access token in a Single Page Application. There is always the possibility of stealing access token from app by attacker. But, what if even the web app don't have access to the token. Then, attacker can't stole it, right? But, how is it possible, you may ask.</p>
<p>The idea is to move OAuth flow and Access token storage into a dynamic backend server. This will be possible only if we use SPA framework and serve it from a backend server (like SpringBoot). This is a common pattern and then use backend for OAuth flow and proxy all the API requests through that backend. The backend can send an <a target="_blank" href="https://owasp.org/www-community/HttpOnly">HttpOnly session cookie</a> to the browser and thus even that can't be stolen from JavaScript. I will cover how to build and use this dynamic backend for single page application in the next part of this series.</p>
<h3 id="heading-summary">Summary</h3>
<p>In this article, we looked at some of the security concerns while storing credentials and access token in browser for single page applications. We also discussed some of the possible solutions. In the next article we will build a backend server to serve our single page application.</p>
<p>Until then, stay safe and keep learning...</p>
]]></content:encoded></item><item><title><![CDATA[Handling Authentication and Authorization failures in API Server]]></title><description><![CDATA[Learn how to send custom response in case of authentication failure or authorization failure]]></description><link>https://blog.javarush.dev/handling-authentication-and-authorization-failures-in-api-server</link><guid isPermaLink="true">https://blog.javarush.dev/handling-authentication-and-authorization-failures-in-api-server</guid><category><![CDATA[authentication]]></category><category><![CDATA[authorization]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[Angular]]></category><dc:creator><![CDATA[Himanshu Pareek]]></dc:creator><pubDate>Fri, 10 Dec 2021 04:32:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1638816059858/sHu3ZQ2pR.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the <a target="_blank" href="https://hpareek.hashnode.dev/create-oauth2-api-server-using-spring-boot">previous article of this series</a>, we created an API server using Spring Boot. We secured the API server to allow only authenticated requests to access the resources. But, in case of unauthenticated request, the server responds with an empty response, which is not helpful at all. So, in this article we will learn how to send custom response if the request is not authenticated or not authorized.</p>
<h3 id="heading-create-a-custom-oauth2-authentication-entry-point">Create a Custom OAuth2 Authentication Entry Point</h3>
<p>To handle unauthenticated requests, we need to implement <code>commence</code> method of <code>AuthenticationEntryPoint</code> interface. Create a file <code>CustomOAuth2AuthenticationEntryPoint.java</code> inside <code>security</code> package. Replace the code of this file with the following code:</p>
<pre><code>package dev.hashnode.hpareek.OAuth2DemoResourceServer.security;

<span class="hljs-keyword">import</span> <span class="hljs-title">com</span>.<span class="hljs-title">fasterxml</span>.<span class="hljs-title">jackson</span>.<span class="hljs-title">databind</span>.<span class="hljs-title">ObjectMapper</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">http</span>.<span class="hljs-title">HttpStatus</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">security</span>.<span class="hljs-title">core</span>.<span class="hljs-title">AuthenticationException</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">security</span>.<span class="hljs-title">web</span>.<span class="hljs-title">AuthenticationEntryPoint</span>;

<span class="hljs-keyword">import</span> <span class="hljs-title">javax</span>.<span class="hljs-title">servlet</span>.<span class="hljs-title">ServletException</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">javax</span>.<span class="hljs-title">servlet</span>.<span class="hljs-title">http</span>.<span class="hljs-title">HttpServletRequest</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">javax</span>.<span class="hljs-title">servlet</span>.<span class="hljs-title">http</span>.<span class="hljs-title">HttpServletResponse</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">java</span>.<span class="hljs-title">io</span>.<span class="hljs-title">IOException</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">java</span>.<span class="hljs-title">util</span>.<span class="hljs-title">Date</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">java</span>.<span class="hljs-title">util</span>.<span class="hljs-title">HashMap</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">java</span>.<span class="hljs-title">util</span>.<span class="hljs-title">Map</span>;

<span class="hljs-keyword">public</span> class CustomOAuth2AuthenticationEntryPoint implements AuthenticationEntryPoint {

    <span class="hljs-keyword">private</span> final ObjectMapper objectMapper <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> ObjectMapper();

    @Override
    <span class="hljs-keyword">public</span> void commence(
            HttpServletRequest request,
            HttpServletResponse response,
            AuthenticationException authException
    ) throws IOException, ServletException {
        HttpStatus httpStatus <span class="hljs-operator">=</span> HttpStatus.UNAUTHORIZED; <span class="hljs-comment">// 401</span>

        Map<span class="hljs-operator">&lt;</span>String, Object<span class="hljs-operator">&gt;</span> data <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> HashMap<span class="hljs-operator">&lt;</span><span class="hljs-operator">&gt;</span>();
        data.put(<span class="hljs-string">"timestamp"</span>, <span class="hljs-keyword">new</span> Date());
        data.put(<span class="hljs-string">"code"</span>, httpStatus.<span class="hljs-built_in">value</span>());
        data.put(<span class="hljs-string">"status"</span>, httpStatus.<span class="hljs-built_in">name</span>());
        data.put(<span class="hljs-string">"message"</span>, authException.getMessage());

        response.setStatus(httpStatus.<span class="hljs-built_in">value</span>());

        response.getOutputStream()
                .println(objectMapper.writeValueAsString(data));
    }
}
</code></pre><p>Here, we store some information related to <code>authException</code> in <code>data</code>. We set the status of the response to <code>401</code> or <code>UNAUTHORIZED</code> and respond with <code>data</code>. Now, we need to configure <code>HttpSecurity</code> to use this class for <code>AuthenticationException</code>. To do that, we modify the code of <code>SecurityConfig.java</code> file using the following code:</p>
<pre><code><span class="hljs-comment">// Imports</span>

@Configuration
<span class="hljs-keyword">public</span> class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .oauth2ResourceServer()
                .authenticationEntryPoint(authenticationEntryPoint())
                .jwt();
        http.cors();
    }

    @Bean
    <span class="hljs-keyword">public</span> AuthenticationEntryPoint authenticationEntryPoint() {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> CustomOAuth2AuthenticationEntryPoint();
    }
}
</code></pre><p>Here we are creating a method <code>authenticationEntryPoint</code> to return a bean of <code>AuthenticationEntryPoint</code> interface. And this method returns an instance of <code>CustomOAuth2AuthenticationEntryPoint</code> class which we created in the previous step. Also, we are configuring <code>HttpSecurity</code> to use bean returned by <code>authenticationEntryPoint</code> method to handle <code>AuthenticationException</code>.</p>
<h3 id="heading-create-a-custom-access-denied-handler">Create a Custom Access Denied Handler</h3>
<p><code>AuthenticationException</code> is thrown when the api request is not authenticated. And to handle this exception, we made some configuration in previous section. But, what if the request is authenticated, but it does not have access to use certain resources? In this case, <code>AccessDeniedException</code> is thrown and we need to handle it by implementing <code>AccessDeniedHandler</code> interface. Create a file <code>CustomAccessDeniedHandler.java</code> inside <code>security</code> package and replace the code of this file with the following code:</p>
<pre><code>package dev.hashnode.hpareek.OAuth2DemoResourceServer.security;

<span class="hljs-keyword">import</span> <span class="hljs-title">com</span>.<span class="hljs-title">fasterxml</span>.<span class="hljs-title">jackson</span>.<span class="hljs-title">databind</span>.<span class="hljs-title">ObjectMapper</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">http</span>.<span class="hljs-title">HttpStatus</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">security</span>.<span class="hljs-title">access</span>.<span class="hljs-title">AccessDeniedException</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">security</span>.<span class="hljs-title">web</span>.<span class="hljs-title">access</span>.<span class="hljs-title">AccessDeniedHandler</span>;

<span class="hljs-keyword">import</span> <span class="hljs-title">javax</span>.<span class="hljs-title">servlet</span>.<span class="hljs-title">ServletException</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">javax</span>.<span class="hljs-title">servlet</span>.<span class="hljs-title">http</span>.<span class="hljs-title">HttpServletRequest</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">javax</span>.<span class="hljs-title">servlet</span>.<span class="hljs-title">http</span>.<span class="hljs-title">HttpServletResponse</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">java</span>.<span class="hljs-title">io</span>.<span class="hljs-title">IOException</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">java</span>.<span class="hljs-title">util</span>.<span class="hljs-title">Date</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">java</span>.<span class="hljs-title">util</span>.<span class="hljs-title">HashMap</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">java</span>.<span class="hljs-title">util</span>.<span class="hljs-title">Map</span>;

<span class="hljs-keyword">public</span> class CustomAccessDeniedHandler implements AccessDeniedHandler {

    <span class="hljs-keyword">private</span> ObjectMapper objectMapper <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> ObjectMapper();

    @Override
    <span class="hljs-keyword">public</span> void handle(
            HttpServletRequest request,
            HttpServletResponse response,
            AccessDeniedException accessDeniedException
    ) throws IOException, ServletException {
        accessDeniedException.printStackTrace();
        HttpStatus httpStatus <span class="hljs-operator">=</span> HttpStatus.FORBIDDEN; <span class="hljs-comment">// 403</span>

        Map<span class="hljs-operator">&lt;</span>String, Object<span class="hljs-operator">&gt;</span> data <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> HashMap<span class="hljs-operator">&lt;</span><span class="hljs-operator">&gt;</span>();
        data.put(<span class="hljs-string">"timestamp"</span>, <span class="hljs-keyword">new</span> Date());
        data.put(<span class="hljs-string">"code"</span>, httpStatus.<span class="hljs-built_in">value</span>());
        data.put(<span class="hljs-string">"status"</span>, httpStatus.<span class="hljs-built_in">name</span>());
        data.put(<span class="hljs-string">"message"</span>, accessDeniedException.getMessage());

        response.setStatus(httpStatus.<span class="hljs-built_in">value</span>());

        response.getOutputStream()
                .println(objectMapper.writeValueAsString(data));
    }
}
</code></pre><p>Here, just like <code>AuthenticationEntryPoint</code>, we are responding with custom response in case of <code>AccessDeniedException</code>. We are using <code>403</code> status code. Now, we need to configure <code>HttpSecurity</code> to use this class to handle <code>AccessDeniedException</code>. Update the code in <code>SecurityConfig.java</code> file according the following code:</p>
<pre><code><span class="hljs-comment">// Imports...</span>

@Configuration
<span class="hljs-keyword">public</span> class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .oauth2ResourceServer()
                .authenticationEntryPoint(authenticationEntryPoint())
                 .accessDeniedHandler(accessDeniedHandler())
                .jwt();
        http.cors();
    }

    <span class="hljs-comment">// Rest of the code</span>

    @Bean
    <span class="hljs-keyword">public</span> AccessDeniedHandler accessDeniedHandler() {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> CustomAccessDeniedHandler();
    }
}
</code></pre><p>This is same as we did for <code>AuthenticationEntryPoint</code>.</p>
<h3 id="heading-apply-method-level-security">Apply method level security</h3>
<p>Let's assume that we want to allow access to <code>/authors/all</code> endpoint only to the users who have <code>authors</code> scope in <code>access_token</code>. All the information about access levels is stored in <code>access_token</code>. To accomplish this type of security, we use method level security. Annotate <code>SecurityConfig</code> class with <code>EnableGlobalMethodSecurity</code> annotation to enable method level security:</p>
<pre><code><span class="hljs-comment">// Rest of the code</span>

<span class="hljs-variable">@Configuration</span>
<span class="hljs-variable">@EnableGlobalMethodSecurity</span>(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    <span class="hljs-comment">// Rest of the code    </span>

}
</code></pre><p>Annotate <code>getAuthor</code> method of <code>AuthorController</code> class with <code>PreAuthorize</code> annotation to add extra access level security:</p>
<pre><code><span class="hljs-comment">// Rest of the code</span>
<span class="hljs-selector-tag">public</span> <span class="hljs-selector-tag">class</span> <span class="hljs-selector-tag">AuthorController</span> {

    <span class="hljs-variable">@GetMapping</span>(<span class="hljs-string">"/all"</span>) <span class="hljs-comment">// This method handles requests for /authors/all</span>
    <span class="hljs-variable">@PreAuthorize</span>(<span class="hljs-string">"hasAuthority('SCOPE_authors')"</span>)
    public List&lt;String&gt; getAuthor() {
        <span class="hljs-comment">// Rest of the code</span>
    }
}
</code></pre><p>The method <code>getAuthor</code> will get executed only if the request has <code>authors</code> scope, otherwise <code>AccessDeniedException</code> is thrown and is caught by our custom implementation of <code>AccessDeniedHandler</code>.</p>
<h3 id="heading-create-authors-scope-in-okta">Create authors scope in Okta</h3>
<p>Let's create <code>authors</code> scope in Okta. Go to <strong>Security</strong> &gt; <strong>API</strong>. Click on name of authorization server. It will be <strong>default</strong> most probably. Switch to <strong>Scops</strong> tab. Click on <strong>Add Scop</strong> button. Enter the following information and click <strong>Create</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638810578870/2T1MjWaEe.png" alt="Screenshot from 2021-12-06 22-39-00.png" />
The <strong>authors</strong> scope has been created.</p>
<h3 id="heading-see-everything-in-action">See everything in action</h3>
<p>Run the angular application which we developed in first part of this series and enhanced in second part using <code>ng serve</code> command. And open <code>http://localhost:4200</code> url in a private window. Without logging into the app click on <strong>Get Authors</strong> button. We see response similar to the following in the <strong>Network</strong> tab of developer tools:</p>
<pre><code>{
  <span class="hljs-attr">"code"</span>: <span class="hljs-number">401</span>,
  <span class="hljs-attr">"message"</span>: <span class="hljs-string">"Full authentication is required to access this resource"</span>,
  <span class="hljs-attr">"timestamp"</span>: <span class="hljs-number">1638813968756</span>,
  <span class="hljs-attr">"status"</span>: <span class="hljs-string">"UNAUTHORIZED"</span>
}
</code></pre><p>It is obvious since we are not authenticated. Now, log into the app by clicking on <strong>Login</strong> button. After successful login, click on <strong>Get Authors</strong> button. This time we get the following response:</p>
<pre><code>{
  <span class="hljs-attr">"code"</span>: <span class="hljs-number">403</span>,
  <span class="hljs-attr">"message"</span>: <span class="hljs-string">"Access is denied"</span>,
  <span class="hljs-attr">"timestamp"</span>: <span class="hljs-number">1638814214423</span>,
  <span class="hljs-attr">"status"</span>: <span class="hljs-string">"FORBIDDEN"</span>
}
</code></pre><p>This time, we are authenticated, but we do don't have <code>authors</code> scope associated with the <code>access_token</code>. So, we get <strong>Access Denied</strong> response. Now, change the <code>scope</code> field in <code>authCodeFlowConfig.ts</code> file in directory <code>src/app/config</code> as shown below:</p>
<pre><code><span class="hljs-comment">// Rest of the code</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> authCodeFlowConfig: AuthConfig = {
  <span class="hljs-comment">// Rest of the code</span>
  scope: <span class="hljs-string">"openid profile email authors"</span>,
  showDebugInformation: <span class="hljs-literal">true</span>
};
</code></pre><p>Here, we want access to resources related to <code>authors</code> as well. Now, when user tries to login, she gets prompted to allow our app to have <code>authors</code> access. Re-run angular app and visite <code>http://localhost:4200</code> in a private window. Click on <strong>Login</strong> button. We see a consent screen as below image:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638814670088/pCIxX3TI-.png" alt="Screenshot from 2021-12-06 23-47-07.png" />
Click on <strong>Allow Access</strong> button. You are now logged in and the access token has <code>authors</code> scope. Click on <strong>Get Authors</strong> button. We see a response similar to this in <strong>Console</strong> or <strong>Network</strong> tab of Developer tools:</p>
<pre><code>[
  <span class="hljs-string">"Author 1"</span>,
  <span class="hljs-string">"Author 2"</span>,
  <span class="hljs-string">"Author 3"</span>
]
</code></pre><p>Wow. That's all.</p>
<h3 id="heading-summary">Summary</h3>
<p><a target="_blank" href="https://github.com/himanshu-pareek/OAuth2SPA/tree/03-Handling-Authentication-and-Authorization-Failure">Click here</a> to get the source code of everything covered in this article. We learnt how to send custom response back to user in case of authentication or authorization failure. We also used some annotations to protect our methods. In next articles, I will try to explain some disadvantages and security concerns of using OAuth2 flow in Single Page Applications.</p>
<p>Until then. Stay safe and keep learning...</p>
]]></content:encoded></item><item><title><![CDATA[Create OAuth2 API Server using Spring Boot]]></title><description><![CDATA[Creating a resource / API server using Spring Boot Framework]]></description><link>https://blog.javarush.dev/create-oauth2-api-server-using-spring-boot</link><guid isPermaLink="true">https://blog.javarush.dev/create-oauth2-api-server-using-spring-boot</guid><category><![CDATA[Springboot]]></category><category><![CDATA[REST API]]></category><category><![CDATA[authentication]]></category><category><![CDATA[authorization]]></category><category><![CDATA[Angular]]></category><dc:creator><![CDATA[Himanshu Pareek]]></dc:creator><pubDate>Tue, 07 Dec 2021 15:25:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1638634876277/6EdJ77a-7.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the <a target="_blank" href="https://hpareek.hashnode.dev/authentication-using-oauth2-openid-connect-in-angular-single-page-application">previous article</a> of the series, we created a Single Page Application (SPA) using Angular Framework. And we used OAuth2 and OpenId Connect to authenticate users. In this part, we will create an API server using <a target="_blank" href="https://spring.io/projects/spring-boot">Spring Boot framework</a> which will provide some APIs to be consumed by SPA. API server is called Resource Server as well.</p>
<h3 id="heading-create-a-spring-boot-project">Create a Spring Boot project</h3>
<p>There are multiple ways to create Spring Boot project. The method I like most is using <a target="_blank" href="https://start.spring.io/">Spring Initializr</a> website.</p>
<ol>
<li>Head over to https://start.spring.io/.</li>
<li>Select <strong>Maven Project</strong> as <em>Project</em> and <strong>Java</strong> as <em>Language</em>.</li>
<li>Keep the default selected version of <strong>Spring Boot</strong>. At the time of writing of this blog, it is <code>2.6.1</code>.</li>
<li>Select <strong>Jar</strong> as <em>Packaging</em>.</li>
<li>Let's use Java version <code>11</code>.</li>
<li>Fill rest of the fields as needed.</li>
<li>Click on <strong>Add Dependencies</strong> button.</li>
<li>Search for <strong>Web</strong> in the search box and Select <strong>Spring Web</strong> dependency. <em>Spring Web</em> dependency is used to create RESTFul APIs.
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638602391108/hRQCVzKGG.png" alt="Screenshot from 2021-12-04 12-49-27.png" /></li>
<li>Click on <strong>Generate</strong> button. This will download a zip.</li>
<li>Extract the zip file. You can delete the zip file after that.</li>
</ol>
<h3 id="heading-run-the-project">Run the project</h3>
<p>Its time to run the project. Open the project in your favourite IDE. I will tell the steps for <a target="_blank" href="https://www.jetbrains.com/idea/">IntelliJ IDEA</a>.</p>
<ol>
<li>Open <strong>IntelliJ IDEA</strong>. You will see a welcome screen.
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638602934507/Y1xg2axIj.png" alt="Screenshot from 2021-12-04 12-58-33.png" /></li>
<li>Click on <strong>Open</strong> button.</li>
<li>Select the extracted directory.</li>
<li>Click on <strong>OK</strong> or <strong>Open</strong>.</li>
<li>If you see a popup to trust the project, click on <strong>Trust Project</strong>. </li>
</ol>
<p>The project opens in IDE. It takes some time to resolve the dependencies. The progress is visible in the bottom of the IDE. Let's wait for it to complete. Create 2 package with name <code>controllers</code> and <code>security</code> as shown in the image below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638614931752/Adp0exZ_V.png" alt="Screenshot from 2021-12-04 16-18-19.png" />
Create a file <code>AuthorController.java</code> inside <code>controllers</code> package. This will be a rest controller for our application. Replace the code of <code>AuthorController.java</code> with the following code:</p>
<pre><code>package dev.hashnode.hpareek.OAuth2DemoResourceServer.controllers;

<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">web</span>.<span class="hljs-title">bind</span>.<span class="hljs-title">annotation</span>.<span class="hljs-title">GetMapping</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">web</span>.<span class="hljs-title">bind</span>.<span class="hljs-title">annotation</span>.<span class="hljs-title">PathVariable</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">web</span>.<span class="hljs-title">bind</span>.<span class="hljs-title">annotation</span>.<span class="hljs-title">RequestMapping</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">org</span>.<span class="hljs-title">springframework</span>.<span class="hljs-title">web</span>.<span class="hljs-title">bind</span>.<span class="hljs-title">annotation</span>.<span class="hljs-title">RestController</span>;

<span class="hljs-keyword">import</span> <span class="hljs-title">java</span>.<span class="hljs-title">util</span>.<span class="hljs-title">ArrayList</span>;
<span class="hljs-keyword">import</span> <span class="hljs-title">java</span>.<span class="hljs-title">util</span>.<span class="hljs-title">List</span>;

@RestController
@RequestMapping(<span class="hljs-string">"/authors"</span>) <span class="hljs-comment">// This class handles requests for /authors</span>
<span class="hljs-keyword">public</span> class AuthorController {

    @GetMapping(<span class="hljs-string">"/all"</span>) <span class="hljs-comment">// This method handles requests for /authors/all</span>
    <span class="hljs-keyword">public</span> List<span class="hljs-operator">&lt;</span>String<span class="hljs-operator">&gt;</span> getAuthors() {
        List<span class="hljs-operator">&lt;</span>String<span class="hljs-operator">&gt;</span> authorList <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> ArrayList<span class="hljs-operator">&lt;</span><span class="hljs-operator">&gt;</span>();
        authorList.add(<span class="hljs-string">"Author 1"</span>);
        authorList.add(<span class="hljs-string">"Author 2"</span>);
        authorList.add(<span class="hljs-string">"Author 3"</span>);
        <span class="hljs-keyword">return</span> authorList;
    }
}
</code></pre><p>In the code above, <code>AuthorController</code> class handles requests for <code>/authors</code> endpoint. <code>getAuthors</code> method handles requests for <code>/authors/all</code> endpoint and returns a list of some dummy author names. Run the server by clicking on green play button. The server runs on port <code>8080</code> as shown in the image</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638615849657/9ryYHACyA.png" alt="Screenshot from 2021-12-04 16-33-29.png" />
Go to url <code>http://localhost:8080/authors/all</code> in browser and we can see the response from the server. We have not added security yet, so we are able to access <code>/authors/all</code> endpoint. Now, we will add security to the project.</p>
<h3 id="heading-adding-security-dependencies">Adding Security Dependencies</h3>
<p>We need 2 dependencies to make this server secure using OAuth2.</p>
<ol>
<li><code>spring-boot-starter-security</code> is required to prevent unauthorized access to the protected resources of the server. Add these lines in <code>pom.xml</code> for this dependency:<pre><code><span class="hljs-operator">&lt;</span>dependency<span class="hljs-operator">&gt;</span>
         <span class="hljs-operator">&lt;</span>groupId<span class="hljs-operator">&gt;</span>org.springframework.boot&lt;<span class="hljs-operator">/</span>groupId<span class="hljs-operator">&gt;</span>
         <span class="hljs-operator">&lt;</span>artifactId<span class="hljs-operator">&gt;</span>spring<span class="hljs-operator">-</span>boot<span class="hljs-operator">-</span>starter<span class="hljs-operator">-</span>security<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>artifactId<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>dependency<span class="hljs-operator">&gt;</span>
</code></pre></li>
<li><p><code>spring-boot-starter-oauth2-resource-server</code> is required to make this server capable of using OAuth2 protocol to verify the access of the user. Add these lines in <code>pom.xml</code> file for this dependency:</p>
<pre><code><span class="hljs-operator">&lt;</span>dependency<span class="hljs-operator">&gt;</span>
 <span class="hljs-operator">&lt;</span>groupId<span class="hljs-operator">&gt;</span>org.springframework.boot&lt;<span class="hljs-operator">/</span>groupId<span class="hljs-operator">&gt;</span>
 <span class="hljs-operator">&lt;</span>artifactId<span class="hljs-operator">&gt;</span>spring<span class="hljs-operator">-</span>boot<span class="hljs-operator">-</span>starter<span class="hljs-operator">-</span>oauth2<span class="hljs-operator">-</span>resource<span class="hljs-operator">-</span>server<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>artifactId<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>dependency<span class="hljs-operator">&gt;</span>
</code></pre><p>After adding the above dependencies, the <code>dependencies</code> node of the <code>pom.xml</code> file looks similar to below code:</p>
<pre><code>
 <span class="hljs-operator">&lt;</span>dependencies<span class="hljs-operator">&gt;</span>
     <span class="hljs-operator">&lt;</span>dependency<span class="hljs-operator">&gt;</span>
         <span class="hljs-operator">&lt;</span>groupId<span class="hljs-operator">&gt;</span>org.springframework.boot&lt;<span class="hljs-operator">/</span>groupId<span class="hljs-operator">&gt;</span>
         <span class="hljs-operator">&lt;</span>artifactId<span class="hljs-operator">&gt;</span>spring<span class="hljs-operator">-</span>boot<span class="hljs-operator">-</span>starter<span class="hljs-operator">-</span>web<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>artifactId<span class="hljs-operator">&gt;</span>
     <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>dependency<span class="hljs-operator">&gt;</span>

     <span class="hljs-operator">&lt;</span>dependency<span class="hljs-operator">&gt;</span>
         <span class="hljs-operator">&lt;</span>groupId<span class="hljs-operator">&gt;</span>org.springframework.boot&lt;<span class="hljs-operator">/</span>groupId<span class="hljs-operator">&gt;</span>
         <span class="hljs-operator">&lt;</span>artifactId<span class="hljs-operator">&gt;</span>spring<span class="hljs-operator">-</span>boot<span class="hljs-operator">-</span>starter<span class="hljs-operator">-</span>security<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>artifactId<span class="hljs-operator">&gt;</span>
     <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>dependency<span class="hljs-operator">&gt;</span>

     <span class="hljs-operator">&lt;</span>dependency<span class="hljs-operator">&gt;</span>
         <span class="hljs-operator">&lt;</span>groupId<span class="hljs-operator">&gt;</span>org.springframework.boot&lt;<span class="hljs-operator">/</span>groupId<span class="hljs-operator">&gt;</span>
         <span class="hljs-operator">&lt;</span>artifactId<span class="hljs-operator">&gt;</span>spring<span class="hljs-operator">-</span>boot<span class="hljs-operator">-</span>starter<span class="hljs-operator">-</span>oauth2<span class="hljs-operator">-</span>resource<span class="hljs-operator">-</span>server<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>artifactId<span class="hljs-operator">&gt;</span>
     <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>dependency<span class="hljs-operator">&gt;</span>

     <span class="hljs-operator">&lt;</span>dependency<span class="hljs-operator">&gt;</span>
         <span class="hljs-operator">&lt;</span>groupId<span class="hljs-operator">&gt;</span>org.springframework.boot&lt;<span class="hljs-operator">/</span>groupId<span class="hljs-operator">&gt;</span>
         <span class="hljs-operator">&lt;</span>artifactId<span class="hljs-operator">&gt;</span>spring<span class="hljs-operator">-</span>boot<span class="hljs-operator">-</span>starter<span class="hljs-operator">-</span>test<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>artifactId<span class="hljs-operator">&gt;</span>
         <span class="hljs-operator">&lt;</span>scope<span class="hljs-operator">&gt;</span>test<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>scope<span class="hljs-operator">&gt;</span>
     <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>dependency<span class="hljs-operator">&gt;</span>
 <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>dependencies<span class="hljs-operator">&gt;</span>
</code></pre><p>After adding dependencies, <em>Refresh maven changes</em> using <code>Ctrl/Cmd + Shift + o</code> in IntelliJ IDEA or any other method (depends on IDE). Some IDEs do this automatically.</p>
</li>
</ol>
<h3 id="heading-configure-resource-server">Configure Resource Server</h3>
<p>Edit <code>src/main/resources/application.properties</code> file and replace the code with following code:</p>
<pre><code>spring.security.oauth2.resourceserver.jwt.issuer-uri<span class="hljs-operator">=</span><span class="hljs-operator">&lt;</span>Issuer URI<span class="hljs-operator">&gt;</span>
</code></pre><p><strong>Issuer URI</strong> is same which was used while creating Angular application in the previous article. If you are using <strong>Okta</strong> as an identity provider, then Issuer URI is <code>https://${OktaDomain}/oauth2/default</code>.</p>
<p>Create a file <code>SecurityConfig.java</code> inside <code>security</code> package and replace the code with the following code:</p>
<pre><code><span class="hljs-selector-tag">package</span> <span class="hljs-selector-tag">dev</span><span class="hljs-selector-class">.hashnode</span><span class="hljs-selector-class">.hpareek</span><span class="hljs-selector-class">.OAuth2DemoResourceServer</span><span class="hljs-selector-class">.security</span>;

<span class="hljs-selector-tag">import</span> <span class="hljs-selector-tag">org</span><span class="hljs-selector-class">.springframework</span><span class="hljs-selector-class">.context</span><span class="hljs-selector-class">.annotation</span><span class="hljs-selector-class">.Configuration</span>;
<span class="hljs-selector-tag">import</span> <span class="hljs-selector-tag">org</span><span class="hljs-selector-class">.springframework</span><span class="hljs-selector-class">.security</span><span class="hljs-selector-class">.config</span><span class="hljs-selector-class">.annotation</span><span class="hljs-selector-class">.web</span><span class="hljs-selector-class">.builders</span><span class="hljs-selector-class">.HttpSecurity</span>;
<span class="hljs-selector-tag">import</span> <span class="hljs-selector-tag">org</span><span class="hljs-selector-class">.springframework</span><span class="hljs-selector-class">.security</span><span class="hljs-selector-class">.config</span><span class="hljs-selector-class">.annotation</span><span class="hljs-selector-class">.web</span><span class="hljs-selector-class">.configuration</span><span class="hljs-selector-class">.WebSecurityConfigurerAdapter</span>;

<span class="hljs-keyword">@Configuration</span>
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    <span class="hljs-keyword">@Override</span>
    protected void configure(HttpSecurity http) throws Exception {
        <span class="hljs-selector-tag">http</span><span class="hljs-selector-class">.authorizeRequests</span>()
                <span class="hljs-selector-class">.anyRequest</span>()<span class="hljs-selector-class">.authenticated</span>()
                <span class="hljs-selector-class">.and</span>()
                <span class="hljs-selector-class">.oauth2ResourceServer</span>()<span class="hljs-selector-class">.jwt</span>();
    }
}
</code></pre><p>In this code, we are configuring <code>HttpSecurity</code> to make sure that each request is authenticated and to use OAuth2 protocol for authenticating and authorizing requests. Now, restart the server and try to access <code>http://localhost:8080/authors/all</code> url again in a browser. You won't be able to access it, since we have secured our server to allow only authenticated requests.</p>
<h3 id="heading-get-access-token">Get Access Token</h3>
<p>To access the protected resources at resource server, the request should contain some information about the authenticated user. This is done using <code>authorization header</code>. For OAuth2 protocol, we use <code>Authorization: Bearer ACCESS_TOKEN</code> header. We get <code>ACCESS_TOKEN</code>, when we authenticate to application using OAuth2. So, how do we get it?</p>
<p>Simple, run the angular application using <code>ng serve</code> command which we developed in previous article and open the url <code>http://localhost:4200</code> in a private browser window. Open <strong>Developer tools</strong> in browser and switch to <strong>Network</strong> tab. Now, click on <strong>Login</strong> button and login using username and password. After successful login, in network tab, wee see a request to <code>token</code> endpoint. Click on this request to see the response. We see the response similar to the image below:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638627348870/cFvY5W6YY.png" alt="Screenshot from 2021-12-04 19-45-07.png" />
From the response copy the value of <code>access_token</code> field. This is the required <code>ACCESS_TOKEN</code>. Now, open any terminal and paste the following command to send a request to the resource server along with <code>ACCESS_TOKEN</code>:</p>
<pre><code>curl <span class="hljs-operator">-</span>X GET <span class="hljs-operator">-</span><span class="hljs-operator">-</span>location <span class="hljs-string">"http://localhost:8080/authors/all"</span> \
<span class="hljs-operator">-</span>H <span class="hljs-string">"Authorization: Bearer ACCESS_TOKEN"</span>
</code></pre><p>You will get response like this:</p>
<pre><code>[<span class="hljs-string">"Author 1"</span>,<span class="hljs-string">"Author 2"</span>,<span class="hljs-string">"Author 3"</span>]
</code></pre><h3 id="heading-configure-angular-app-to-send-access-token">Configure Angular App to send access token</h3>
<p>Now, let's configure the Angular App to send access token with each request to resource server. Open <code>app.module.ts</code> file and replace the code with the below code:</p>
<pre><code><span class="hljs-keyword">import</span> { <span class="hljs-title">HttpClientModule</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'@angular/common/http'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title">NgModule</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title">BrowserModule</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'@angular/platform-browser'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title">OAuthModule</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'angular-oauth2-oidc'</span>;

<span class="hljs-keyword">import</span> { <span class="hljs-title">AppComponent</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'./app.component'</span>;

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    OAuthModule.forRoot({
      resourceServer: {
        allowedUrls: [<span class="hljs-string">"http://localhost:8080"</span>],
        sendAccessToken: <span class="hljs-literal">true</span>
      }
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre><p>Here, we are defining <code>resourceServer</code> to send <code>access_token</code> with all requests which has prefix <code>http://localhost:8080</code>. Now, let's send a request to resource server from app. Open <code>app.component.ts</code> file and replace the code with the following code:</p>
<pre><code><span class="hljs-keyword">import</span> { <span class="hljs-title">HttpClient</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'@angular/common/http'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title">Component</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title">OAuthService</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'angular-oauth2-oidc'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title">authCodeFlowConfig</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'./config/authCodeFlowConfig'</span>;

@Component({
  selector: <span class="hljs-string">'app-root'</span>,
  templateUrl: <span class="hljs-string">'./app.component.html'</span>,
  styleUrls: [<span class="hljs-string">'./app.component.css'</span>]
})
export class AppComponent {
  title <span class="hljs-operator">=</span> <span class="hljs-string">'AngularOAuth2Demo'</span>;

  <span class="hljs-function"><span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> oauthService: OAuthService,
    <span class="hljs-keyword">private</span> _http: HttpClient
  </span>) </span>{
    <span class="hljs-built_in">this</span>.oauthService.configure(authCodeFlowConfig);
    <span class="hljs-built_in">this</span>.oauthService.loadDiscoveryDocumentAndTryLogin();
  }

  login() {
    <span class="hljs-built_in">this</span>.oauthService.initCodeFlow();
  }

  logout() {
    <span class="hljs-built_in">this</span>.oauthService.logOut();
  }

  get name () {
    const claims <span class="hljs-operator">=</span> <span class="hljs-built_in">this</span>.oauthService.getIdentityClaims();
    <span class="hljs-keyword">if</span> (<span class="hljs-operator">!</span>claims) <span class="hljs-keyword">return</span> null;
    const nameClaim <span class="hljs-operator">=</span> claims <span class="hljs-keyword">as</span> {name: <span class="hljs-keyword">string</span>};
    <span class="hljs-keyword">return</span> nameClaim.<span class="hljs-built_in">name</span>;
  }

  getAuthors() {
    <span class="hljs-built_in">this</span>._http.get(<span class="hljs-string">"http://localhost:8080/authors/all"</span>)
      .toPromise()
      .then(console.log)
      .catch(console.error);
  }

}
</code></pre><p>In <code>getAuthors()</code> method we are simply sending a request to <code>http://localhost:8080/authors/all</code> endpoint and printing the response to the console. Header <code>Authorization: Bearer ACCESS_TOKEN</code> will be added to it since we configured it in previous step. Now, create a <code>button</code> in <code>app.component.html</code> file to invoke <code>getAuthors</code> method using the following code:</p>
<pre><code><span class="hljs-operator">&lt;</span>div<span class="hljs-operator">&gt;</span>
  <span class="hljs-comment">// Previous code should remain same</span>
  <span class="hljs-operator">&lt;</span>br <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span>button (click)<span class="hljs-operator">=</span><span class="hljs-string">"getAuthors()"</span><span class="hljs-operator">&gt;</span>Get Authors<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>button<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
</code></pre><p>Now, restart the angular app and open the same url <code>http://localhost:4200</code> in a private browser window. Login to the app by clicking on <strong>Login</strong> button. Open the developer tools and select <strong>Network</strong> tab. Click on <strong>Get Authors</strong> button. We can see a request sent to <code>http://localhost:8080/authors/all</code> endpoint with <code>Authorization</code> header.
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638631583680/TaJzStcZS.png" alt="Screenshot from 2021-12-04 20-55-56.png" /></p>
<h3 id="heading-solve-cors-error">Solve CORS Error</h3>
<p>But, if we open the <strong>Console</strong> tab, we see an error that the request to the resource server is blocked by the <strong>CORS</strong> policy.
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638631693604/hvNKqX9RT.png" alt="Screenshot from 2021-12-04 20-57-51.png" />
This is because, by default we can not send request to another origin (server) from any server. To allow requests from Angular app to Resource Server, we need to do some configuration in Spring Boot Application.</p>
<p>Open <code>SecurityConfig.java</code> file inside <code>security</code> package and add <code>http.cors()</code> after other configurations:</p>
<pre><code>http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .oauth2ResourceServer().jwt();
        http.cors();
</code></pre><p>We need to configure individual controllers with <code>CrossOrigin</code> annotation. Open <code>AuthorController.java</code> file inside <code>controllers</code> package and add <code>CrossOrigin</code> annotation:</p>
<pre><code><span class="hljs-variable">@CrossOrigin</span>(origins = <span class="hljs-string">"http://localhost:4200"</span>) <span class="hljs-comment">// allow requests from origin 'http://localhost:4200'</span>
<span class="hljs-variable">@RestController</span>
<span class="hljs-variable">@RequestMapping</span>(<span class="hljs-string">"/authors"</span>) <span class="hljs-comment">// This class handles requests for /authors</span>
public class AuthorController {
    <span class="hljs-comment">// Rest of the code</span>
}
</code></pre><p>Restart the Resource Server. Again click on <strong>Get Authors</strong> button in Angular app (make sure you are signed into the app).
In the console, we can see the correct output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638632399809/EkrnyF8bb.png" alt="Screenshot from 2021-12-04 21-09-35.png" />
It's working. Wow.</p>
<h3 id="heading-summary">Summary</h3>
<p>You can find the source code of everything covered in the article <a target="_blank" href="https://github.com/himanshu-pareek/OAuth2SPA/tree/02-Resource-server-init">here</a>. In this article, we saw how to make resource server and how to send api requests to the server. We also got to know about CORS and how to solve it. In the next article, I will explain how to handle Authentication and Authorization failure errors in resource server and how to return appropriate response.</p>
<p>Your suggestions are welcome. Until then, bye and keep learning...</p>
]]></content:encoded></item><item><title><![CDATA[Authentication using OAuth2 + OpenId Connect in Angular Single Page Application]]></title><description><![CDATA[Learn how to use Okta as an authorization server for your angular application]]></description><link>https://blog.javarush.dev/authentication-using-oauth2-openid-connect-in-angular-single-page-application</link><guid isPermaLink="true">https://blog.javarush.dev/authentication-using-oauth2-openid-connect-in-angular-single-page-application</guid><category><![CDATA[Angular]]></category><category><![CDATA[authentication]]></category><category><![CDATA[authorization]]></category><dc:creator><![CDATA[Himanshu Pareek]]></dc:creator><pubDate>Sat, 04 Dec 2021 18:01:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1638524201643/R1_EAf1qo.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Authentication and authorization are critical component of any application. In simple terms, authentication is a mechanism to verify if the user is the person who he/she is claiming to be. On the other hand, authorization is used to check for the accesses the user have. Authorization tells the application what actions the user is allowed to perform. In this article, we will focus on authentication only. Authorization will be covered in next articles of the series.</p>
<p>If you want your users to login to your application using Google, Facebook, GitHub or any other identity providers, then you need to use OAuth2 for authorization.</p>
<h3 id="heading-oauth2-and-openid-connect">OAuth2 and OpenId Connect</h3>
<p> <a target="_blank" href="https://oauth.net/2/">OAuth2</a> is an industry-standard protocol for authorization. It is not meant for authentication. But, we need authentication as well. That's where  <a target="_blank" href="https://openid.net/connect/">OpenId Connect</a>  comes into play. It is a simple identity layer on top of OAuth2 protocol.</p>
<h3 id="heading-oauth2-components">OAuth2 Components</h3>
<p>3 components are involved while making single page application which uses OAuth2. </p>
<ol>
<li><p><strong>Authorization Server</strong> takes care of authenticating and authorizing users using various methods - Username/Password, Google, Facebook, GitHub (you name it). We have some options for it. First is to build your own which will be very time and resources consuming, error-prone and not so secure task. Second is to use any existing authorization server and maintain that by yourself.  <a target="_blank" href="https://www.keycloak.org/">Keycloak</a>  is a good example of it. Third option is to completely outsource this task to other identity providers.  <a target="_blank" href="https://www.okta.com/">Okta</a> and <a target="_blank" href="https://auth0.com">Auth0</a> are good examples of these providers. We will be using Okta for this series.</p>
</li>
<li><p><strong>Client Server</strong> is responsible to display User Interface and data in the web browser. For now, we will use <a target="_blank" href="https://angular.io/">Angular framework</a> to create it.</p>
</li>
<li><p><strong>API/Resource Server</strong> exposes APIs to be consumed by Client Server and is responsible for storing all the data related to the application. It also restricts the user from accessing the resources which she doesn't have permission to. We will use <a target="_blank" href="https://spring.io/projects/spring-boot">Spring Boot</a> to create API Server in next parts of the series.</p>
</li>
</ol>
<h3 id="heading-setup-okta">Setup Okta</h3>
<p>Let's create one application and user in Okta identity platform for this application.</p>
<h4 id="heading-create-application">Create Application</h4>
<ol>
<li>Create a free developer account at <code>https://developer.okta.com/</code>.</li>
<li>Go to <strong>Applications</strong> &gt; <strong>Applications</strong>.</li>
<li>Click on <strong>Create App Integration</strong>.</li>
<li>For <strong>Sign-in method</strong>, select <em>OIDC - OpenId Connect</em>.</li>
<li>For <strong>Application type</strong>, select <em>Single-Page Application</em>.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638514028441/WuF7pzd19.png" alt="Screenshot from 2021-12-02 22-42-25.png" /></p>
<ol>
<li>Click on <strong>Next</strong>.</li>
<li>For <strong>App Integration name</strong>, enter name best suitable to your application.</li>
<li>For <strong>Grant Type</strong>, choose <em>Authorization Code</em>.</li>
<li>For <strong>Sign-in redirect URIs</strong>, add <em>http://localhost:4200</em>.</li>
<li>For <strong>Sign-out redirect URIs</strong>, add <em>http://localhost:4200</em>.</li>
<li>For <strong>Controlled Access</strong>, select <em>Allow everyone in your organization</em>.</li>
<li>Click on <strong>Save</strong>.</li>
</ol>
<p>After that, we can see application name, <strong>Client ID</strong>, <strong>Okta domain</strong> and other settings for the newly created application. <code>Client ID</code> and <code>Okta domain</code> will be used later in the article.</p>
<h4 id="heading-create-user">Create User</h4>
<ol>
<li>Go to <strong>Directory</strong> &gt; <strong>People</strong>.</li>
<li>Click on <strong>Add Person</strong>.</li>
<li>Fill all the fields as given in the image below and click on <strong>Save</strong>.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638514721847/J5lJyK9iz.png" alt="Screenshot from 2021-12-02 23-53-17.png" /></p>
<h3 id="heading-build-angular-application">Build Angular application</h3>
<p>Now, let's dive into code and build an angular application which will use Okta as an identity provider to login the users. But hold on, let's make sure you have the right tools with you.</p>
<ol>
<li><strong>Node.js</strong> is a JavaScript runtime built on Chrome's V8 JavaScript Engine. It is needed to run the JavaScript code outside of the browser. If you don't have it in your machine, install it from <a target="_blank" href="https://nodejs.org/en/">here</a>.</li>
<li><strong>Angular CLI</strong> is used to create angular apps. If you don't have it, follow the instructions <a target="_blank" href="https://angular.io/guide/setup-local#install-the-angular-cli">here</a> to install it.</li>
</ol>
<p>Now, my friend, you are ready to code.</p>
<p>Open terminal and run the following command to create a new angular app named <code>AngularOAuth2Demo</code>:</p>
<pre><code>$: ng <span class="hljs-built_in">new</span> AngularOAuth2Demo
</code></pre><p>This command might prompt you to select some options. Choose what is best for your application. After that, change your current directory to <code>AngularOAuth2Demo</code> app with the following command:</p>
<pre><code>$: <span class="hljs-built_in">cd</span> AngularOAuth2Demo
</code></pre><p>To manage all the requests for OAuth2 flow and to manage state of the logged in user in our angular app, we will use <a target="_blank" href="https://www.npmjs.com/package/angular-oauth2-oidc">angular-oauth2-oidc</a> package. Install it into your app using the following command:</p>
<pre><code>$: npm i angular<span class="hljs-operator">-</span>oauth2<span class="hljs-operator">-</span>oidc <span class="hljs-operator">-</span><span class="hljs-operator">-</span>save
</code></pre><p>Crete a file <code>src/app/config/authCodeFlowConfig.ts</code> to manage configurations related to OAuth2 flow. You will need to create <code>config</code> directory inside  <code>src/app</code> directory and then create the file. Replace the code of <code>authCodeFlowConfig.ts</code> with the following code:</p>
<pre><code><span class="hljs-keyword">import</span> { <span class="hljs-title">AuthConfig</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">"angular-oauth2-oidc"</span>;

export const authCodeFlowConfig: AuthConfig <span class="hljs-operator">=</span> {
  issuer: <span class="hljs-string">"&lt;Your Issuer URI&gt;"</span>,
  redirectUri: window.location.origin,
  clientId: <span class="hljs-string">"&lt;Your Client Id&gt;"</span>,
  responseType: <span class="hljs-string">"code"</span>,
  scope: <span class="hljs-string">"openid profile email"</span>,
  showDebugInformation: <span class="hljs-literal">true</span>
};
</code></pre><p>Let's break down this file and try to understand it. <strong>Issuer URI</strong> is a unique URI to identify the application for authentication and authorization purpose. You can find it on your application page in identity provider. If you created app in Okta, you will see <strong>Okta Domain</strong> for you app and the Issuer URI will be <code>https://&lt;Your Okta Domain&gt;/oauth2/default</code>.</p>
<p>The second part is <code>redirectUri</code>, which is used to redirect the user after authentication. This URI must be one of those <code>Sign-in redirect URIs</code> which you configured while making the app in Okta provider. We are using <code>window.location.origin</code> which will be <code>http://localhost:4200</code>, when the angular app will start, since Angular apps run on port 4200 by default. But, if you deploy your app to any server, say <code>https://yourcoolwebsite.dev</code>, then be sure to add this URI (<code>https://yourcoolwebsite.dev</code>) to Sign-in redirect URIs for your app in Okta or any other identity provider.</p>
<p>The <code>clientId</code> is unique to your application and you will find it on the application page in your identity provider. We are using <code>responseType</code> as <code>"code"</code>, so that identity provider will not send the <code>access token</code> and <code>id token</code> in query parameters (which is displayed in browser search bar). The next attribute <code>scope</code> is used to get access token with the given scopes from identity provider. The last attribute <code>showDebugInformation</code> is used to print some debugging information to the console.</p>
<p>Replace the code of <code>app.module.ts</code> with the following code:</p>
<pre><code><span class="hljs-keyword">import</span> { <span class="hljs-title">HttpClientModule</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'@angular/common/http'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title">NgModule</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title">BrowserModule</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'@angular/platform-browser'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title">OAuthModule</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'angular-oauth2-oidc'</span>;

<span class="hljs-keyword">import</span> { <span class="hljs-title">AppComponent</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'./app.component'</span>;

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    OAuthModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre><p>Here, we imported <code>HttpClientModule</code> module from '@angular/common/http<code>package and</code>OAuthModule<code>from</code>angular-oauth2-oidc` package to handle auth flow and user state.</p>
<p>Now, replace the code of <code>app.component.ts</code> with the following code:</p>
<pre><code><span class="hljs-keyword">import</span> { <span class="hljs-title">Component</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title">OAuthService</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'angular-oauth2-oidc'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title">authCodeFlowConfig</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">'./config/authCodeFlowConfig'</span>;

@Component({
  selector: <span class="hljs-string">'app-root'</span>,
  templateUrl: <span class="hljs-string">'./app.component.html'</span>,
  styleUrls: [<span class="hljs-string">'./app.component.css'</span>]
})
export class AppComponent {
  title <span class="hljs-operator">=</span> <span class="hljs-string">'AngularOAuth2Demo'</span>;

  <span class="hljs-function"><span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> oauthService: OAuthService</span>) </span>{
    <span class="hljs-built_in">this</span>.oauthService.configure(authCodeFlowConfig);
    <span class="hljs-built_in">this</span>.oauthService.loadDiscoveryDocumentAndTryLogin();
  }

  login() {
    <span class="hljs-built_in">this</span>.oauthService.initCodeFlow();
  }

  logout() {
    <span class="hljs-built_in">this</span>.oauthService.logOut();
  }

  get name () {
    const claims <span class="hljs-operator">=</span> <span class="hljs-built_in">this</span>.oauthService.getIdentityClaims();
    <span class="hljs-keyword">if</span> (<span class="hljs-operator">!</span>claims) <span class="hljs-keyword">return</span> null;
    const nameClaim <span class="hljs-operator">=</span> claims <span class="hljs-keyword">as</span> {name: <span class="hljs-keyword">string</span>};
    <span class="hljs-keyword">return</span> nameClaim.<span class="hljs-built_in">name</span>;
  }
}
</code></pre><p>Here, in the <code>constructor</code> we are configuring the <code>oauthService</code> to use <code>authCodeFlowConfig.ts</code> file for configuration. Then, we are trying to login the user if the session already exists.</p>
<p>In the <code>login</code> method, we are initiating the code flow for login. The <code>initCodeFlow</code> method of <code>oauthService</code> handles all the requests to and from the identity provider to get the access token. In the <code>logout</code> method, we are simply logging the user out.</p>
<p>The <code>name</code> setter method is used to extract <code>name</code> property from the claims, which we receive from the identity provider.</p>
<p>Now, replace the code of <code>app.component.html</code> with the following code:</p>
<pre><code><span class="hljs-operator">&lt;</span>div<span class="hljs-operator">&gt;</span>
  Welcome to Angular OAuth2 Demo

  <span class="hljs-operator">&lt;</span>div <span class="hljs-operator">*</span>ngIf<span class="hljs-operator">=</span><span class="hljs-string">"name"</span><span class="hljs-operator">&gt;</span>
    Welcome, {{name}}<span class="hljs-operator">&lt;</span>br <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span>button (click)<span class="hljs-operator">=</span><span class="hljs-string">"logout()"</span><span class="hljs-operator">&gt;</span>Logout<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>button<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span>div <span class="hljs-operator">*</span>ngIf<span class="hljs-operator">=</span><span class="hljs-string">"!name"</span><span class="hljs-operator">&gt;</span>
    You are not logged in.
    &lt;button (click)<span class="hljs-operator">=</span><span class="hljs-string">"login()"</span><span class="hljs-operator">&gt;</span>Login<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>button<span class="hljs-operator">&gt;</span>
  <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
</code></pre><p>Here, if the <code>name</code> is not empty, we are displaying a welcome message and a button which will call <code>logout</code> method when clicked. If the <code>name</code> is null or empty, another button will be displayed, which will call <code>login</code> method when clicked. And we have already created <code>login</code> and <code>logout</code> methods and <code>name</code> setter method in <code>app.component.ts</code>.</p>
<p>Now, its time to see the application in action. Run the following command in the terminal to start the application:</p>
<pre><code><span class="hljs-section">$: ng serve</span>
</code></pre><p>In a private window of the browser, open <code>http://localhost:4200</code>. You will see a page with <strong>Login</strong> button. Click on login button. You will be redirected to Okta login page to enter username and password. Enter the username and password of the user which you created in Okta platform. After log in you will be redirected back to the angular application. Now, you will be able to see welcome message along with <code>Logout</code> button. Clicking on the logout button will logout the user and login button will appear again.</p>
<h3 id="heading-summary">Summary</h3>
<p> <a target="_blank" href="https://github.com/himanshu-pareek/OAuth2SPA/tree/01-Authentication-Angular-OAuth2">Click here</a>  to view the source code on GitHub.
In this article, we used Okta as an identity provider to user OAuth2 in a Single Page Application. We still need to make resource server in order to complete the application. We will do that in next article. Also, we will discuss about some of the drawback of client side app and how to resolve them.</p>
<p>Your suggestions are welcome. Until then, Bye and keep learning...</p>
]]></content:encoded></item></channel></rss>