Skip to content

Blog Công Nghệ

MENUMENU
  • Trang chủ
  • Giới Thiệu
  • Lập Trình
    • Lập Trình Website
      • Laravel
        • Phân Tích Dự Án
      • PHP
      • SQL
      • HTML
      • CSS
      • Javascipt
      • My Project
      • Wordpress
    • Luyện Skill
    • Lập trình winform
    • CSDL
    • Lập Trình Android
    • Trí tuệ nhân tạo
    • Khai Khoáng Dữ Liệu
    • Arduino
    • Khác
    • Đồ án
  • Phần Mềm
    • Powerpoint
    • Tool
  • Cuộc sống và Giải trí
    • Hợp âm
    • web5ngay - youtube
    • Công Giáo
    • Kỹ Năng Sống
    • Street Workout
  • Danh sách bài viết
  • Guide line
    • Guild line phỏng vấn
    • Guide lines Laravel
    • Guide line Module Frontend
  • Tóm tắt sách
  • Fanpage

Blog Công Nghệ

Nơi chia sẻ kiến thức

Xử lý đăng nhập bằng Google

11 Tháng Mười, 2022 by admin
Lượt xem: 164

Ở bài trước mình đã hướng dẫn các bạn xử lý đăng nhập bằng facebook, hôm nay mình sẽ hướng dẫn đăng nhập bằng google nhé!

Contents

  • 1. Tạo Application
  • 2. Xử lý bằng PHP
  • 3. Xử lý với laravel
  • 4. Xử lý với C# Web
  • Kết Luận

1. Tạo Application

Bước 1: Bạn đăng nhập bằng tài khoản google của bạn và vào đây nhé!

Bước 2: Điền tên app

Bước 3:

Bước 4:

Bước 5: Nhấn vào identify/ Credentials ở menu bên trái có biểu tượng hình chìa khóa

Bước 6:

Có thể thay thành đường dẫn localhost nhé!

Bạn sẽ được 2 thông tin quan trọng để xử lý login google.

Bên dưới có nhiều cách kết nối, bạn chọn cách phù hợp với dự án của mình nhé!

2. Xử lý bằng PHP

  • document: thư viện google api 

Bước 1: Bạn download thư viện api của google bằng composer

composer require google/apiclient:"^2.0"

Bước 2: Bạn tạo file config.php cùng cấp với thư mục vendor. Và copy nội dung sau vào file đó!

<?php  
	require_once 'vendor/autoload.php';

	$gClient = new Google_Client();
	$gClient->setClientId("");
	$gClient->setClientSecret("");
	$gClient->setApplicationName("CPI Login Tutorial");
	$gClient->setRedirectUri("http://localhost/gg2/g-callback.php");
	$gClient->addScope("https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email");

	$loginURL = $gClient->createAuthUrl(); // lấy link đăng nhập
	
	/*
     * setClientId và setClientSecret: bạn lấy ở phần tạo app lúc nãy điền vào
     * setApplicationName: Thay đổi tên cho phù hợp
     * setRedirectUri: để giống như lúc bạn tạo app
     * addScope: các quyền yêu cầu người dùng
    */
?>

Xem thêm các quyền – Scope của google: https://developers.google.com

Bước 3: Tạo file index.php

<?php  
	require_once "config.php";
?>

<a href="<?php echo $loginURL; ?>">Login</a>

Lúc này bạn đã có thể chạy được đăng nhập như thế này!

Bước 4: tạo file g-callback.php là file nhận kết quả trả về mình đã khai báo ở lúc tạo app và ở file config.php

<?php
	require_once "config.php";


	if (isset($_SESSION['access_token']))
		$gClient->setAccessToken($_SESSION['access_token']);
	else if (isset($_GET['code'])) {
		$token = $gClient->fetchAccessTokenWithAuthCode($_GET['code']);
		$_SESSION['access_token'] = $token;
	} else {
		header('Location: index.php');
		exit();
	}

	$oAuth = new Google_Service_Oauth2($gClient);
	$userData = $oAuth->userinfo_v2_me->get();

	echo "<pre>";
	print_r($userData);
	echo "</pre>";

?>

Lúc này bạn đã có data ở dạng mảng. Muốn lấy thông tin nào ra thì:

$userData["email"] //ví dụ ở đây mình lấy email

Như vậy là xong, à còn khi đăng xuất thì phải xóa token bằng cách

