Google第三方登录(JavaScript SDK)

网页使用google账号实现第三方登录


详细demo下载

本demo示例利用JavaScript SDK实现了Facebook、google、LinkedIn第三方登录,可以获取用户的基本信息,并且同时包括官方登录按钮和自定义登录按钮代码示例。


1、创建Google API控制台项目和客户端ID

首先前往Google API 控制台选择或者创建一个项目


选择创建凭据 -> OAuth 客户端 ID -> 网页应用,之输入 JavaScript 来源、重定向 URI(可以添加开发地址:http://localhost:8085),拿到的客户端ID用于后续操作。

2、自定义登录和注销按钮

<button id="customBtn" type="button">Google登录</button>
<div id="name"></div>
<button type="button" onclick="signOut();">Sign out</button>
  
<script src="https://apis.google.com/js/api:client.js"></script>
<script>
	var googleUser = {};
	var startApp = function() {
		gapi.load('auth2', function(){
		  // Retrieve the singleton for the GoogleAuth library and set up the client.
		  auth2 = gapi.auth2.init({
		    client_id: 'xxxx', //客户端ID
		    cookiepolicy: 'single_host_origin',
		    scope: 'profile' //可以请求除了默认的'profile' and 'email'之外的数据
		  });
		  attachSignin(document.getElementById('customBtn'));
		});
	};

	function attachSignin(element) {
		auth2.attachClickHandler(element, {},
	    function(googleUser) {
	      document.getElementById('name').innerText = "Signed in: " + googleUser.getBasicProfile().getName();
		var profile = auth2.currentUser.get().getBasicProfile();
		console.log('ID: ' + profile.getId());
		console.log('Full Name: ' + profile.getName());
		console.log('Given Name: ' + profile.getGivenName());
		console.log('Family Name: ' + profile.getFamilyName());
		console.log('Image URL: ' + profile.getImageUrl());
		console.log('Email: ' + profile.getEmail());
	    }, function(error) {
	      console.log(JSON.stringify(error, undefined, 2));
	    });
	}
	startApp();

	//注销
	function signOut() {
		var auth2 = gapi.auth2.getAuthInstance();
		auth2.signOut().then(function () {
			alert('用户注销成功');
		});
	}
</script>
注意: Google帐户的电子邮件地址可能会更改,因此请勿使用它来标识用户。相反,请使用帐户的ID,您可以在客户端上获取ID, 在ID标记getBasicProfile().getId()sub声明中使用该ID。


猜你喜欢

转载自blog.csdn.net/zh_rey/article/details/79013290
今日推荐