Cách Tích Hợp Đăng Nhập Google, GitHub Và Facebook Trong Ứng Dụng Java (Spring Boot)

Việc tích hợp đăng nhập bằng Google, GitHub hoặc Facebook đang trở thành một tiêu chuẩn phổ biến trong các hệ thống web hiện đại sử dụng Java (Spring Boot). Không chỉ mang lại trải nghiệm người dùng mượt mà hơn, hình thức đăng nhập này còn giúp đơn giản hóa việc xác thực và giảm thiểu rủi ro bảo mật liên quan đến mật khẩu. Bài viết dưới đây hướng dẫn cách cấu hình đăng nhập xã hội một cách hiệu quả và dễ hiểu. I. Tổng quan về OAuth 2.0 Tất cả các nền tảng đăng nhập xã hội lớn hiện nay đều sử dụng OAuth 2.0, một giao thức ủy quyền cho phép ứng dụng của bạn truy cập thông tin người dùng từ bên thứ ba (Google, Facebook, GitHub) mà không cần trực tiếp xử lý mật khẩu của họ. Spring Security hỗ trợ tích hợp OAuth 2.0 rất tốt thông qua spring-security-oauth2-client. II. Chuẩn Bị Môi Trường Java 17+ Spring Boot 3.x Spring Security Maven hoặc Gradle Thymeleaf (hoặc bất kỳ template engine nào) IDE như IntelliJ hoặc VS Code Thêm dependency trong pom.xml: org.springframework.boot spring-boot-starter-security org.springframework.boot spring-boot-starter-oauth2-client org.springframework.boot spring-boot-starter-thymeleaf III. Cấu hình đăng nhập Google 1. Đăng ký ứng dụng Google Truy cập: https://console.cloud.google.com/ Tạo một project mới Chọn "OAuth consent screen" → chọn "External" Điền các thông tin cơ bản (tên app, email) Chọn "Credentials" → Tạo "OAuth 2.0 Client ID" Ứng dụng: Web application Authorized redirect URIs: http://localhost:8080/login/oauth2/code/google 2. Cấu hình application.yml spring: security: oauth2: client: registration: google: client-id: YOUR_CLIENT_ID client-secret: YOUR_CLIENT_SECRET scope: profile, email 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 IV. Cấu hình đăng nhập với GitHub 1. Tạo OAuth App trên GitHub Truy cập: https://github.com/settings/developers New OAuth App: Homepage: http://localhost:8080 Authorization callback URL: http://localhost:8080/login/oauth2/code/github 2. Thêm vào application.yml: spring: security: oauth2: client: registration: github: client-id: YOUR_CLIENT_ID client-secret: YOUR_CLIENT_SECRET scope: read:user,user:email V. Cấu hình đăng nhập với Facebook 1. Tạo OAuth App trên GitHub Truy cập: https://developers.facebook.com Tạo App → Chọn Consumer Thêm sản phẩm "Facebook Login" → Cấu hình: Valid OAuth Redirect URIs: http://localhost:8080/login/oauth2/code/facebook 2. Thêm vào application.yml: spring: security: oauth2: client: registration: facebook: client-id: YOUR_CLIENT_ID client-secret: YOUR_CLIENT_SECRET scope: email, public_profile VI. Cấu hình Security @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers("/", "/login**").permitAll() .anyRequest().authenticated() ) .oauth2Login() .defaultSuccessUrl("/home", true); return http.build(); } } VII. Hiển thị giao diện Đăng nhập Đăng nhập bằng: Google GitHub Facebook VIII. Hiển thị thông tin người dùng sau khi đăng nhập @Controller public class HomeController { @GetMapping("/home") public String home(Model model, OAuth2AuthenticationToken authentication) { OAuth2User user = authentication.getPrincipal(); model.addAttribute("name", user.getAttribute("name")); model.addAttribute("email", user.getAttribute("email")); return "home"; } } Trang chủ Xin chào, ! Email: Hiện tại thì mình đang học môn SEO trên trường, nên trong bài viết mình xin để một link về trang web mình SEO cho môn học: https://cynhub.id.vn . Cảm ơn các bạn đã đọc bài viết.

May 14, 2025 - 04:12
 0
Cách Tích Hợp Đăng Nhập Google, GitHub Và Facebook Trong Ứng Dụng Java (Spring Boot)

