GitHub OAuth 第三方登錄
第三方登錄的關鍵知識點就是 OAuth2.0 . 第三方登錄,實質就是 OAuth 授權 . OAuth 是一個開放標准,允許用戶讓第三方應用訪問某一個網站的資源,而不需要提供賬號和密碼.
總體就是:myapp <=> user <=> github
授權的總體流程
- 用戶進入到我的網站,我想要獲取到用戶的 GitHub 信息
- 跳轉到 GitHub 授權頁面,然后問用戶是否允許我獲得他的信息,授予權限
- 同意,我的網站會獲得 GitHub 發回的一個授權碼,使用該授權碼向 GitHub 申請一個令牌
- GitHub 授權碼進行驗證,沒問題就會返回一個令牌(這個令牌只在短時間內有效)
- 我的網站獲得令牌,然后向 GitHub 的 user 發起請求
- GitHub 驗證令牌,沒問題用戶信息就返回過來了
- 我們通過返回的用戶信息然后創建一個用戶,並生成 token 返回給 client
- 然后根據 token 進行登錄驗證,來保持登錄
授權登錄一次之后就不用再次授權了,除非在 github app 中清除授權記錄
應用登記
一個應用要求 OAuth 授權,必須先到對方網站登記,讓對方知道是誰在請求。
所以,你要先去 GitHub 登記一下。當然,我已經登記過了,你使用我的登記信息也可以,但為了完整走一遍流程,還是建議大家自己登記。這是免費的。
user => settings => Developer settings
提交表單以后,GitHub 應該會返回客戶端 ID(client ID)和客戶端密鑰(client secret),這就是應用的身份識別碼。
webhook 通知
現在進行 oauth 應用創建的時候需要添加一個 webhook,這個就是 github 的一個通知系統,有更改的時候就會進行接口請求.現在創建 github app 強制要配置這個.
頁面請求
首先在網站上加一個按鈕
<Button type="primary" icon="github" size="large" onClick={this.login}>
Github登錄
</Button>
//handle
public login() {
const CLIENT_ID = "Iv1.59ce080xxxxx";
const REDIRECT_URL = "ff852c46bxxxxx";
const url = "https://github.com/login/oauth/authorize?client_id=" + CLIENT_ID + `&client_secret=${REDIRECT_URL}`;
window.location.href = url;
}
點擊按鈕進入到授權頁面
授權之后就去去請求當前應用在 github 保存的回調接口 ===> User authorization callback URL: http://localhost:6776/api/user/oauth
實現 oauth 接口
用戶同意授權,GitHub 就會跳轉到 User authorization callback URL 指定的跳轉網址,並且帶上授權碼,跳轉回來的 URL 就是下面的樣子。
http://localhost:6776/api/user/oauth?code=df9da5bfca34bff19f2e
通過 query 拿到 code,這個就是授權碼.
后端使用的是 nest.js 實現 , 之后的請求都使用后端實現.
@Get('/oauth')
@Redirect('/', 301)
async githubOauth(@Query() queryData: { code: string }) {
const ClientID = 'Iv1.59ce08xxxx';
const ClientSecret = 'ff852c46bxxxxx';
const config = {
method: 'post',
uri:
'http://github.com/login/oauth/access_token?' +
`client_id=${ClientID}&` +
`client_secret=${ClientSecret}&` +
`code=${queryData.code}`,
headers: {
'Content-Type': 'application/json',
accept: 'application/json',
},
};
const result: string = (await asyncRequest(config)) as string; //發起請求,拿到token
}
}
function asyncRequest(config) {
return new Promise((resolve, reject) => {
request(config)
.then(response => {
resolve(response);
})
.catch(error => {
reject(error);
});
});
}
拿到 token 之后我們可以通過 token 獲取用戶信息
const parseResult = JSON.parse(result);
const githubConfig = {
method: 'get',
uri: `https://api.github.com/user`,
headers: {
Authorization: `token ${parseResult.access_token}`,
'User-Agent': 'easterCat',
},
};
const user: string = (await asyncRequest(githubConfig)) as string; //獲取用戶信息
const parseUser = JSON.parse(user);
獲取到用戶信息{"login":"easterCat"....."created_at":"2016-07-13T07:24:06Z","updated_at":"2019-10-25T05:26:34Z"}
之后,處理用戶信息
我們將需要的數據創建一個新用戶
await this.userService.create({
login: parseUser.login,
avatarUrl: parseUser.avatar_url,
name: parseUser.name,
createdAt: parseUser.created_at,
updatedAt: parseUser.updated_at,
}); // 創建新用戶
await this.sessionService.create({
token: loginStatus,
createAt: +Date.now(),
name: parseUser.name,
}); //創建session
然后之前 get 請求下添加了跳轉 redirect,此時傳入跳轉接口
return { url: `/logged?name=${parseUser.name}` };
驗證登錄
前端進行的 ajax 請求開啟 withCredentials , 將 cookie 進行攜帶.
前端使用的使用 next.js 進行的 react 開發.后端會將頁面跳轉到 logged 頁面.
public async componentDidMount() {
const parsed = queryString.parse(window.location.search);
const result: any = await this.props.login({ name: parsed.name });
Cookies.set("ptg-token", result.token);
this.setState({
loginStatus: true,
loading: true
});
}
當前頁面進行登錄接口請求,並將 token 保存到 cookie 中.
之后的持久化登錄就在應用初始階段請求后端/logged 接口,后端會從請求中的 cookie 中拿到 token,然后對 session 進行判斷.