<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yatheesan Chandreswaran on Medium]]></title>
        <description><![CDATA[Stories by Yatheesan Chandreswaran on Medium]]></description>
        <link>https://medium.com/@yatheesanc9?source=rss-227da4539db5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*nIZ2rAFUKz9G2anXvwrpMw.jpeg</url>
            <title>Stories by Yatheesan Chandreswaran on Medium</title>
            <link>https://medium.com/@yatheesanc9?source=rss-227da4539db5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 19:38:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yatheesanc9/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Spring Boot with Google Sign-In]]></title>
            <link>https://yatheesanc9.medium.com/spring-boot-with-google-sign-in-8e304dbe936e?source=rss-227da4539db5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e304dbe936e</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[google-sign-in]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[web-applications]]></category>
            <dc:creator><![CDATA[Yatheesan Chandreswaran]]></dc:creator>
            <pubDate>Sun, 01 Nov 2020 07:14:50 GMT</pubDate>
            <atom:updated>2020-11-01T10:13:09.500Z</atom:updated>
            <content:encoded><![CDATA[<p>This article provides basic steps to enable google sign-in with a simple spring boot web application. You will learn how to enable google sign-in authentication with spring security.</p><p>The code for this example can be found in my <a href="https://github.com/Yatheesan/google-login-spring-boot">Github repository</a></p><blockquote><strong><em>You need the following prerequisite</em></strong></blockquote><blockquote>A text editor or IDE</blockquote><blockquote>JDK 1.8 or the latest</blockquote><blockquote>Gradle 4+ or Maven 3.2+</blockquote><blockquote>Google account</blockquote><blockquote>Basic understanding of OAuth 2.0 Authentication process</blockquote><p>There are two ways to enable authentication and authorization to web applications. The first option is to implement, create, and maintain a user database with the Authentication process, the second option is to use an external authentication framework.</p><h3><strong>OAuth2 Authentication</strong></h3><p>OAuth 2.0 is the industry-standard protocol for authentication and authorization. OAuth 2.0 grant a third-party web site or application access to the user’s protected resources. The below diagram explains how the authentication process works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*ZTHPurb2DGfMM1J_h9JuGw.png" /><figcaption>authentication process</figcaption></figure><p>When the user requests an API through a web client which requires an authenticated user is redirected to the Google Sign-In page. One of the request parameters is the client ID, so google knows which registered application the user tries to Sign-In. If the authentication process is successful, the user agrees on the scope of data to be shared with the application. The browser received an authorization code. at the moment browser knows the user has successfully signed in, but again API application validates the authorization code sent from the browser. Google sign-in system confirms the code and sends backs an access token. This token will be used by the browser or client application to query the requests.</p><h3>Register the Application in the Google Sign-in portal</h3><p>To use Google OAuth 2.0 as an authentication provider, let us create a web client in Google cloud console. To enable google auth with spring boot you need a client identifier and shared secret which needs to be passed as a configuration parameter to the application.</p><p>1) log in to the Google API console using your Google account.</p><p>2) Enable Gmail service, Analytics services, and Google+ service APIs in Google cloud console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*p3GpipeyL_EHwwmDfVikJQ.png" /><figcaption>Google cloud console</figcaption></figure><p>3) After enabling the above services, navigate to the credentials section on the left menu, and choose the OAuth client ID option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*eGxYTV-fngNvGfQjYxI1Hw.png" /><figcaption>Google cloud console</figcaption></figure><p>4) If you&#39;re accessing this service for the first time, then you need to create a project.</p><p>5) After selecting the OAuth client ID next, choose the application type as “Web application” which will provide the authorized javascript origins and authorized redirect URIs form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*lPNPGxG7n7KqrM9bY5t6GA.png" /><figcaption>Google cloud console</figcaption></figure><p>6) After choosing the application type, let&#39;s provide the application name, Authorized javascript origins, authorized redirect URIs, and select the create option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*j_pU-5FPoiCN-kdDL8nTnw.png" /><figcaption>Google cloud console</figcaption></figure><p>7) finally, you will find the Client ID and Client secret in the OAuth client created section. Copy the client id and client secret for later use to configure the web application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*2psBsfxPqsHXVOtFTSd7uA.png" /><figcaption>Google cloud console</figcaption></figure><p>8) Now we have successfully created the auth client in the google cloud console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UjqGKNAFZa6J2reONV6sAw.png" /><figcaption>Google cloud console</figcaption></figure><h3>Simple Web Application</h3><p>Generate Spring application using Spring Initializer. The Spring Initializer helps to generate a spring boot application quickly with needed dependencies. This project needs the spring web, Thymeleaf, spring-security, and spring oauth2 client. The above image shows the configurations set up for this project. After generating the project, you will get a zip file with the given artifact name. Unzip the project file and open it using an IDE. This project uses Maven as the build tool. You can use Maven or Gradle to build the project. The following image shows the project structure and pom.xml file that got created for the Maven project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*eY8MER1LGOZVF0iwuf-IsA.png" /><figcaption>pom.xml file</figcaption></figure><p>The dependency section shows a list of selected dependencies for this project.</p><h3>Add an Index Page</h3><p>Before moving into the security section, let us create a simple web application with an index.html home page. You can use the Thymeleaf template to create the views. Create the <strong><em>index.html</em></strong> file inside the following location: <strong>src/main/resources/templates/index.html</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xmlns:th=&quot;https://www.thymeleaf.org&quot;<br>      xmlns:sec=&quot;https://www.thymeleaf.org/thymeleaf-extras-springsecurity3&quot;&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Welcome&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;h1&gt;Welcome Page&lt;/h1&gt;<br>&lt;p&gt;Welcome to Spring Security&lt;/p&gt;<br>&lt;form th:action=&quot;@{/logout}&quot; method=&quot;post&quot;&gt;<br>    &lt;input type=&quot;submit&quot; value=&quot;Sign Out&quot;/&gt;<br>&lt;/form&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>After creating the template view needs to configure the pages based on Spring MVC. Let us create a view controller and configure the Spring MVC. Create MvcConfig.java file in the following location: <strong><em>src/main/java/com/example/googledemo/MvcConfig.java </em></strong>The following code shows the implementation of Spring MVC configuration</p><pre>package com.example.googledemo;<br><br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;<br>import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;<br><br>@Configuration<br>public class MvcConfig implements WebMvcConfigurer {<br><br>    @Override<br>    public void addViewControllers(ViewControllerRegistry registry){<br>        registry.addViewController(&quot;/index&quot;).setViewName(&quot;index&quot;);<br>    }<br>}</pre><p>This class overrides the method of the <strong>WebMvcConfigure </strong>class <strong>addViewControllers()</strong> method and binds the views with the controller. Now lets us enable the spring security and secure this web application with the user login.</p><p>Now all the users can view the index page. Suppose if you want to secure and restrict the index page from unauthorized users, the index page access needs to be secured by forcing the user to the google login page.</p><p>Spring Security dependencies are already added to the <strong>pom.xml</strong> file during the project generation.</p><h3>Secure the application with Spring Security</h3><p>Let&#39;s create a SecurityConfig.java class and annotate it with <em>@EnableWebSecurity </em>to enable the Spring web security support to the Spring MVC. After enabling the spring security, run the application and access it in the browser. You will see the spring default login form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*OcoxCUS6Hc5NVg5SHW6HWw.png" /><figcaption>Spring default login page</figcaption></figure><p>Now you need to override the spring default security methods to apply the application authentication logic. You need to extend <strong>WebSecurityConfigurerAdapter </strong>class and overrides a couple of its methods to set some custom specific security access configurations. The <strong><em>configure(HttpSecurity)</em> </strong>method needs to override to define which URLs need to be secured and which not.</p><h3>Enable Google Sign-in</h3><p>Now we need to configure the generated client credentials to the application.properties file in the resources folder. The spring security-related prefixes start with <strong><em>“spring.security.oauth2.client.registration” </em></strong><em>and follow with client-related custom properties.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*6FwY-kSygiVoa4dwKanRnQ.png" /><figcaption>application property file</figcaption></figure><p>After adding the above application properties for the google client, this will enable all the required beans for OAuth 2 login.</p><h3>Protect API Endpoints</h3><pre>package com.example.googledemo;<br><br>import org.springframework.security.config.annotation.web.builders.HttpSecurity;<br>import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;<br>import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;<br><br>@EnableWebSecurity<br>public class SecurityConfig extends WebSecurityConfigurerAdapter {<br><br>    @Override<br>    public void configure(HttpSecurity httpSecurity) throws Exception {<br>        httpSecurity.csrf().disable().antMatcher(&quot;/**&quot;).authorizeRequests()<br>                .antMatchers(&quot;/&quot;, &quot;/index.html&quot;).authenticated()<br>                .anyRequest().authenticated()<br>                .and()<br>                .oauth2Login().permitAll()<br>                .and().<br>                logout().logoutSuccessUrl(&quot;/&quot;);<br>    }<br>}</pre><p>The above SecurityConfig.java class provides the implementation of the security configuration. here you can notice oauth2Login() element which provides a number of configuration options to enable the customized OAuth 2 logins for different providers. The above configuration shows that all the endpoints and URL paths are protected with authentication and the user will be redirected to the login page by default if not authorized. Finally, the logout URL is also configured with logout() which clears the current session of the user if the “/logout” URL endpoint is triggered and redirected to the base path again after successful logout which will again navigate the user to the login page.</p><p>The index.html page contains the logout function which will trigger the “/logout” endpoint and navigates the user to the login page after the successful logout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*fnV-IhhVY4PS5_IvqHecUQ.png" /><figcaption>index.html file</figcaption></figure><h3>Whitelisting the home page public</h3><p>We can whitelist any views from the authentication by providing the permitAll() permission as shown in the bellow configuration.</p><pre>.antMatchers(&quot;/home&quot;).permitAll()</pre><h3>Build and Run the application</h3><p>Last you need to Build and Run the application. You can run the main class using the IDE from the location: src/main/java/com/example/googledemo/GoogledemoApplication.java</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y_pUfmT6kmAeaPT_1wtDDA.png" /><figcaption>GoogledemoApplication.java file</figcaption></figure><p>You will get the following console output with a successful application startup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c1WS80I8hPRbvlsOwabYiA.png" /><figcaption>Console output</figcaption></figure><h3>Build the executable JAR</h3><p>You can build the executable from the command line using the Maven build command. You can build a jar with all the necessary dependencies, classes, and resources files to run the demo app. Use the following command to run the application.</p><blockquote>mvnw spring-boot:run</blockquote><p>You can package and build the jar using the following command.</p><blockquote>mvnw clean package</blockquote><p>Console output of the successful build</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*iKbRlHTo2OvX_1Pe7SMV6A.png" /><figcaption>Build console output</figcaption></figure><p>After building the jar then run the build jar from the target folder location.</p><blockquote>java -jar target/googledemo-0.0.1.jar</blockquote><p>Once the application starts executed, access the URL in the browser.</p><blockquote><a href="http://localhost:8080/login">http://localhost:8080</a></blockquote><p>The application will redirect the user to the Google login screen and provide Gmail login details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*qjs2vzQtxVxA0l_JVPD5_w.png" /><figcaption>Google sign-in page</figcaption></figure><p>If login successful, the User will be redirected to index home view</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*wsLckO7x-q5Q7DZYcupg8w.png" /><figcaption>Web app index page</figcaption></figure><p>After accessing the welcome page you can able to sign out by clicking on the sign-out. Spring security revokes the authentication and you logged out from the web application. After logged out the application will redirect the user to the Google login page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*qjs2vzQtxVxA0l_JVPD5_w.png" /><figcaption>Google sign-in page</figcaption></figure><h3><strong>Summary</strong></h3><p>This article discusses basic google authentication with spring security for Web Applications in spring boot. By following the steps you can build a simple web application with Google login and learn how to configure basic authentication to web applications. The code for this example can be <a href="https://github.com/Yatheesan/google-login-spring-boot">found in my Github repository.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e304dbe936e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Spring Security : Spring boot, Spring Security, Web Application]]></title>
            <link>https://yatheesanc9.medium.com/basic-spring-security-spring-boot-spring-security-web-application-36962199d8fd?source=rss-227da4539db5------2</link>
            <guid isPermaLink="false">https://medium.com/p/36962199d8fd</guid>
            <dc:creator><![CDATA[Yatheesan Chandreswaran]]></dc:creator>
            <pubDate>Sat, 02 May 2020 09:05:53 GMT</pubDate>
            <atom:updated>2020-05-02T09:39:44.930Z</atom:updated>
            <content:encoded><![CDATA[<h3>Basic Spring Security: Spring boot, Spring Security, Web Application</h3><p>This article guides you through the basic <strong>Authentication</strong> and <strong>Authorization </strong>using spring security set up with a simple web application. You will learn to build a basic spring boot MVC web application with user role-based resource access using <strong>spring security</strong>.</p><p>The code for this example can be <a href="https://github.com/Yatheesan/spring-security">found in my Github repository</a>.</p><blockquote><strong>You need the following prerequisite</strong></blockquote><blockquote><em>A text editor or IDE</em></blockquote><blockquote><a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html"><em>JDK 1.8</em></a><em> or later</em></blockquote><blockquote><a href="http://www.gradle.org/downloads"><em>Gradle 4+</em></a><em> or </em><a href="https://maven.apache.org/download.cgi"><em>Maven 3.2+</em></a></blockquote><h3><strong>Generate a Spring boot project using Spring Initializr</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xpsq8tyjN1m_YVZBxfdWBA.jpeg" /><figcaption>Spring Initializr</figcaption></figure><p>Generate Spring application using <a href="https://start.spring.io/"><strong>Spring Initializr</strong></a>. The Spring Initializer helps you to generate a spring boot application quickly with needed dependencies. This project needs the spring web, Thymeleaf, and spring security. The above image shows the configurations set up for this project.</p><p>After generating the project, you will get a zip file with the given artifact name. Unzip the project file and open it using an IDE. This project uses Maven as the build tool. You can use Maven or Gradle to build the project. The following image shows the project structure and pom.xml file that got created for the Maven project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i5s_-29vzM2-RSYPidQ8og.jpeg" /><figcaption>pom.xml file</figcaption></figure><p>The dependency section shows a list of selected dependencies for this project.</p><h3><strong>Create a simple web client application</strong></h3><p>Before moving into the security section, let us create a simple web application. After creating the web application we can secure the web app using spring security. This simple Web app includes two views initially. A landing <strong>home page</strong> and a <strong>welcome page</strong>. You can use the Thymeleaf template to create the views. Create the <strong><em>home.html</em></strong> file inside the following location: src/main/resources/templates/home.html</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xmlns:th=&quot;https://www.thymeleaf.org&quot; xmlns:sec=&quot;https://www.thymeleaf.org/thymeleaf-extras-springsecurity3&quot;&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Home&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;h1&gt;Home Page&lt;/h1&gt;<br>Spring Security Example<br>&lt;p&gt; Click &lt;a th:href=&quot;@{/welcome}&quot;&gt;here&lt;/a&gt; to visit welcome page.&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>This home.html page includes a link to a welcome page which defined in the following Thymeleaf template. location: src/main/resources/templates/welcome.html</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xmlns:th=&quot;https://www.thymeleaf.org&quot;<br>      xmlns:sec=&quot;https://www.thymeleaf.org/thymeleaf-extras-springsecurity3&quot;&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Welcome&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;h1&gt;Welcome Page&lt;/h1&gt;<br>&lt;p&gt;Welcome to Spring Security&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>After creating the template views needs to configure the pages based on Spring MVC. Let us create a view controller and configure the Spring MVC. Create a <strong><em>SpringMvcConig.java</em></strong> file in the following location: <strong><em>src/main/java/com/example/springsecurity/SpringMvcConig.java</em></strong> Following code shows the implementation of Spring MVC configuration</p><pre>package com.example.springsecurity;<br><br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;<br>import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;<br><br>@Configuration<br>public class SpringMvcConig implements WebMvcConfigurer {<br><br>    @Override<br>    public void addViewControllers(ViewControllerRegistry registry){<br>      registry.addViewController(&quot;/home&quot;).setViewName(&quot;home&quot;);<br>      registry.addViewController(&quot;/&quot;).setViewName(&quot;home&quot;);<br>      registry.addViewController(&quot;/welcome&quot;).setViewName(&quot;welcome&quot;);<br>    }<br>}</pre><p>This class overrides the method of the <strong>WebMvcConfigure </strong>class <strong>addViewControllers()</strong> method and binds the views with the controller. In the same approach other pages also need to be created in later sections. At the moment you have created a simple web application with two views. Run the application and view the application in the browser using the following URL: <a href="http://localhost:8080/">http://localhost:8080/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*euF_A0wZOZ-puOZCuixobw.png" /><figcaption>Home page</figcaption></figure><p>Now lets us enable the spring security and secure this web application with the user login.</p><h3><strong>Configure basic Spring Security</strong></h3><p>Now all the users can view the home page and the welcome page. Suppose if you want to secure and restrict the welcome page from unauthorized users, the welcome page access needs to be secured by forcing the user to the login page.</p><p>Spring Security dependencies are already added to the <strong>pom.xml</strong> file during the project generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*xRAFTHBFjadoXupeLkgVcw.png" /><figcaption>pom.xml</figcaption></figure><p>After checking the dependencies create a <strong>WebSecurityConfig.java</strong> class and annotate it with <em>@Configuration </em>and <em>@EnableWebSecurity </em>to enable the Spring web security support to the Spring MVC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*mtsroxqBleGs6ulvbn8Jzw.png" /><figcaption>Web security configuration</figcaption></figure><p>After enabling the spring security, run the application and access it in the browser. You will see the spring default login form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*zngTj0kuPRRG0238oSd3KA.png" /><figcaption>Spring default login page</figcaption></figure><p>Now you need to override the spring default security methods to apply the application authentication logic. You need to extend <strong>WebSecurityConfigurerAdapter </strong>class and overrides a couple of its methods to set some custom specif security access configurations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*44oZrHVX0yBMZV-9zkOXjA.png" /><figcaption>WebSecurityConfiig.java file</figcaption></figure><p>The <strong><em>configure(HttpSecurity)</em> </strong>method needs to override to define which URLs need to be secured and which not. The home page, the main route, and the support page are configured to permit all access where the users access without any authentications. Other paths need authentication. Once the user successfully authenticated through the login page they are redirected to the previously requested resource path. The custom login page needs to configured inside the<strong> <em>loginPage()</em></strong> where everyone allowed to view if they need to get authenticated. Spring Security provides Role-based authorization where we can allow specific user groups to access specific resources or URLs. <strong><em>hasAuthority(“USER”) </em></strong>secure access to the specific user group. <strong><em>permitAll()</em></strong> allow all the users to access the URL. The support page URL configured with <strong><em>authenticated()</em></strong> without any authorization assigned, This configuration allows all the authenticated users to access the support URL path. <strong><em>exceptionHandling().accessDeniedPage(“/access-denied”)</em></strong> method provides access denied page if logged in user group don&#39;t have access to the URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AmrAO7qt8On0xwy-T6OAfQ.png" /><figcaption><strong><em>configure(HttpSecurity) — Access Configuration</em></strong></figcaption></figure><p>The <strong><em>userDetailsService()</em></strong> method provides an in-memory user store with a group of users with different user groups. The users are configured with their user name, password, and grant authority group names. The below code base shows the in-memory user store creation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wFB5UuTa5dvG0Mw8dDghRw.png" /><figcaption>User details service implementation</figcaption></figure><p>The <strong><em>password encoder</em></strong> method is a part of the spring security password management process. This method provides a more secure default mechanism for encoding and decoding the passwords than storing the passwords as a plain text.</p><p>After configuring the above spring-security in <strong><em>WebSecurityConfig.java</em></strong>, now you need to create a login view and update the view controller with the login path. create the login.html in the following location: <strong>src/main/resources/templates/login.html</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xmlns:th=&quot;https://www.thymeleaf.org&quot; xmlns:sec=&quot;https://www.thymeleaf.org/thymeleaf-extras-springsecurity3&quot;&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Spring Security Example &lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;h1&gt;Login Page&lt;/h1&gt;<br>&lt;div th:if=&quot;${param.error}&quot;&gt;<br>    Invalid username and password.<br>&lt;/div&gt;<br>&lt;div th:if=&quot;${param.logout}&quot;&gt;<br>    You have been logged out.<br>&lt;/div&gt;<br>&lt;form th:action=&quot;@{/login}&quot; method=&quot;post&quot;&gt;</pre><pre>&lt;div&gt;<br>&lt;label&gt; User Name : &lt;input type=&quot;text&quot; name=&quot;username&quot; placeholder=&quot;Enter User Name&quot; required=&quot;true&quot; autofocus=&quot;true&quot;/&gt; &lt;/label&gt;<br>&lt;/div&gt;</pre><pre>&lt;div&gt;<br>&lt;label&gt; Password  : &lt;input type=&quot;password&quot; name=&quot;password&quot; placeholder=&quot;Enter Password&quot; required=&quot;true&quot; /&gt; <br>&lt;/label&gt;<br>&lt;/div&gt;</pre><pre>&lt;div&gt;<br>&lt;input type=&quot;submit&quot; value=&quot;Sign In&quot;/&gt;<br>&lt;/div&gt;</pre><pre>&lt;/form&gt;<br><br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>The login Thymeleaf template configured with spring security login, this template presents a form that captures username and password and posts the form action to <strong>/login</strong> path. if the user fails spring-security redirected to <strong>/login?error</strong> path and it provides the error message in the error parameter. if the user logs out spring security navigates to <strong>/login?logout</strong> path and displays the success message. Then update the <strong><em>welcome.html</em></strong> to say hello message to the current user and add a sign-out form. location: <a href="https://github.com/Yatheesan/spring-security/blob/master/src/main/resources/templates/welcome.html"><strong>src/main/resources/templates/welcome.html</strong></a></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xmlns:th=&quot;https://www.thymeleaf.org&quot;<br>      xmlns:sec=&quot;https://www.thymeleaf.org/thymeleaf-extras-springsecurity3&quot;&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Welcome&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;h1&gt;Welcome Page&lt;/h1&gt;<br>&lt;h1&gt;Hello [[${#httpServletRequest.remoteUser}]]!&lt;/h1&gt;<br>&lt;p&gt;Welcome to Spring Security&lt;/p&gt;<br>&lt;form th:action=&quot;@{/logout}&quot; method=&quot;post&quot;&gt;<br>    &lt;input type=&quot;submit&quot; value=&quot;Sign Out&quot;/&gt;<br>&lt;/form&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong><em>HttpServletRequest#getRemoteUser()</em></strong> gives the logged in the user name and the sign-out form POST the request to <strong><em>/logout </em></strong>by submitting the sign-out button. Once the user successfully logged out spring security redirects the user to <strong>/login?logout</strong>.</p><p>After updating the <strong><em>welcome page</em></strong>, let us create the admin page (<a href="https://github.com/Yatheesan/spring-security/blob/master/src/main/resources/templates/admin.html"><strong><em>admin.html</em></strong></a>) and access denied page (<a href="https://github.com/Yatheesan/spring-security/blob/master/src/main/resources/templates/accessdenied.html"><strong><em>access-denied.html</em></strong></a>) to handle user role-based authentication. So if the user doesn’t have access to the requested URL spring security navigate him to <strong><em>access-denied page</em></strong>. The below code shows the admin view implementation.</p><p><strong>src/main/resources/templates/admin.html</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xmlns:th=&quot;https://www.thymeleaf.org&quot;<br>      xmlns:sec=&quot;https://www.thymeleaf.org/thymeleaf-extras-springsecurity3&quot;&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Admin&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;h1&gt;Admin Panel&lt;/h1&gt;<br>&lt;h1&gt;Hello [[${#httpServletRequest.remoteUser}]]!&lt;/h1&gt;<br>&lt;form th:action=&quot;@{/logout}&quot; method=&quot;post&quot;&gt;<br>    &lt;input type=&quot;submit&quot; value=&quot;Sign Out&quot;/&gt;<br>&lt;/form&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>The below code shows the access denied page implementation. <strong>src/main/resources/templates/access-denied.html</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xmlns:th=&quot;https://www.thymeleaf.org&quot;<br>      xmlns:sec=&quot;https://www.thymeleaf.org/thymeleaf-extras-springsecurity3&quot;&gt;<br>&lt;head&gt;<br>    &lt;title&gt;403&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;h1&gt;Access Denied&lt;/h1&gt;<br>&lt;p&gt; Click &lt;a th:href=&quot;@{/home}&quot;&gt;here&lt;/a&gt; to go back to home.&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>At last, lets us create a support page (support.html) with permit all access with authentication required and about us page (about.html) where any user can access without authentication.</p><p>The below code shows the support page implementation. <strong>src/main/resources/templates/support.html</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xmlns:th=&quot;https://www.thymeleaf.org&quot;<br>      xmlns:sec=&quot;https://www.thymeleaf.org/thymeleaf-extras-springsecurity3&quot;&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Support&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;h1&gt;Support Page&lt;/h1&gt;<br>&lt;p&gt; Click &lt;a th:href=&quot;@{/home}&quot;&gt;here&lt;/a&gt; to visit home page.&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>The below code shows the About us page implementation. <strong>src/main/resources/templates/about.html</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xmlns:th=&quot;https://www.thymeleaf.org&quot;<br>      xmlns:sec=&quot;https://www.thymeleaf.org/thymeleaf-extras-springsecurity3&quot;&gt;<br>&lt;head&gt;<br>    &lt;title&gt;About&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;h1&gt;About Us Page&lt;/h1&gt;<br>&lt;p&gt; Click &lt;a th:href=&quot;@{/home}&quot;&gt;here&lt;/a&gt; to visit home page.&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>After creating all the view pages, update the <a href="https://github.com/Yatheesan/spring-security/blob/master/src/main/java/com/example/springsecurity/MvcConfig.java"><strong><em>MVC view controllers</em></strong></a> by adding the new view controllers to the registry as shown below.</p><pre>package com.example.springsecurity;<br><br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;<br>import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;<br><br>@Configuration<br>public class MvcConfig implements WebMvcConfigurer {<br><br>    @Override<br>    public void addViewControllers(ViewControllerRegistry registry){<br>        registry.addViewController(&quot;/home&quot;).setViewName(&quot;home&quot;);<br>        registry.addViewController(&quot;/&quot;).setViewName(&quot;home&quot;);<br>        registry.addViewController(&quot;/welcome&quot;)<br>        .setViewName(&quot;welcome&quot;);<br>        registry.addViewController(&quot;/login&quot;).setViewName(&quot;login&quot;);<br>        registry.addViewController(&quot;/logout&quot;).setViewName(&quot;login&quot;);<br>        registry.addViewController(&quot;/error&quot;).setViewName(&quot;login&quot;);<br>        registry.addViewController(&quot;/admin&quot;).setViewName(&quot;admin&quot;);<br>        registry.addViewController(&quot;/access-denied&quot;)<br>        .setViewName(&quot;access-denied&quot;);<br>      registry.addViewController(&quot;/support&quot;).setViewName(&quot;support&quot;);<br>      registry.addViewController(&quot;/about&quot;).setViewName(&quot;about&quot;);<br>    }<br>}</pre><p>Last you need to Build and Run the application.</p><h3><strong>Build and Run the application</strong></h3><p>You can run the main class using the IDE from the location: src/main/java/com/example/securingweb/SpringSecurityApplication.java</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*Lojsl2sQUvLJkWJK2HhfwA.png" /><figcaption>SpringSecurityApplication.java</figcaption></figure><p>You will get the following console output with successful user registration to the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d1CcHm1gzoGXKAPnv7ZylQ.png" /><figcaption>Console output</figcaption></figure><h3>Build the executable JAR</h3><p>You can build the executable from the command line using the Maven build command. You can build a jar with all the necessary dependencies, classes, and resources files to run the demo app. Use the following command to run the application.</p><p>./mvnw spring-boot:run</p><p>You can package and build the jar using the following command.</p><p>./mvnw clean package</p><p>Console output of the successful build</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*f-4xiTz5D0eD5Gf5GGPVzQ.png" /><figcaption>Build console output</figcaption></figure><p>After building the jar then run the build jar from the target folder location.</p><pre>java -jar target/spring-security-0.0.1.jar</pre><p>Once the application starts executed, access the URL in the browser.</p><p><a href="http://localhost:8080/login">http://localhost:8080</a></p><p>The home page will load initially in the browsers with four clickable links that take the user to the <strong>welcome page, admin page, support page, </strong>and <strong>about us page</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*BKtc7IAEvfu5LIjx2wfkqw.png" /><figcaption>Home page</figcaption></figure><p>First Click on the link to navigate to the welcome message. The web application will ask for authentication by navigating to the login page because <strong><em>/welcome</em></strong> URL is restricted for authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*_qbo5832FiixStsQD5KwDw.png" /><figcaption>Login page</figcaption></figure><p>If you insert a wrong credentials application will display the invalid username and password message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*ntFDu6tOIGdGQLsPMOqbtg.png" /><figcaption>Error message</figcaption></figure><p>Insert the correct user credentials and select the sign-in button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*4XOoMPTtfkk_9OK7E8PIrw.png" /><figcaption>Login page</figcaption></figure><p>After a successful authentication application navigates to the welcome page. with a user name and welcome message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*B-P22j7IXihbAEV8ELFYBw.png" /><figcaption>Welcome page</figcaption></figure><p>After accessing the welcome page you can able to sign out by clicking on the sign-out. Spring security revokes the authentication and you logged out from the web application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*0YIyhudn54Rdsvnm3NcaFw.png" /><figcaption>Login page</figcaption></figure><p>After logged out again login with the admin user credentials</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*MECssuFL0Atk5SHApnnUIg.png" /><figcaption>Login as admin</figcaption></figure><p>After logging in as an Admin User, the application shows you the home page with the options of pages to visit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*Nw9oyeWgoTHN6ECWPZPkRg.png" /><figcaption>Home page</figcaption></figure><p>If you clicked on the welcome page option you will get an access denied message to indicate you don&#39;t have access to the welcome page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*yyR36HomgaPCkYkki_8r8w.png" /><figcaption>Access denied</figcaption></figure><p>If you select the admin page option application will navigate to the admin page and displays the admin welcome message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*4W0djt7e8YyEXhgl5v3CBw.png" /><figcaption>Admin Page</figcaption></figure><p>From the admin page logged out and navigate to the home page. Select the About us page. The application will allow you to access the about us page without any authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*6DeDXDSKTkxsGBM2O2U4fA.png" /><figcaption>About Page</figcaption></figure><p>After navigating to the about us page, click the home page and select the support page option from the home page. Once you click the support page option application again request for authentication. Here you can log in as User or Admin because the access is opened for all the authenticated users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*RFGO-0l0sBeqaQ8f37Ux_g.png" /><figcaption>Log in as a user to access the support page</figcaption></figure><p>After successful authentication, the web application will allow the user to navigate to the support page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*YTVqbam76cW1_y0yiSLSxA.png" /><figcaption>Support Page</figcaption></figure><p><strong>Summary</strong></p><p>This article discusses basic authentication and authorization with spring security for Web Applications in spring boot. By following the steps you can build a simple web application with spring security and learn how to configure basic authentication and authorization to web applications.</p><p>The code for this example can be <a href="https://github.com/Yatheesan/spring-security">found in my Github repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36962199d8fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>