Việc tích hợp đăng nhập bằng Google, GitHub hoặc Facebook đang trở thành một tiêu chuẩn phổ biến trong các hệ thống web hiện đại sử dụng Java (Spring Boot). Không chỉ mang lại trải nghiệm người dùng mượt mà hơn, hình thức đăng nhập này còn giúp đơn giản hóa việc xác thực và giảm thiểu rủi ro bảo mật liên quan đến mật khẩu. Bài viết dưới đây hướng dẫn cách cấu hình đăng nhập xã hội một cách hiệu quả và dễ hiểu.

I. Tổng quan về OAuth 2.0
Tất cả các nền tảng đăng nhập xã hội lớn hiện nay đều sử dụng OAuth 2.0, một giao thức ủy quyền cho phép ứng dụng của bạn truy cập thông tin người dùng từ bên thứ ba (Google, Facebook, GitHub) mà không cần trực tiếp xử lý mật khẩu của họ. Spring Security hỗ trợ tích hợp OAuth 2.0 rất tốt thông qua spring-security-oauth2-client.

II. Chuẩn Bị Môi Trường
Java 17+
Spring Boot 3.x
Spring Security
Maven hoặc Gradle
Thymeleaf (hoặc bất kỳ template engine nào)
IDE như IntelliJ hoặc VS Code Thêm dependency trong pom.xml:


    
        org.springframework.boot
        spring-boot-starter-security
    
    
        org.springframework.boot
        spring-boot-starter-oauth2-client
    
    
        org.springframework.boot
        spring-boot-starter-thymeleaf
    

III. Cấu hình đăng nhập Google
1. Đăng ký ứng dụng Google
Truy cập: https://console.cloud.google.com/
Tạo một project mới
Chọn "OAuth consent screen" → chọn "External"
Điền các thông tin cơ bản (tên app, email)
Chọn "Credentials" → Tạo "OAuth 2.0 Client ID"
Ứng dụng: Web application
Authorized redirect URIs: http://localhost:8080/login/oauth2/code/google

2. Cấu hình application.yml

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: YOUR_CLIENT_ID
            client-secret: YOUR_CLIENT_SECRET
            scope: profile, email
        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

IV. Cấu hình đăng nhập với GitHub
1. Tạo OAuth App trên GitHub
Truy cập: https://github.com/settings/developers
New OAuth App:
Homepage: http://localhost:8080
Authorization callback URL: http://localhost:8080/login/oauth2/code/github

2. Thêm vào application.yml:

spring:
  security:
    oauth2:
      client:
        registration:
          github:
            client-id: YOUR_CLIENT_ID
            client-secret: YOUR_CLIENT_SECRET
            scope: read:user,user:email

V. Cấu hình đăng nhập với Facebook
1. Tạo OAuth App trên GitHub
Truy cập: https://developers.facebook.com
Tạo App → Chọn Consumer
Thêm sản phẩm "Facebook Login" → Cấu hình:
Valid OAuth Redirect URIs: http://localhost:8080/login/oauth2/code/facebook

2. Thêm vào application.yml:

spring:
  security:
    oauth2:
      client:
        registration:
          facebook:
            client-id: YOUR_CLIENT_ID
            client-secret: YOUR_CLIENT_SECRET
            scope: email, public_profile

VI. Cấu hình Security

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/", "/login**").permitAll()
                .anyRequest().authenticated()
            )
            .oauth2Login()
            .defaultSuccessUrl("/home", true);
        return http.build();
    }
}

VII. Hiển thị giao diện



 xmlns:th="http://www.thymeleaf.org">

    </span>Đăng nhập<span class="nt">


    

Đăng nhập bằng:

href="/oauth2/authorization/google">Google
href="/oauth2/authorization/github">GitHub
href="/oauth2/authorization/facebook">Facebook

VIII. Hiển thị thông tin người dùng sau khi đăng nhập

@Controller
public class HomeController {

    @GetMapping("/home")
    public String home(Model model, OAuth2AuthenticationToken authentication) {
        OAuth2User user = authentication.getPrincipal();
        model.addAttribute("name", user.getAttribute("name"));
        model.addAttribute("email", user.getAttribute("email"));
        return "home";
    }
}


 xmlns:th="http://www.thymeleaf.org">
</span>Trang chủ<span class="nt">

    

Xin chào, th:text="${name}">!

Email: th:text="${email}">

Hiện tại thì mình đang học môn SEO trên trường, nên trong bài viết mình xin để một link về trang web mình SEO cho môn học: https://cynhub.id.vn . Cảm ơn các bạn đã đọc bài viết.