<?php
	require_once "config.php";
	unset($_SESSION['access_token']);
	$gClient->revokeToken();
	session_destroy();
	header('Location: index.php');
	exit();
?>

3. Xử lý với laravel

Bước 1: Cài thư viện

composer require google/apiclient

Bước 2: Tạo route

Route::get('login-google', 'GoogleController@login');
Route::get('callback', 'GoogleController@callback');

Bước 3: Tạo GoogleController

php artisan make:controller GoogleController

Nội dung Controller như sau:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Google_Client;
use Google_Service_Oauth2;

class GoogleController extends Controller
{
	private $gClient;

	public function __construct() {
		$this->gClient = new Google_Client();
		$this->gClient->setClientId("");
		$this->gClient->setClientSecret("");
		$this->gClient->setApplicationName("CPI Login Tutorial");
		$this->gClient->setRedirectUri("http://localhost/lar6/callback");
		$this->gClient->addScope("https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email");
		/*
           * setClientId và setClientSecret: bạn lấy ở phần tạo app lúc nãy điền vào
           * setApplicationName: Thay đổi tên cho phù hợp
           * setRedirectUri: để giống như lúc bạn tạo app
           * addScope: các quyền yêu cầu người dùng
        */
    }

    public function login() {
    	$loginURL = $this->gClient->createAuthUrl(); //Lấy link đăng nhập google
    	return view('login')->with(compact('loginURL'));
    }

    public function callback() {
		if (isset($_SESSION['access_token']))
			$this->gClient->setAccessToken($_SESSION['access_token']);
		else if (isset($_GET['code'])) {
			$token = $this->gClient->fetchAccessTokenWithAuthCode($_GET['code']);
			$_SESSION['access_token'] = $token;
		} else {
			header('Location: index.php');
			exit();
		}

		$oAuth = new Google_Service_Oauth2($this->gClient);
		$userData = $oAuth->userinfo_v2_me->get();

		echo "<pre>";
		print_r($userData);
		echo "</pre>";
    }
}

Còn phải tạo view nữa nha! Bạn tạo file login.blade.php trong resource/views nhé

<a href="<?php echo $loginURL; ?>">Login</a>

Lúc này bạn đã có data ở dạng mảng. Muốn lấy thông tin nào ra thì:

$userData["email"] //ví dụ ở đây mình lấy email

Có dữ liệu rồi muốn xử sao thì tùy các bạn.

Như vậy là xong, à còn khi đăng xuất thì phải xóa token bằng cách tạo hàm này trong GoogleController.

public function logout(Request $request) {
  	$request->session()->forget('access_token');
	$this->gClient->revokeToken();
	$request->session()->flush();
	return redirect(....);
}

4. Xử lý với C# Web

Đầu tiên bạn tạo mới một project:

Bạn add Thư viện DotNetOpenAuth này vào project nhé (thư mục bin) và nhớ là kéo thả vào vào project đừng copy, nếu không Solution Explorer sẽ không nhận.

Download thư viện: http://www.mediafire.com/file/byf9wu43yw

Sau đó thêm một file login.aspx

Tại file này bạn thiết kế một button để đăng nhập google nhé. Nháy đúp vào nút này để chuyển sang code behind (nơi viết code xử lý).

protected void btnDangNhapGoogle_Click(object sender, EventArgs e)
{
  //your client id  
  string clientid = "xxxxxxxxxxxxxxxx";
  //your client secret  
  string clientsecret = "xxxxxxxxxxxxxxxx";
  //your redirection url  
  string redirection_url = "xxxxxxxxxxxxxxxx";
  string url = "https://accounts.google.com/o/oauth2/v2/auth?scope=profile%20email&include_granted_scopes=true&redirect_uri=" + redirection_url + "&response_type=code&client_id=" + clientid + "";
  Response.Redirect(url);
}

// client id và client secret bạn copy của phần số 1 gắn vào nhé.
// redirection_url là phần địa chỉ để google trả về bạn cũng cấu hình ở phần số 1 luôn đấy
// url chỗ này là các quyền mà bạn có thể lấy thông tin nhưng chỗ này không nên thay đổi

Đây là ClientID và Client secret ở bước 1.

Và bên dưới là địa chỉ mà google sẽ trả dữ liệu về mình cấu hình ở bước 1 đấy.

