Project to Implement Spring Cloud Security in a Spring Boot Application

We need to implement the spring cloud security of the spring project. First, we create the project in Google Cloud and create the OAuth Client ID then add it to the spring project.

Step 1: Open the Google Cloud Console and create the project it named google-cloud-security click the create button then create the cloud project in Google Cloud Console.


Step 2: Once create the project click on the credentials and again click on the OAuth Client ID option then create id of the OAuth of the google cloud console.


Step 3: In OAuth Client ID configuration add the spring app link and save the details then save client id and secret code details to add into the spring boot project.

Refer the image for client id and client secret details information it will help find the details after the create OAuth Client Id into the google cloud console.


Step 4: Create the spring project and it named as the spring-cloud-security on creating the project include the below dependencies into the project.

Dependencies:

  • OAuth2 Client
  • Spring Web
  • Spring Security
  • Thymeleaf

Once create the project then the file structure looks like the below image.


Step 5: Open the application.properties and it renamed as application.yml file and put the below code for the OAuth Client ID configuration into the project.

spring:
security:
oauth2:
client:
registration:
google:
client-id: 66985898397-p1io24vn17sdm658fl6ndtio65h17if9.apps.googleusercontent.com
client-secret: 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
scope:
- openid
- profile
- email
redirect-uri: "http://localhost:8080/login/oauth2/code/google"
provider:
google:
authorization-uri: "https://accounts.google.com/o/oauth2/auth"
token-uri: "https://oauth2.googleapis.com/token"
user-info-uri: "https://openidconnect.googleapis.com/v1/userinfo"
user-name-attribute: name


Step 6: Create the new java class and it named as Auth2Config and this class can be OAuth configure of the application.

Go to src > springcloudsecurity > Auth2Config and put the below code.

Java
package com.gfg.springcloudsecurity;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@EnableWebSecurity
public class Auth2Config  {



    protected SecurityFilterChain configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .requestMatchers("/", "/login**", "/error**").permitAll()
                .anyRequest().authenticated()
                .and()
                .oauth2Login()
                .loginPage("/login"); // Custom login page URL, if needed

        return http.build();
    }
}



Step 7: Create the new Java class and it named as HomeController and this class can handles the requests of the user.

Go to src > springcloudsecurity > HomeController and put the below code.

Java
package com.gfg.springcloudsecurity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping("/")
    public String home() {
        return "home"; // Returns the home.html template
    }

    @GetMapping("/login")
    public String login() {
        return "login"; // Returns the login.html template
    }

    @GetMapping("/user")
    public String getUserInfo(OAuth2AuthenticationToken authenticationToken, Model model) {
        if (authenticationToken != null) {
            String email = authenticationToken.getPrincipal().getAttribute("email");
            String name = authenticationToken.getPrincipal().getAttribute("name");
            model.addAttribute("name", name);
            model.addAttribute("email", email);
            return "user";
        } else {
            return "redirect:/login";
        }
    }
}



Step 8: Open the main class and put the below code.

Java
package com.gfg.springcloudsecurity;

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

@SpringBootApplication
public class SpringCloudSecurityApplication {

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

}


Step 9: Create the html page and it named as home.html.

Go to src > resources > home.html and put the code below.

HTML
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Home</title>
</head>
<body>
<h1>Welcome to the Home Page</h1>
<a th:href="@{/login}">Login with Google</a>
</body>
</html>


Step 10: Create the html page and it named as login.html.

Go to src > resources > login.html and put the code below.

Java
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
<h1>Login</h1>
<a th:href="@{/oauth2/authorization/google}">Login with Google</a>
</body>
</html>


Step 11: Create the html page and it named as user.html.

Go to src > resources > user.html and put the code below.

HTML
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>User Profile</title>
</head>
<body>
<h1>Welcome, <span th:text="${name}"></span>!</h1>
<p>Your email: <span th:text="${email}"></span></p>
<a th:href="@{/logout}">Logout</a>
</body>
</html>

pom.xml

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.gfg</groupId>
    <artifactId>spring-cloud-security</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-cloud-security</name>
    <description>spring-cloud-security</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>


Step 12: Once complete the spring project then it can run as spring project. It will run successfully then starts the application at port 8080.

Login Screen:

Home Page:

User Page:


Final Output:

Below in the output video, we can see the whole process and the final output.



Spring Cloud Security

Spring Cloud Security is part of the Spring Cloud ecosystem that can provide the tools and components to secure the microservices-based applications and it can integrate seamlessly with the Spring Boot and Spring Security to offer features such as authentication, authorization, token management, secure communication and protection against common the security threats.

Similar Reads

Project to Implement Spring Cloud Security in a Spring Boot Application

We need to implement the spring cloud security of the spring project. First, we create the project in Google Cloud and create the OAuth Client ID then add it to the spring project....

Contact Us