基于Github的OAuth2.0协议的单点登录
项目开发过程中,多个子系统需要集成统一认证平台,统一登录,说白了就是第三方登录。当下第三方登录最流行的协议是OAuth2.0。如:微信开放平台,支付宝开放平台,QQ开放平台,Github开放平台等,都提供了第三方登录的功能,现提供一个demo,供码友们参考。
Github单点登录的流程
流程地址 https://developer.github.com/apps/building-oauth-apps/
按照流程操作即可,只不过全程是英文,有些不便。
第一步、在Github上创建OAuth App
homepage url 是第三方网站(咱们自己的网站)的主页地址。
callback url 是第三方网站的回调地址,用来接收用户授权后的access_token。
应用创建成功后会得到client id和client secret。(后续会用到)
第三方登录流程
第三方登录流程 https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/
第一步,请求github用户授权
第二步,请求github获取令牌
第三步、使用令牌获取github存储的用户信息
用户信息很多,根据自己需要进行展示:
{
"login": "octocat",
"id": 1,
"node_id": "MDQ6VXNlcjE=",
"avatar_url": "https://github.com/images/error/octocat_happy.gif",
"gravatar_id": "",
"url": "https://api.github.com/users/octocat",
"html_url": "https://github.com/octocat",
"followers_url": "https://api.github.com/users/octocat/followers",
"following_url": "https://api.github.com/users/octocat/following{/other_user}",
"gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",
"starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/octocat/subscriptions",
"organizations_url": "https://api.github.com/users/octocat/orgs",
"repos_url": "https://api.github.com/users/octocat/repos",
"events_url": "https://api.github.com/users/octocat/events{/privacy}",
"received_events_url": "https://api.github.com/users/octocat/received_events",
"type": "User",
"site_admin": false,
"name": "monalisa octocat",
"company": "GitHub",
"blog": "https://github.com/blog",
"location": "San Francisco",
"email": "octocat@github.com",
"hireable": false,
"bio": "There once was...",
"twitter_username": "monatheoctocat",
"public_repos": 2,
"public_gists": 1,
"followers": 20,
"following": 0,
"created_at": "2008-01-14T04:33:35Z",
"updated_at": "2008-01-14T04:33:35Z",
"private_gists": 81,
"total_private_repos": 100,
"owned_private_repos": 100,
"disk_usage": 10000,
"collaborators": 8,
"two_factor_authentication": true,
"plan": {
"name": "Medium",
"space": 400,
"private_repos": 20,
"collaborators": 0
}
}
下面开始我们的SpringBoot工程Java代码。
工程结构如下
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
<