Spring Boot – Admin Server ”; Previous Next Monitoring your application by using Spring Boot Actuator Endpoint is slightly difficult. Because, if you have ‘n’ number of applications, every application has separate actuator endpoints, thus making monitoring difficult. Spring Boot Admin Server is an application used to manage and monitor your Microservice application. To handle such situations, CodeCentric Team provides a Spring Boot Admin UI to manage and monitor all your Spring Boot application Actuator endpoints at one place. For building a Spring Boot Admin Server we need to add the below dependencies in your build configuration file. Maven users can add the below dependencies in your pom.xml file − <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-server</artifactId> <version>1.5.5</version> </dependency> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-server-ui</artifactId> <version>1.5.5</version> </dependency> Gradle users can add the below dependencies in your build.gradle file − compile group: ”de.codecentric”, name: ”spring-boot-admin-server”, version: ”1.5.5” compile group: ”de.codecentric”, name: ”spring-boot-admin-server-ui”, version: ”1.5.5” Add the @EnableAdminServer annotation in your main Spring Boot application class file. The @EnableAdminServer annotation is used to make your as Admin Server to monitor all other microservices. package com.tutorialspoint.adminserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import de.codecentric.boot.admin.config.EnableAdminServer; @SpringBootApplication @EnableAdminServer public class AdminserverApplication { public static void main(String[] args) { SpringApplication.run(AdminserverApplication.class, args); } } Now, define the server.port and application name in application.properties file a shown − server.port = 9090 spring.application.name = adminserver For YAML users, use the following properties to define the port number and application name in application.yml file. server: port: 9090 spring: application: name: adminserver The build configuration file is given below. For Maven users – 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>adminserver</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>adminserver</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</artifactId> </dependency> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-server</artifactId> <version>1.5.5</version> </dependency> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-server-ui</artifactId> <version>1.5.5</version> </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> For Gradle users – build.gradle file 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”) compile group: ”de.codecentric”, name: ”spring-boot-admin-server”, version: ”1.5.5” compile group: ”de.codecentric”, name: ”spring-boot-admin-server-ui”, version: ”1.5.5” testCompile(”org.springframework.boot:spring-boot-starter-test”) } You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands − For Maven, use the command shown here − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under target directory. For Gradle, use the command shown here − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under build/libs directory. Now, run the JAR file by using the command given below − java –jar <JARFILE> Now, the application has started on the Tomcat port 9090 as shown here − Now hit the below URL from your web browser and see the Admin Server UI. http://localhost:9090/ Print Page Previous Next Advertisements ”;
Category: Java
Spring Boot – Logging
Spring Boot – Logging ”; Previous Next Spring Boot uses Apache Commons logging for all internal logging. Spring Boot’s default configurations provides a support for the use of Java Util Logging, Log4j2, and Logback. Using these, we can configure the console logging as well as file logging. If you are using Spring Boot Starters, Logback will provide a good support for logging. Besides, Logback also provides a use of good support for Common Logging, Util Logging, Log4J, and SLF4J. Log Format The default Spring Boot Log format is shown in the screenshot given below. which gives you the following information − Date and Time that gives the date and time of the log Log level shows INFO, ERROR or WARN Process ID The — which is a separator Thread name is enclosed within the square brackets [] Logger Name that shows the Source class name The Log message Console Log Output The default log messages will print to the console window. By default, “INFO”, “ERROR” and “WARN” log messages will print in the log file. If you have to enable the debug level log, add the debug flag on starting your application using the command shown below − java –jar demo.jar –debug You can also add the debug mode to your application.properties file as shown here − debug = true File Log Output By default, all logs will print on the console window and not in the files. If you want to print the logs in a file, you need to set the property logging.file or logging.path in the application.properties file. You can specify the log file path using the property shown below. Note that the log file name is spring.log. logging.path = /var/tmp/ You can specify the own log file name using the property shown below − logging.file = /var/tmp/mylog.log Note − files will rotate automatically after reaching the size 10 MB. Log Levels Spring Boot supports all logger levels such as “TRACE”, “DEBUG”, “INFO”, “WARN”, “ERROR”, “FATAL”, “OFF”. You can define Root logger in the application.properties file as shown below − logging.level.root = WARN Note − Logback does not support “FATAL” level log. It is mapped to the “ERROR” level log. Configure Logback Logback supports XML based configuration to handle Spring Boot Log configurations. Logging configuration details are configured in logback.xml file. The logback.xml file should be placed under the classpath. You can configure the ROOT level log in Logback.xml file using the code given below − <?xml version = “1.0” encoding = “UTF-8”?> <configuration> <root level = “INFO”> </root> </configuration> You can configure the console appender in Logback.xml file given below. <?xml version = “1.0” encoding = “UTF-8”?> <configuration> <appender name = “STDOUT” class = “ch.qos.logback.core.ConsoleAppender”></appender> <root level = “INFO”> <appender-ref ref = “STDOUT”/> </root> </configuration> You can configure the file appender in Logback.xml file using the code given below. Note that you need to specify the Log file path insider the file appender. <?xml version = “1.0” encoding = “UTF-8”?> <configuration> <appender name = “FILE” class = “ch.qos.logback.core.FileAppender”> <File>/var/tmp/mylog.log</File> </appender> <root level = “INFO”> <appender-ref ref = “FILE”/> </root> </configuration> You can define the Log pattern in logback.xml file using the code given below. You can also define the set of supported log patterns inside the console or file log appender using the code given below − <pattern>[%d{yyyy-MM-dd”T”HH:mm:ss.sss”Z”}] [%C] [%t] [%L] [%-5p] %m%n</pattern> The code for complete logback.xml file is given below. You have to place this in the class path. <?xml version = “1.0” encoding = “UTF-8”?> <configuration> <appender name = “STDOUT” class = “ch.qos.logback.core.ConsoleAppender”> <encoder> <pattern>[%d{yyyy-MM-dd”T”HH:mm:ss.sss”Z”}] [%C] [%t] [%L] [%-5p] %m%n</pattern> </encoder> </appender> <appender name = “FILE” class = “ch.qos.logback.core.FileAppender”> <File>/var/tmp/mylog.log</File> <encoder> <pattern>[%d{yyyy-MM-dd”T”HH:mm:ss.sss”Z”}] [%C] [%t] [%L] [%-5p] %m%n</pattern> </encoder> </appender> <root level = “INFO”> <appender-ref ref = “FILE”/> <appender-ref ref = “STDOUT”/> </root> </configuration> The code given below shows how to add the slf4j logger in Spring Boot main class file. package com.tutorialspoint.demo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { private static final Logger logger = LoggerFactory.getLogger(DemoApplication.class); public static void main(String[] args) { logger.info(“this is a info message”); logger.warn(“this is a warn message”); logger.error(“this is a error message”); SpringApplication.run(DemoApplication.class, args); } } The output that you can see in the console window is shown here − The output that you can see in the log file is shown here − Print Page Previous Next Advertisements ”;
TestNG – Useful Resources
TestNG – Useful Resources ”; Previous Next The following resources contain additional information on TestNG. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Selenium And Java Advanced Course with Live Project Best Seller 296 Lectures 146 hours Arun Motoori More Detail TestNG Complete Bootcamp For Beginners 39 Lectures 4.5 hours Lets Kode It More Detail Selenium WebDriver 4 with Java – Zero To Hero Most Popular 294 Lectures 41.5 hours Lets Kode It More Detail தமிழ் மொழியில் Selenium கற்றுக்கொள்ளுங்கள் | Learn Selenium 35 Lectures 8.5 hours Programming Line More Detail Learn TestNG 15 Lectures 1.5 hours Quaatso Learning More Detail The Complete Selenium WebDriver with Java Course Most Popular 202 Lectures 21 hours Dezlearn Education More Detail Print Page Previous Next Advertisements ”;
TestNG – Overview
TestNG – Overview ”; Previous Next Testing is the process of checking the functionality of an application to ensure it works as per requirements. Unit testing comes into picture at the developer level where adequate measures are taken to test every single entity (class or method) to ensure the final product meets the requirements. JUnit has driven developers to understand the usefulness of tests, especially of unit tests, when compared to any other testing framework. Leveraging a rather simple, pragmatic, and strict architecture, JUnit has been able to “infect” great number of developers. Do take a look at our tutorial on JUnit to have a good understanding of its features. JUnit, at the same time, has some shortcomings as well, which are listed below − Initially designed to enable unit testing only, now used for all kinds of testing. Cannot do dependency testing. Poor configuration control (setUp/tearDown). Intrusive (forces you to extend classes and name your methods a certain way). Static programming model (forces you to recompile unnecessarily). The management of different suites of tests in complex projects can be very tricky. What is TestNG? Definition of TestNG as per its documentation is as follows − TestNG is a testing framework inspired from JUnit and NUnit, but introducing some new functionalities that make it more powerful and easier to use. TestNG is an open source automated testing framework; where NG means NextGeneration. TestNG is similar to JUnit (especially JUnit 4), but it is not a JUnit extension. It is inspired by JUnit. It is designed to be better than JUnit, especially when testing integrated classes. The creator of TestNG is Cedric Beust. Eliminating most of the limitations of the older framework, TestNG gives the developer the ability to write more flexible and powerful tests. As it heavily borrows from Java Annotations (introduced with JDK 5.0) to define tests, it can also show you how to use this new feature of the Java language in a real production environment. TestNG Features Supports annotations. TestNG uses more Java and OO features. Supports testing integrated classes (e.g., by default, no need to create a new test class instance for every test method). Separates compile-time test code from run-time configuration/data info. Flexible runtime configuration. Introduces ‘test groups’. Once you have compiled your tests, you can just ask TestNG to run all the “front-end” tests, or “fast”, “slow”, “database” tests, etc. Supports Dependent test methods, parallel testing, load testing, and partial failure. Flexible plug-in API. Support for multi threaded testing. Print Page Previous Next Advertisements ”;
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 – 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 ”; 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 ”;