Mình tạm lấy địa chỉ trả về sẽ là http://localhost:1526/google-callback.aspx nha.

Vậy là mình cần có file google-callback.aspx để google trả kết quả về. Bạn tạo file này và nháy chuột phải chọn view code để vào code behind nhé.

Tiếp theo bạn copy đoạn code sau vào trên hàm Page_Load: và nhớ thay các giá trị như lúc nãy nhé

//your client id  
string clientid = "xxxxxxxxxxxxxxxx";
//your client secret  
string clientsecret = "xxxxxxxxxxxxxxxx";
//your redirection url  
string redirection_url = "xxxxxxxxxxxxxxxx";
string url = "https://accounts.google.com/o/oauth2/token";
private object imgprofile;

Dưới hàm page_load bạn thêm code sau vào

public void GetToken(string code)
{
  string poststring = "grant_type=authorization_code&code=" + code + "&client_id=" + clientid + "&client_secret=" + clientsecret + "&redirect_uri=" + redirection_url + "";
  var request = (HttpWebRequest)WebRequest.Create(url);
  request.ContentType = "application/x-www-form-urlencoded";
  request.Method = "POST";
  UTF8Encoding utfenc = new UTF8Encoding();
  byte[] bytes = utfenc.GetBytes(poststring);
  Stream outputstream = null;
  try
  {
    request.ContentLength = bytes.Length;
    outputstream = request.GetRequestStream();
    outputstream.Write(bytes, 0, bytes.Length);
  }
  catch { }
  var response = (HttpWebResponse)request.GetResponse();
  var streamReader = new StreamReader(response.GetResponseStream());
  string responseFromServer = streamReader.ReadToEnd();
  JavaScriptSerializer js = new JavaScriptSerializer();
  Tokenclass obj = js.Deserialize<Tokenclass>(responseFromServer);
  GetuserProfile(obj.access_token);
}
public void GetuserProfile(string accesstoken)
{
  string url = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + accesstoken + "";
  WebRequest request = WebRequest.Create(url);
  request.Credentials = CredentialCache.DefaultCredentials;
  WebResponse response = request.GetResponse();
  Stream dataStream = response.GetResponseStream();
  StreamReader reader = new StreamReader(dataStream);
  string responseFromServer = reader.ReadToEnd();
  reader.Close();
  response.Close();
  JavaScriptSerializer js = new JavaScriptSerializer();
  Userclass userinfo = js.Deserialize < Userclass > (responseFromServer);
  //Response.Write(responseFromServer);
}

Đến đây có thể sẽ có khá nhiều lỗi đỏ, bình tĩnh mình sẽ gỡ từ từ. Ở hàm Page_Load bạn thêm code sau vào.

protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    if (Request.QueryString["code"] != null)
    {
      GetToken(Request.QueryString["code"].ToString());
    }
  }
}

Tiếp theo hãy tạo một file Tokenclass.cs bằng cách nháy chuột phải vào project => Add => Add New Item…  => Class   và nhập tên class là Tokenclass.cs. Nội dung file này bạn copy code bên dưới nhé! 

public class Tokenclass
{
    public string access_token { get; set; }  
    public string token_type { get; set; }  
    public int expires_in { get; set; }  
    public string refresh_token { get; set; }  
}

//Nếu có code mà class tạo sẵn thì xóa hết và copy này vào thôi nhé

Tương tự tạo một file Userclass.cs   Copy code bên dưới dán vào

public class Userclass
{
    public string id { get; set; }  
    public string name { get; set; }  
    public string given_name { get; set; }  
    public string family_name { get; set; }  
    public string link { get; set; }  
    public string picture { get; set; }  
    public string gender { get; set;}  
    public string locale {  get; set; }
    public string email { get; set; }
}

Quay trở lại file gg-calback.aspx bạn nháy chuột phải chọn view code để vào code behind.

Ở các phần lỗi đỏ bạn rê chuột vào có hình bóng đèn sáng, bạn mở bóng đèn và chọn cái lựa chọn đầu tiên nhé. Làm đến khi hết lỗi là ok.

Mọi chuyện đã xong xuôi. Phần code của gg-callback.aspx sẽ trông như thế này

//your client id  
string clientid = "xxxxxxxxxxxxxxxx";
//your client secret  
string clientsecret = "xxxxxxxxxxxxxxxx";
//your redirection url  
string redirection_url = "xxxxxxxxxxxxxxxx";
string url = "https://accounts.google.com/o/oauth2/token";
private object imgprofile;

protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    if (Request.QueryString["code"] != null)
    {
      GetToken(Request.QueryString["code"].ToString());
    }
  }
}

public void GetToken(string code)
{
  string poststring = "grant_type=authorization_code&code=" + code + "&client_id=" + clientid + "&client_secret=" + clientsecret + "&redirect_uri=" + redirection_url + "";
  var request = (HttpWebRequest)WebRequest.Create(url);
  request.ContentType = "application/x-www-form-urlencoded";
  request.Method = "POST";
  UTF8Encoding utfenc = new UTF8Encoding();
  byte[] bytes = utfenc.GetBytes(poststring);
  Stream outputstream = null;
  try
  {
    request.ContentLength = bytes.Length;
    outputstream = request.GetRequestStream();
    outputstream.Write(bytes, 0, bytes.Length);
  }
  catch { }
  var response = (HttpWebResponse)request.GetResponse();
  var streamReader = new StreamReader(response.GetResponseStream());
  string responseFromServer = streamReader.ReadToEnd();
  JavaScriptSerializer js = new JavaScriptSerializer();
  Tokenclass obj = js.Deserialize<Tokenclass>(responseFromServer);
  GetuserProfile(obj.access_token);
}
public void GetuserProfile(string accesstoken)
{
  string url = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + accesstoken + "";
  WebRequest request = WebRequest.Create(url);
  request.Credentials = CredentialCache.DefaultCredentials;
  WebResponse response = request.GetResponse();
  Stream dataStream = response.GetResponseStream();
  StreamReader reader = new StreamReader(dataStream);
  string responseFromServer = reader.ReadToEnd();
  reader.Close();
  response.Close();
  JavaScriptSerializer js = new JavaScriptSerializer();
  Userclass userinfo = js.Deserialize < Userclass > (responseFromServer);
  //Response.Write(responseFromServer);
}

Bạn xem hàm cuối cùng nhé. 

  • Biến responseFromServer là dữ liệu google trả về dạng json
  • dòng 55 và 56 là chuyển json thành đối tượng Userclass chứa vào biến userinfo
  • Từ biến userinfo này bạn có thể truy xuất được các giá trị mà google trả về cho bạn. Ví dụ bạn muốn lấy id của người đó. Bạn sử dụng userinfo.id. Hoặc bạn muốn lấy ảnh đại diện hãy sử dụng userinfo.picture, hoặc bạn muốn lấy email => userinfo.email

Đến đây có dữ liệu bạn có thể xào nấu theo ý riêng của bạn rồi, bạn có thể bỏ vào cơ sở dữ liệu để lưu trữ lại, hoặc sử dụng nó vào một mục đích gì đó. Chúc bạn thành công nhé!

Nguồn C#: https://www.c-sharpcorner.com/blogs/login-with-google-account-api-in-asp-net-and-get-google-plus-profile-details-in-c-sharp

Kết Luận

Như vậy mình đã hướng dẫn các bạn đăng nhập bằng google với PHP, Laravel và C#. Cảm ơn các bạn đã đọc bài viết. Nếu có thắc mắc gì cứ để lại bình luận bên dưới nhé!

Related posts:

  1. Xử lý đăng nhập bằng facebook đơn giản
  2. Thư viện Socialite trong Laravel để xử lý đăng nhập social
  3. Tạo google reCAPTCHA đơn giản ngay trên Laravel còn dễ dàng
  4. Đăng ký web với google còn đơn giản hơn Bing

Post navigation

Previous Post:

Hướng dẫn sử dụng công cụ animate.css

Next Post:

Đồ án quản lý thực tập

Trả lời Hủy

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

Ẩn sidebar

Tìm kiếm

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages

Blog Công Nghệ

Bài viết mới

  • Master typescript
  • Sendmail trong Laravel sử dụng dịch vụ SES, SQS của Amazon
  • Install SSL in Nginx Ubuntu
  • Docker study
  • Bảo vệ: Hướng dẫn code bot Telegram easy game

Lượng truy cập

0077913
Visit Today : 12
Visit Yesterday : 154
This Month : 4184
Who's Online : 2
© 2025 Blog Công Nghệ | WordPress Theme by Superbthemes