Spring Boot – Interceptor

Spring Boot – Interceptor ”; Previous Next You can use the Interceptor in Spring Boot to perform operations under the following situations − Before sending the request to the controller Before sending the response to the client For example, you can use an interceptor to add the request header before sending the request to the controller and add the response header before sending the response to the client. To work with interceptor, you need to create @Component class that supports it and it should implement the HandlerInterceptor interface. The following are the three methods you should know about while working on Interceptors − preHandle() method − This is used to perform operations before sending the request to the controller. This method should return true to return the response to the client. postHandle() method − This is used to perform operations before sending the response to the client. afterCompletion() method − This is used to perform operations after completing the request and response. Observe the following code for a better understanding − @Component public class ProductServiceInterceptor implements HandlerInterceptor { @Override public boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return true; } @Override public void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {} @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception {} } You will have to register this Interceptor with InterceptorRegistry by using WebMvcConfigurerAdapter as shown below − @Component public class ProductServiceInterceptorAppConfig extends WebMvcConfigurerAdapter { @Autowired ProductServiceInterceptor productServiceInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(productServiceInterceptor); } } In the example given below, we are going to hit the GET products API which gives the output as given under − The code for the Interceptor class ProductServiceInterceptor.java is given below − package com.tutorialspoint.demo.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; @Component public class ProductServiceInterceptor implements HandlerInterceptor { @Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println(“Pre Handle method is Calling”); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println(“Post Handle method is Calling”); } @Override public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception { System.out.println(“Request and Response is completed”); } } The code for Application Configuration class file to register the Interceptor into Interceptor Registry – ProductServiceInterceptorAppConfig.java is given below − package com.tutorialspoint.demo.interceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Component public class ProductServiceInterceptorAppConfig extends WebMvcConfigurerAdapter { @Autowired ProductServiceInterceptor productServiceInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(productServiceInterceptor); } } The code for Controller class file ProductServiceController.java is given below − package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.exception.ProductNotfoundException; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); static { Product honey = new Product(); honey.setId(“1”); honey.setName(“Honey”); productRepo.put(honey.getId(), honey); Product almond = new Product(); almond.setId(“2”); almond.setName(“Almond”); productRepo.put(almond.getId(), almond); } @RequestMapping(value = “/products”) public ResponseEntity<Object> getProduct() { return new ResponseEntity<>(productRepo.values(), HttpStatus.OK); } } The code for POJO class for Product.java is given below − package com.tutorialspoint.demo.model; public class Product { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } The code for main Spring Boot application class file DemoApplication.java is given below − package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } The code for Maven build – pom.xml is shown here − <?xml version = “1.0” encoding = “UTF-8”?> <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>com.tutorialspoint</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> The code for Gradle Build build.gradle is shown here − buildscript { ext { springBootVersion = ”1.5.8.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } You can create an executable JAR file, and run the Spring Boot application by using the below Maven or Gradle commands. For Maven, use the command as shown below − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, use the command as shown below − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. You can run the JAR file by using the following command − java –jar <JARFILE> Now, the application has started on the Tomcat port 8080 as shown below − Now hit the below URL in POSTMAN application and you can see the output as shown under − GET API: http://localhost:8080/products In the console window, you can see the System.out.println statements added in the Interceptor as shown in the screenshot given below − Print Page Previous Next Advertisements ”;

Spring Boot – Enabling Swagger2

Spring Boot – Enabling Swagger2 ”; Previous Next Swagger2 is an open source project used to generate the REST API documents for RESTful web services. It provides a user interface to access our RESTful web services via the web browser. To enable the Swagger2 in Spring Boot application, you need to add the following dependencies in our build configurations file. <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency> For Gradle users, add the following dependencies in your build.gradle file. compile group: ”io.springfox”, name: ”springfox-swagger2”, version: ”2.7.0” compile group: ”io.springfox”, name: ”springfox-swagger-ui”, version: ”2.7.0” Now, add the @EnableSwagger2 annotation in your main Spring Boot application. The @EnableSwagger2 annotation is used to enable the Swagger2 for your Spring Boot application. The code for main Spring Boot application is shown below − package com.tutorialspoint.swaggerdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication @EnableSwagger2 public class SwaggerDemoApplication { public static void main(String[] args) { SpringApplication.run(SwaggerDemoApplication.class, args); } } Next, create Docket Bean to configure Swagger2 for your Spring Boot application. We need to define the base package to configure REST API(s) for Swagger2. @Bean public Docket productApi() { return new Docket(DocumentationType.SWAGGER_2).select() .apis(RequestHandlerSelectors.basePackage(“com.tutorialspoint.swaggerdemo”)).build(); } Now, add this bean in main Spring Boot application class file itself and your main Spring Boot application class will look as shown below − package com.tutorialspoint.swaggerdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication @EnableSwagger2 public class SwaggerDemoApplication { public static void main(String[] args) { SpringApplication.run(SwaggerDemoApplication.class, args); } @Bean public Docket productApi() { return new Docket(DocumentationType.SWAGGER_2).select() .apis(RequestHandlerSelectors.basePackage(“com.tutorialspoint.swaggerdemo”)).build(); } } Now, add the below Spring Boot Starter Web dependency in your build configuration file to write a REST Endpoints as shown below − Maven users can add the following dependency in your pom.xml file − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> Gradle users can add the following dependency in build.gradle file − compile(”org.springframework.boot:spring-boot-starter-web”) Now, the code to build two simple RESTful web services GET and POST in Rest Controller file is shown here − package com.tutorialspoint.swaggerdemo; import java.util.ArrayList; import java.util.List; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class SwaggerAPIController { @RequestMapping(value = “/products”, method = RequestMethod.GET) public List<String> getProducts() { List<String> productsList = new ArrayList<>(); productsList.add(“Honey”); productsList.add(“Almond”); return productsList; } @RequestMapping(value = “/products”, method = RequestMethod.POST) public String createProduct() { return “Product is saved successfully”; } } The complete build configuration file is given below − Maven – pom.xml <?xml version = “1.0” encoding = “UTF-8”?> <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>com.tutorialspoint</groupId> <artifactId>swagger-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>swagger-demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath /> <!– lookup parent from repository –> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Gradle – build.gradle buildscript { ext { springBootVersion = ”1.5.9.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) compile group: ”io.springfox”, name: ”springfox-swagger2”, version: ”2.7.0” compile group: ”io.springfox”, name: ”springfox-swagger-ui”, version: ”2.7.0” } You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands. For Maven, you can use the command shown here − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the command as shown here − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Now, run the JAR file by using the command shown here − java –jar <JARFILE> Now, the application will start on the Tomcat port 8080 as shown − Now, hit the URL in your web browser and see the Swagger API functionalities. http://localhost:8080/swagger-ui.html Print Page Previous Next Advertisements ”;

Spring Boot – Google OAuth2 Sign-In

Spring Boot – Google OAuth2 Sign-In ”; Previous Next In this chapter, we are going to see how to add the Google OAuth2 Sign-In by using Spring Boot application with Gradle build. First, add the Spring Boot OAuth2 security dependency in your build configuration file and your build configuration file is given below. buildscript { ext { springBootVersion = ”1.5.8.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint.projects” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter”) testCompile(”org.springframework.boot:spring-boot-starter-test”) compile(”org.springframework.security.oauth:spring-security-oauth2”) compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } Now, add the HTTP Endpoint to read the User Principal from the Google after authenticating via Spring Boot in main Spring Boot application class file as given below − package com.tutorialspoint.projects.googleservice; import java.security.Principal; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class GoogleserviceApplication { public static void main(String[] args) { SpringApplication.run(GoogleserviceApplication.class, args); } @RequestMapping(value = “/user”) public Principal user(Principal principal) { return principal; } } Now, write a Configuration file to enable the OAuth2SSO for web security and remove the authentication for index.html file as shown − package com.tutorialspoint.projects.googleservice; import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableOAuth2Sso public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .csrf() .disable() .antMatcher(“/**”) .authorizeRequests() .antMatchers(“/”, “/index.html”) .permitAll() .anyRequest() .authenticated(); } } Next, add the index.html file under static resources and add the link to redirect into user HTTP Endpoint to read the Google user Principal as shown below − <!DOCTYPE html> <html> <head> <meta charset = “ISO-8859-1”> <title>Insert title here</title> </head> <body> <a href = “user”>Click here to Google Login</a> </body> </html> Note − In Google Cloud console – Enable the Gmail Services, Analytics Services and Google+ service API(s). Then, go the Credentials section and create a credentials and choose OAuth Client ID. Next, provide a Product Name in OAuth2 consent screen. Next, choose the Application Type as “Web application”, provide the Authorized JavaScript origins and Authorized redirect URIs. Now, your OAuth2 Client Id and Client Secret is created. Next, add the Client Id and Client Secret in your application properties file. security.oauth2.client.clientId = <CLIENT_ID> security.oauth2.client.clientSecret = <CLIENT_SECRET> security.oauth2.client.accessTokenUri = https://www.googleapis.com/oauth2/v3/token security.oauth2.client.userAuthorizationUri = https://accounts.google.com/o/oauth2/auth security.oauth2.client.tokenName = oauth_token security.oauth2.client.authenticationScheme = query security.oauth2.client.clientAuthenticationScheme = form security.oauth2.client.scope = profile email security.oauth2.resource.userInfoUri = https://www.googleapis.com/userinfo/v2/me security.oauth2.resource.preferTokenInfo = false Now, you can create an executable JAR file, and run the Spring Boot application by using the following Gradle command. For Gradle, you can use the command as shown − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Run the JAR file by using the command java –jar <JARFILE> and application is started on the Tomcat port 8080. Now hit the URL http://localhost:8080/ and click the Google Login link. It will redirect to the Google login screen and provide a Gmail login details. If login success, we will receive the Principal object of the Gmail user. Print Page Previous Next Advertisements ”;

Spring Boot – Home

Spring Boot Tutorial PDF Version Quick Guide Resources Job Search Discussion Spring Boot is an open source Java-based framework used to create a Micro Service. It is developed by Pivotal Team. It is easy to create a stand-alone and production ready spring applications using Spring Boot. Spring Boot contains a comprehensive infrastructure support for developing a micro service and enables you to develop enterprise-ready applications that you can “just run”. Audience This tutorial is designed for Java developers to understand and develop production-ready spring applications with minimum configurations. It explores major features of Spring Boot such as Starters, Auto-configuration, Beans, Actuator and more. By the end of this tutorial, you will gain an intermediate level of expertise in Spring Boot. Prerequisites This tutorial is written for readers who have a prior experience of Java, Spring, Maven, and Gradle. You can easily understand the concepts of Spring Boot if you have knowledge on these concepts. It would be an additional advantage if you have an idea about writing a RESTful Web Service. If you are a beginner, we suggest you to go through tutorials related to these concepts before you start with Spring Boot. Print Page Previous Next Advertisements ”;

Spring Boot – Code Structure

Spring Boot – Code Structure ”; Previous Next Spring Boot does not have any code layout to work with. However, there are some best practices that will help us. This chapter talks about them in detail. Default package A class that does not have any package declaration is considered as a default package. Note that generally a default package declaration is not recommended. Spring Boot will cause issues such as malfunctioning of Auto Configuration or Component Scan, when you use default package. Note − Java”s recommended naming convention for package declaration is reversed domain name. For example − com.tutorialspoint.myproject Typical Layout The typical layout of Spring Boot application is shown in the image given below − The Application.java file should declare the main method along with @SpringBootApplication. Observe the code given below for a better understanding − package com.tutorialspoint.myproject; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) {SpringApplication.run(Application.class, args);} } Print Page Previous Next Advertisements ”;

Spring Boot – Discussion

Discuss Spring Boot ”; Previous Next Spring Boot is an open source Java-based framework used to create a Micro Service. It is developed by Pivotal Team. It is easy to create a stand-alone and production ready spring applications using Spring Boot. Spring Boot contains a comprehensive infrastructure support for developing a microservice and enables you to develop enterprise-ready applications that you can “just run”. Print Page Previous Next Advertisements ”;

Spring Boot – Useful Resources

Spring Boot – Useful Resources ”; Previous Next The following resources contain additional information on Spring Boot. Please use them to get more in-depth knowledge on this. Useful Links on Spring Boot Spring Framework − Wikipedia Reference for Spring Boot. Official Website − Official Website of Spring Boot. Useful Books on Spring Boot To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;

Securing Web Applications

Spring Boot – Securing Web Applications ”; Previous Next If a Spring Boot Security dependency is added on the classpath, Spring Boot application automatically requires the Basic Authentication for all HTTP Endpoints. The Endpoint “/” and “/home” does not require any authentication. All other Endpoints require authentication. For adding a Spring Boot Security to your Spring Boot application, we need to add the Spring Boot Starter Security dependency in our build configuration file. Maven users can add the following dependency in the pom.xml file. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> Gradle users can add the following dependency in the build.gradle file. compile(“org.springframework.boot:spring-boot-starter-security”) Securing a Web application First, create an unsecure web application by using Thymeleaf templates. Then, create a home.html file under src/main/resources/templates directory. <!DOCTYPE html> <html xmlns = “http://www.w3.org/1999/xhtml” xmlns:th = “http://www.thymeleaf.org” xmlns:sec = “http://www.thymeleaf.org/thymeleaf-extras-springsecurity3”> <head> <title>Spring Security Example</title> </head> <body> <h1>Welcome!</h1> <p>Click <a th:href = “@{/hello}”>here</a> to see a greeting.</p> </body> </html> The simple view /hello defined in the HTML file by using Thymeleaf templates. Now, create a hello.html under src/main/resources/templates directory. <!DOCTYPE html> <html xmlns = “http://www.w3.org/1999/xhtml” xmlns:th = “http://www.thymeleaf.org” xmlns:sec = “http://www.thymeleaf.org/thymeleaf-extras-springsecurity3”> <head> <title>Hello World!</title> </head> <body> <h1>Hello world!</h1> </body> </html> Now, we need to setup the Spring MVC – View controller for home and hello views. For this, create a MVC configuration file that extends WebMvcConfigurerAdapter. package com.tutorialspoint.websecuritydemo; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController(“/home”).setViewName(“home”); registry.addViewController(“/”).setViewName(“home”); registry.addViewController(“/hello”).setViewName(“hello”); registry.addViewController(“/login”).setViewName(“login”); } } Now, add the Spring Boot Starter security dependency to your build configuration file. Maven users can add the following dependency in your pom.xml file. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> Gradle users can add the following dependency in the build.gradle file. compile(“org.springframework.boot:spring-boot-starter-security”) Now, create a Web Security Configuration file, that is used to secure your application to access the HTTP Endpoints by using basic authentication. package com.tutorialspoint.websecuritydemo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers(“/”, “/home”).permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage(“/login”) .permitAll() .and() .logout() .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser(“user”).password(“password”).roles(“USER”); } } Now, create a login.html file under the src/main/resources directory to allow the user to access the HTTP Endpoint via login screen. <!DOCTYPE html> <html xmlns = “http://www.w3.org/1999/xhtml” xmlns:th = “http://www.thymeleaf.org” xmlns:sec = “http://www.thymeleaf.org/thymeleaf-extras-springsecurity3”> <head> <title>Spring Security Example </title> </head> <body> <div th:if = “${param.error}”> Invalid username and password. </div> <div th:if = “${param.logout}”> You have been logged out. </div> <form th:action = “@{/login}” method = “post”> <div> <label> User Name : <input type = “text” name = “username”/> </label> </div> <div> <label> Password: <input type = “password” name = “password”/> </label> </div> <div> <input type = “submit” value = “Sign In”/> </div> </form> </body> </html> Finally, update the hello.html file – to allow the user to Sign-out from the application and display the current username as shown below − <!DOCTYPE html> <html xmlns = “http://www.w3.org/1999/xhtml” xmlns:th = “http://www.thymeleaf.org” xmlns:sec = “http://www.thymeleaf.org/thymeleaf-extras-springsecurity3”> <head> <title>Hello World!</title> </head> <body> <h1 th:inline = “text”>Hello [[${#httpServletRequest.remoteUser}]]!</h1> <form th:action = “@{/logout}” method = “post”> <input type = “submit” value = “Sign Out”/> </form> </body> </html> The code for main Spring Boot application is given below − package com.tutorialspoint.websecuritydemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class WebsecurityDemoApplication { public static void main(String[] args) { SpringApplication.run(WebsecurityDemoApplication.class, args); } } The complete code for build configuration file is given below. Maven – pom.xml <?xml version = “1.0” encoding = “UTF-8”?> <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>com.tutorialspoint</groupId> <artifactId>websecurity-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>websecurity-demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!– lookup parent from repository –> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Gradle – build.gradle buildscript { ext { springBootVersion = ”1.5.9.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter-security”) compile(”org.springframework.boot:spring-boot-starter-thymeleaf”) compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) testCompile(”org.springframework.security:spring-security-test”) } Now, create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands. Maven users can use the command as given below − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under target directory. Gradle users can use the command as shown − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Now, run the JAR file by using the command shown below − java –jar <JARFILE> Hit the URL http://localhost:8080/ in your web browser. You can see the output as shown. Print Page Previous Next Advertisements ”;

Spring Boot – OAuth2 with JWT

Spring Boot – OAuth2 with JWT ”; Previous Next In this chapter, you will learn in detail about Spring Boot Security mechanisms and OAuth2 with JWT. Authorization Server Authorization Server is a supreme architectural component for Web API Security. The Authorization Server acts a centralization authorization point that allows your apps and HTTP endpoints to identify the features of your application. Resource Server Resource Server is an application that provides the access token to the clients to access the Resource Server HTTP Endpoints. It is collection of libraries which contains the HTTP Endpoints, static resources, and Dynamic web pages. OAuth2 OAuth2 is an authorization framework that enables the application Web Security to access the resources from the client. To build an OAuth2 application, we need to focus on the Grant Type (Authorization code), Client ID and Client secret.   JWT Token JWT Token is a JSON Web Token, used to represent the claims secured between two parties. You can learn more about the JWT token at www.jwt.io/. Now, we are going to build an OAuth2 application that enables the use of Authorization Server, Resource Server with the help of a JWT Token. You can use the following steps to implement the Spring Boot Security with JWT token by accessing the database. First, we need to add the following dependencies in our build configuration file. Maven users can add the following dependencies in your pom.xml file. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-jwt</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> Gradle users can add the following dependencies in the build.gradle file. compile(”org.springframework.boot:spring-boot-starter-security”) compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) testCompile(”org.springframework.security:spring-security-test”) compile(“org.springframework.security.oauth:spring-security-oauth2″) compile(”org.springframework.security:spring-security-jwt”) compile(“org.springframework.boot:spring-boot-starter-jdbc”) compile(“com.h2database:h2:1.4.191”) where, Spring Boot Starter Security − Implements the Spring Security Spring Security OAuth2 − Implements the OAUTH2 structure to enable the Authorization Server and Resource Server. Spring Security JWT − Generates the JWT Token for Web security Spring Boot Starter JDBC − Accesses the database to ensure the user is available or not. Spring Boot Starter Web − Writes HTTP endpoints. H2 Database − Stores the user information for authentication and authorization. The complete build configuration file is given below. <?xml version = “1.0” encoding = “UTF-8”?> <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>com.tutorialspoint</groupId> <artifactId>websecurityapp</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>websecurityapp</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath /> <!– lookup parent from repository –> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-jwt</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Gradle – build.gradle buildscript { ext { springBootVersion = ”1.5.9.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter-security”) compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) testCompile(”org.springframework.security:spring-security-test”) compile(“org.springframework.security.oauth:spring-security-oauth2″) compile(”org.springframework.security:spring-security-jwt”) compile(“org.springframework.boot:spring-boot-starter-jdbc”) compile(“com.h2database:h2:1.4.191”) } Now, in the main Spring Boot application, add the @EnableAuthorizationServer and @EnableResourceServer annotation to act as an Auth server and Resource Server in the same application. Also, you can use the following code to write a simple HTTP endpoint to access the API with Spring Security by using JWT Token. package com.tutorialspoint.websecurityapp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @EnableAuthorizationServer @EnableResourceServer @RestController public class WebsecurityappApplication { public static void main(String[] args) { SpringApplication.run(WebsecurityappApplication.class, args); } @RequestMapping(value = “/products”) public String getProductName() { return “Honey”; } } Use the following code to define the POJO class to store the User information for authentication. package com.tutorialspoint.websecurityapp; import java.util.ArrayList; import java.util.Collection; import org.springframework.security.core.GrantedAuthority; public class UserEntity { private String username; private String password; private Collection<GrantedAuthority> grantedAuthoritiesList = new ArrayList<>(); public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Collection<GrantedAuthority> getGrantedAuthoritiesList() { return grantedAuthoritiesList; } public void setGrantedAuthoritiesList(Collection<GrantedAuthority> grantedAuthoritiesList) { this.grantedAuthoritiesList = grantedAuthoritiesList; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } } Now, use the following code and define the CustomUser class that extends the org.springframework.security.core.userdetails.User class for Spring Boot authentication. package com.tutorialspoint.websecurityapp; import org.springframework.security.core.userdetails.User; public class CustomUser extends User { private static final long serialVersionUID = 1L; public CustomUser(UserEntity user) { super(user.getUsername(), user.getPassword(), user.getGrantedAuthoritiesList()); } } You can create the @Repository class to read the User information from the database and send it to the Custom user service and also add the granted authority “ROLE_SYSTEMADMIN”. package com.tutorialspoint.websecurityapp; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.stereotype.Repository; @Repository public class OAuthDao { @Autowired private JdbcTemplate jdbcTemplate; public UserEntity getUserDetails(String username) { Collection<GrantedAuthority> grantedAuthoritiesList = new ArrayList<>(); String userSQLQuery = “SELECT * FROM USERS WHERE USERNAME=?”; List<UserEntity> list = jdbcTemplate.query(userSQLQuery, new String[] { username }, (ResultSet rs, int rowNum) -> { UserEntity user = new UserEntity(); user.setUsername(username); user.setPassword(rs.getString(“PASSWORD”)); return user; }); if (list.size() > 0) { GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(“ROLE_SYSTEMADMIN”); grantedAuthoritiesList.add(grantedAuthority); list.get(0).setGrantedAuthoritiesList(grantedAuthoritiesList); return list.get(0); } return null; } } You can create a Custom User detail service class that extends the org.springframework.security.core.userdetails.UserDetailsService to call the DAO repository class as shown. package com.tutorialspoint.websecurityapp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; @Service public class CustomDetailsService implements UserDetailsService { @Autowired OAuthDao oauthDao; @Override public CustomUser loadUserByUsername(final String username) throws UsernameNotFoundException { UserEntity userEntity = null; try { userEntity = oauthDao.getUserDetails(username); CustomUser customUser = new CustomUser(userEntity); return customUser; } catch (Exception e) { e.printStackTrace(); throw new UsernameNotFoundException(“User ” + username + ” was not found in the database”); } } } Next, create a @configuration class to enable the Web Security, defining the Password encoder (BCryptPasswordEncoder), and defining the AuthenticationManager bean. The Security configuration class should extend WebSecurityConfigurerAdapter class. package com.tutorialspoint.websecurityapp; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

Spring Boot – Quick Start

Spring Boot – Quick Start ”; Previous Next This chapter will teach you how to create a Spring Boot application using Maven and Gradle. Prerequisites Your system need to have the following minimum requirements to create a Spring Boot application − Java 7 Maven 3.2 Gradle 2.5 Spring Boot CLI The Spring Boot CLI is a command line tool and it allows us to run the Groovy scripts. This is the easiest way to create a Spring Boot application by using the Spring Boot Command Line Interface. You can create, run and test the application in command prompt itself. This section explains you the steps involved in manual installation of Spring Boot CLI. For further help, you can use the following link: https://docs.spring.io/springboot/ docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-installing-springboot You can also download the Spring CLI distribution from the Spring Software repository at: https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-manual-cli-installation For manual installation, you need to use the following two folders − spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.zip spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.tar.gz After the download, unpack the archive file and follow the steps given in the install.txt file. Not that it does not require any environment setup. In Windows, go to the Spring Boot CLI bin directory in the command prompt and run the command spring –-version to make sure spring CLI is installed correctly. After executing the command, you can see the spring CLI version as shown below − Run Hello World with Groovy Create a simple groovy file which contains the Rest Endpoint script and run the groovy file with spring boot CLI. Observe the code shown here for this purpose − @Controller class Example { @RequestMapping(“/”) @ResponseBody public String hello() { “Hello Spring Boot” } } Now, save the groovy file with the name hello.groovy. Note that in this example, we saved the groovy file inside the Spring Boot CLI bin directory. Now run the application by using the command spring run hello.groovy as shown in the screenshot given below − Once you run the groovy file, required dependencies will download automatically and it will start the application in Tomcat 8080 port as shown in the screenshot given below − Once Tomcat starts, go to the web browser and hit the URL http://localhost:8080/ and you can see the output as shown. Print Page Previous Next Advertisements ”;