起因
最近研究使用 GitHub 仓库作为评论区的技术,找到了 Gitment 这样的技术。但是碍于网速缘故,Github 作为评论区不合适。所以找到 Gitee 作为目标。
然后找到了 Giteement 仓库,打算研究一番这种不用服务器的登录评论技术。
过程
- 分析 Giteement 源代码
Giteement 中主要的登录方式就是 Gitee 官方文档中的 oauth 方式获取 access_token, 然后使用 Gitee API 进行各种操作。
- Giteement 需要在使用者的 Gitee 上申请 第三方应用 以获取
client_id和client_secret - 填写你的测试网页的地址(其实它的名称叫
redirect_uri,即回调地址)
- 前端实现跳转到 Gitee 官方页面进行用户登录验证
class Giteement {
get loginLink() {
// 这里主要是进行授权页面的URL拼接
const oauthUri = "https://gitee.com/oauth/authorize";
const redirect_uri =
this.backcall_uri +
"?bkurl=" +
encodeURIComponent(window.location.href);
const oauthParams = Object.assign(
{
response_type,
redirect_uri,
},
this.oauth
);
return `${oauthUri}${Query.stringify(oauthParams)}`;
}
// ...
login() {
// 这个是使用跳转到 Gitee 的页面进行用户授权
window.location.href = this.loginLink;
}
}
- 点击授权后,用户被重定向回原来的页面,但是在你的网页的 URL 上多了一个
code参数
- 在控制台测试能否拿到关键的 access_token
var myHeaders = new Headers();
myHeaders.append("Accept", "application/json");
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
// ! 下面的参数需要填入相应的信息
urlencoded.append("code", code);
urlencoded.append("client_secret", client_secret);
urlencoded.append("client_id", client_id);
urlencoded.append("redirect_uri", redirect_uri);
urlencoded.append("grant_type", "authorization_code");
var requestOptions = {
method: "POST",
headers: myHeaders,
body: urlencoded,
redirect: "follow",
};
await fetch("https://gitee.com/oauth/token", requestOptions)
.then((response) => response.json())
.catch((error) => console.log("error", error));
结论
- Giteement 使用 Gitee 官方的 oauth API 进行权限申请,通过官方的 API 获取了用户的一定权限。
- 注意!!!Giteement 是不安全的,因为 Giteement 源代码中需要填入
client_secret字段才能工作,所以不太安全,同时用户的access_token被存储在了localStorage中,而且没有进行加密,想想如果发送到统一的一个黑客服务器上,那就麻烦了。 - Gitee 的 Issures 确实可以作为评论区使用,但是还是需要进行保护
client_secret,所以放置在前端肯定不是一个好的选择。