CodeGym /Courses /Module 5. Spring /Lecture 108: Hands-on — setting up OAuth2 for authenticat...

Lecture 108: Hands-on — setting up OAuth2 for authentication via third-party services

Module 5. Spring
Level 18 , Lesson 7
Available

If up until now we studied OAuth2, its architecture and principles theoretically, it's time to roll up our sleeves and get our hands dirty with code. It's time to see OAuth2 in action. Today we'll set up authentication via third-party services like Google and GitHub and learn how to integrate them into our Spring Boot apps. Ready? Let's go!


Why use third-party providers?

Using third-party services for authentication is super convenient. The app doesn't store user passwords (and doesn't take on that responsibility), which immediately makes it safer. Besides, OAuth2 makes it easy to hook up authentication via Google, GitHub, or Facebook and gives users the option to sign into your app with one click!


What are we going to build?

We'll create a Spring Boot application that lets users sign in using their Google or GitHub accounts. The app will show a personalized greeting for authenticated users.

Application architecture

  1. Spring Boot: the foundation of our app.
  2. Spring Security OAuth2: handling all the OAuth2 magic.
  3. Google and GitHub: authentication providers (you can swap them for others, but we picked these two because they're popular).
  4. Thymeleaf: for rendering simple pages.

Configuring the OAuth2 application

Step 1: Creating a Spring Boot project

First, create a new Spring Boot project. Include dependencies for Spring Security and OAuth2 support:

pom.xml (for Maven)


<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
  </dependency>
  <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>
</dependencies>

build.gradle (for Gradle)


dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
}

Step 2: Setting up Google OAuth2

Now register your app in the Google Console.

  1. Go to Google Developer Console.
  2. Create a new project.
  3. Configure the OAuth Consent Screen (add info about your app).
  4. Go to "Credentials" → "Create Credentials" → "OAuth 2.0 Client IDs".
    • Select application type: "Web application".
    • Add the address http://localhost:8080/login/oauth2/code/google to Authorized Redirect URIs.

Save the Client ID and Client Secret. You'll need them for configuration.


Step 3: Setting up GitHub OAuth2

  1. Go to GitHub Developer Settings.
  2. Create a new application (New OAuth App).
    • Set the Homepage URL: http://localhost:8080.
    • Set the Authorization callback URL: http://localhost:8080/login/oauth2/code/github.

Save the issued Client ID and Client Secret.

Step 4: Configuring application.yml

Add settings for the third-party providers in application.yml (or application.properties).


spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: YOUR_GOOGLE_CLIENT_ID
            client-secret: YOUR_GOOGLE_CLIENT_SECRET
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
            scope:
              - email
              - profile
          github:
            client-id: YOUR_GITHUB_CLIENT_ID
            client-secret: YOUR_GITHUB_CLIENT_SECRET
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
            scope:
              - read:user
              - user:email
        provider:
          github:
            authorization-uri: https://github.com/login/oauth/authorize
            token-uri: https://github.com/login/oauth/access_token
            user-info-uri: https://api.github.com/user

Replace YOUR_GOOGLE_CLIENT_ID, YOUR_GOOGLE_CLIENT_SECRET, YOUR_GITHUB_CLIENT_ID, and YOUR_GITHUB_CLIENT_SECRET with the corresponding values.

Step 5: Configuring Spring Security

Now let's create the security configuration using Spring Security.


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

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/", "/login").permitAll()
                .anyRequest().authenticated()
            )
            .oauth2Login(oauth2 -> oauth2
                .loginPage("/login")
                .defaultSuccessUrl("/profile")
            );
        return http.build();
    }
}

Step 6: Controller for user handling

Let's add a controller to show a welcome page after successful authentication.


import org.springframework.security.core.annotation.AuthenticationPrincipal;
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 UserController {

    @GetMapping("/")
    public String home() {
        return "home";
    }

    @GetMapping("/profile")
    public String profile(Model model, @AuthenticationPrincipal OAuth2User principal) {
        model.addAttribute("name", principal.getAttribute("name"));
        model.addAttribute("email", principal.getAttribute("email"));
        return "profile";
    }
}

Step 7: Creating the HTML pages

templates/home.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>Home</title>
</head>
<body>
  <h1>Welcome!</h1>
  <a href="/oauth2/authorization/google">Login with Google</a>
  <a href="/oauth2/authorization/github">Login with GitHub</a>
</body>
</html>

templates/profile.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>Profile</title>
</head>
<body>
  <h1>Welcome, <span th:text="${name}"></span>!</h1>
  <p>Email: <span th:text="${email}"></span></p>
</body>
</html>

Practical testing

  1. Run the application.
  2. Open http://localhost:8080.
  3. Choose an authentication method: Google or GitHub.
  4. After a successful sign-in you'll be redirected to the Profile page, where the name and email provided by the provider will be displayed.

Troubleshooting

If something goes wrong during setup, here are a few tips:

  • Make sure you've set the Redirect URI correctly for each provider.
  • Check that the Client ID and Client Secret match what's shown in the console.
  • If you get a 401 Unauthorized, check the scopes in application.yml.

Today you made a big step in mastering modern authentication methods. You felt the real OAuth2 magic when you saw how easy it is to integrate Google and GitHub authentication. In real projects, this kind of authentication not only boosts security but also improves the user experience. And most importantly — now you know exactly how it works!

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION