Spring Boot + Spring Security example

In this post, we will see how to create Spring boot + Spring Security example.
Let’s see how Spring boot makes over life simpler.I am going to apply Spring Security on Spring Boot hello world example.

Github Source code:

Spring Boot + Spring Security example:

Here are steps to create a Spring boot + Spring Security example.

Project structure:

Spring Boot Spring Security project structure

 

Tools used for creating below project:

  1. Spring Boot 1.5.3.RELEASE
  2. Spring 4.3.8.RELEASE
  3. Tomcat Embed 8
  4. Maven 3
  5. Java 8
  6. Eclipse
Step 1: Create a dynamic web project using maven in eclipse named “SpringBootSpringSecurityExample”.

Maven dependencies:

Step 2: Change pom.xml as below:

The spring-boot-starter-parent provides you all maven defaults required for any spring project.
Since we are developing a web application, we also need to add spring-boot-starter-web dependency and also we need to include spring-boot-starter-security to secure this web application
If you notice, we did not provide any version for specific components. You just need to provide version no.(1.5.3.RELEASE) for spring boot.
step 3: Create a package named "org.arpit.java2blog.springboot"
create a controller class named "HelloWorldController.java"

As request first goes to dispatcherServlet and it redirects to the controller class. Here @Controller depicts that this is our controller class. @RequestMapper is used to map incoming HTTP request to handler method(hello() in above controller).So hello() method of HelloWorldController.java will handle GET request from dispatcher.So when we have url of

above method will get called.
Step 4: Create a file named “WebSecurityConfiguaration.java” in package org.arpit.java2blog

@EnableWebSecurity annotation is used to enable spring security for this webapp.

authroizeRequest().addMatchers() method is used to configure pattern for request.For example: If http request url has pattern /hello*(hello.jsp,helloworld.html), it will be accessed to ROLE_ADMIN only.

We have hardcoded username(java2blog) and password(java123)   using inMemoryAuthentication(), so if user provides correct credential for admin then only he will be able to access helloworld.html.
Step 4: Create a package named “org.arpit.java2blog”
create a class named “SpringBootHelloWorldApplication.java”

We have just added @SpringBootApplication and it does all the work.
Let’s understand more about this annotation.
@SpringBootApplication is an annotation that adds all of the following:

@Configuration makes the class as a source of bean definitions for the application context.
@EnableAutoConfiguration enables Spring boot to add beans presents in classpath setting and various property setting.
Normally you would add @EnableWebMvc for a Spring MVC application, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath.
This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet.
@ComponentScan tells Spring to look for other components, configurations, and services in the default package, allowing it to find the controllers.
If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.

Step 5: Create a property file named application.properties as below and put it in src/main/resoures.

spring.mvc.view.prefix: /WEB-INF/
spring.mvc.view.suffix: .jsp

Above two properties are very much similar to used in springmvc-dispatcher-servlet.xml in Spring MVC example.

Step 7: Modify index.jsp as below:

Step 7: Create hello.jsp in /WEB-INF/ folder

That’s all about Spring Boot hello world example.
Step 8: It ‘s time to do maven build.

Right click on project -> Run as -> Maven build

Step 9: Provide goals as clean install spring-boot:run (given below) and click on run

Spring Boot Spring Security Maven Build

you will see below output at console.Please note that I have truncated output here:

2017-05-06 01:02:53.086 INFO 16095 — [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-05-06 01:02:53.086 INFO 16095 — [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 8060 ms
2017-05-06 01:02:53.773 INFO 16095 — [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: ‘characterEncodingFilter’ to: [/*] 2017-05-06 01:02:53.774 INFO 16095 — [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: ‘hiddenHttpMethodFilter’ to: [/*] 2017-05-06 01:02:53.774 INFO 16095 — [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: ‘httpPutFormContentFilter’ to: [/*] 2017-05-06 01:02:53.774 INFO 16095 — [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: ‘requestContextFilter’ to: [/*] 2017-05-06 01:02:53.776 INFO 16095 — [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: ‘springSecurityFilterChain’ to: [/*] 2017-05-06 01:02:53.776 INFO 16095 — [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: ‘dispatcherServlet’ to [/] 2017-05-06 01:02:54.699 INFO 16095 — [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@16adb5a1, org.springframework.security.web.context.SecurityContextPersistenceFilter@31094dc4, org.springframework.security.web.header.HeaderWriterFilter@496c7d01, org.springframework.security.web.csrf.CsrfFilter@3005d2e1, org.springframework.security.web.authentication.logout.LogoutFilter@2d7ecd73, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@6c308887, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@514797af, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@14a08616, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@3f373a85, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@41b1e420, org.springframework.security.web.session.SessionManagementFilter@61184671, org.springframework.security.web.access.ExceptionTranslationFilter@4716657, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@216679a4] 2017-05-06 01:02:54.846 INFO 16095 — [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6d29ef13: startup date [Sat May 06 01:02:45 IST 2017]; root of context hierarchy
2017-05-06 01:02:54.988 INFO 16095 — [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped “{[/helloworld]}” onto public org.springframework.web.servlet.ModelAndView org.arpit.java2blog.springboot.HelloWorldController.hello()
2017-05-06 01:02:54.990 INFO 16095 — [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped “{[/logout],methods=[GET]}” onto public java.lang.String org.arpit.java2blog.springboot.HelloWorldController.logoutPage(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-05-06 01:02:54.997 INFO 16095 — [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped “{[/error]}” onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-05-06 01:02:54.997 INFO 16095 — [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped “{[/error],produces=[text/html]}” onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-05-06 01:02:55.037 INFO 16095 — [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2017-05-06 01:02:55.038 INFO 16095 — [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2017-05-06 01:02:55.092 INFO 16095 — [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2017-05-06 01:02:55.406 INFO 16095 — [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-05-06 01:02:55.627 INFO 16095 — [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-05-06 01:02:55.636 INFO 16095 — [ main] o.a.j.SpringBootHelloWorldApplication : Started SpringBootHelloWorldApplication in 12.511 seconds (JVM running for 34.07)

Step 10: Let’s test the application now.
As Spring uses embedded tomcat, you can access the project using http://localhost:8080/index.jsp.

Spring security index

When you click on “Click here to read hello message” link, you will get below screen.

If you put correct user and Password, you will see below screen.
Spring boot Hello World

If you put incorrect user or password and click on login, you will get below screen.

Spring security incorrect credentials
That’s all about Spring boot + Spring security example. If you find any issue with this project, please put a comment.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *