DEV Community

Shelner
Shelner

Posted on

Step-by-step Guid: Google Authentication with Spring Boot

Step-by-step Guid: Google Authentication with Spring Boot

1. Create a project

You can use Spring Initializr and select the following dependencies:

  • Spring Web
  • Spring Security
  • OAuth2 Client
  • Thymeleaf (optional, for testing UI)

Or you can add them in your pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</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-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity6</artifactId>
</dependency>
Enter fullscreen mode Exit fullscreen mode

2. Create Google OAuth Credentials

Go to Google Cloud Console:

  1. Create a project.
  2. Navigate to "APIs & Service" > "Credentials"
  3. Click "Create Credentials" > "OAuth 2.0 Client IDs"
  4. Set:
    • Application type: "Web application"
    • Name: Your project name
    • Authorized redirect URIs: http://localhost:8080/login/oauth2/code/google Copy the Client ID and Client Secret.

3. Configure application.yml or application.properties

Using application.yml:

spring:
    security:
        oauth2:
            client:
                registration:
                    google:
                        client-id: YOUR_CLIENT_ID
                        client-secret: YOUR_CLIENT_SECRET
                        scope:
                            - email
                            - profile
                provider:
                    google:
                        authorization-uri: https://accounts.google.com/o/oauth2/v2/auth
                        token-uri: https://oauth2.googleapis.com/token
                        user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo
                        user-name-attribute: sub
Enter fullscreen mode Exit fullscreen mode

4. Create a Security Configuration

Spring Boot auto-configures basic OAuth login, but you can customize with security config:

// src/main/java/com.example.demo/SecurityConfig.java

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/", "/css/**", "/js/**").permitAll()
                .anyRequest().authenticated()
            )
            .oauth2Login(); // Enables Google OAuth login
        return http.build();
    }
}
Enter fullscreen mode Exit fullscreen mode

5. Create a Simple Controller

// src/main/java/com.example.demo/MainController.java

import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MainController {
    @GetMapping("/")
    public String home() {
        return "home"; // a public page
    }

    @GetMapping("/dashboard")
    public String dashboard(Model model, OAuth2AuthenticationToken authentication) {
        Map<String, Object> attributes = authentication.getPrincipal().getAttributes();
        model.addAttribute("name", attributes.get("name"));
        model.addAttribute("email", attributes.get("email"));
        return "dashboard"; // Secured page
    }
}
Enter fullscreen mode Exit fullscreen mode

6. Create Template

Create the file at: src/main/resources/templates/home.html

<!-- home.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Home</title>
</head>
<body>
    <h1>Welcome to the public home page</h1>
    <a href="/dashboard">Go to Dashboard</a>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Create the file at: src/main/resources/templates/dashboard.html

<!-- dashboard.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Dashboard</title>
</head>
<body>
    <h1>Welcome to the secure dashboard page</h1>
    <a href="/">Home</a>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

7. Run and Test

  1. Run your Spring Boot app.
  2. Navigate to http://localhost:8080/dashboard
  3. You'll be redirected to Google for login.
  4. After login, you'll return to /dashboard with your authenticated session.

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.