Thursday 8 August 2019

Spring boot Security: Hello World Application


In this post, we are going to develop simple web application that is protected by spring security.

Step 1: Create new maven project ‘springSecurity’.

Open Eclipse.

File -> New -> Other.

Search for Maven.

Select ‘Maven Project’ and click on Next button.

Select the check box ‘Create a simple project (skip archetype selection)’.

Click on Next button.

Give Group Id, Artifact Id as ‘springSecurity’ and version as 1 and click on Finish button.

It creates below project structure.
Step 2: Update pom.xml with maven dependencies.
I am using below dependencies.
                  <dependency>
                           <groupId>org.springframework.boot</groupId>
                           <artifactId>spring-boot-starter-web</artifactId>
                  </dependency>

                  <dependency>
                           <groupId>org.springframework.boot</groupId>
                           <artifactId>spring-boot-starter-security</artifactId>
                  </dependency>

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>springSecurity</groupId>
 <artifactId>springSecurity</artifactId>
 <version>1</version>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.6.RELEASE</version>
 </parent>

 <dependencies>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
  </dependency>

 </dependencies>
</project>

Step 3: Create HelloWorldController in com.sample.app package.

HelloWorldController.java
package com.sample.app.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorldController {
 @RequestMapping("/")
 public String homePage() {
  return "Welcome to Spring boot Application Development using Spring Security";
 }
}


Step 4: Create App.java in com.sample.app package.
App.java
package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
 public static void main(String[] args) {
  
  SpringApplication.run(App.class, args);
 }
}


Total project structure looks like below.


Run App.java, you can see below messages in console.
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.6.RELEASE)

2019-07-14 08:59:24.056  INFO 19342 --- [           main] com.sample.app.App                       : Starting App on C02X902SJGH5 with PID 19342 (/Users/krishna/Documents/EclipseWorkSpaces/Learnings/springSecurity/target/classes started by krishna in /Users/krishna/Documents/EclipseWorkSpaces/Learnings/springSecurity)
2019-07-14 08:59:24.058  INFO 19342 --- [           main] com.sample.app.App                       : No active profile set, falling back to default profiles: default
2019-07-14 08:59:25.020  INFO 19342 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-07-14 08:59:25.046  INFO 19342 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-07-14 08:59:25.046  INFO 19342 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.21]
2019-07-14 08:59:25.130  INFO 19342 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-07-14 08:59:25.130  INFO 19342 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1025 ms
2019-07-14 08:59:25.302  INFO 19342 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-07-14 08:59:25.511  INFO 19342 --- [           main] .s.s.UserDetailsServiceAutoConfiguration : 

Using generated security password: 32b56cc2-7587-48e0-8580-d3acc512f0c4

2019-07-14 08:59:25.646  INFO 19342 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@4e8e8621, org.springframework.security.web.context.SecurityContextPersistenceFilter@6a4d7f76, org.springframework.security.web.header.HeaderWriterFilter@29be7749, org.springframework.security.web.csrf.CsrfFilter@703feacd, org.springframework.security.web.authentication.logout.LogoutFilter@6b1e7ad3, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@4c0884e8, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@21ab988f, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter@c446b14, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@5bfc257, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@53dfacba, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@2d195ee4, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@3af356f, org.springframework.security.web.session.SessionManagementFilter@4650a407, org.springframework.security.web.access.ExceptionTranslationFilter@2687f956, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@7578e06a]
2019-07-14 08:59:25.729  INFO 19342 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-07-14 08:59:25.732  INFO 19342 --- [           main] com.sample.app.App                       : Started App in 1.987 seconds (JVM running for 2.444)


Search for the string ‘password’ in console, you can see below kind of message.

Using generated security password: 32b56cc2-7587-48e0-8580-d3acc512f0c4

We should use this password while consuming the apis of our application.


Launch the url ‘http://localhost:8080’ in browser, it redirects you to ‘http://localhost:8080/login’ page (This page is provided by spring security itself).


Enter Username as ‘user’ and password as the one that taken from console and click on ‘Sign in’ button.


You will be redirected to home page.
You can download complete working application from this link.



Previous                                                    Next                                                    Home

No comments:

Post a Comment