背景
很多网站登录时,允许使用第三方网站的身份,例如有微信、支付宝、gitlab 等等,然后我们使用场景是前端内部应用 周报平台、自动化发布、埋点系统等等, 需要调用 gitlab api 获取一些基础的项目信息或者需要获取个人资料等等
原理-OAuth 2.0
OAuth(开放授权)是一个开放标准,允许用户让第三方应用访问该用户在某一网站上存储的私密的资源(如照片,视频,联系人列表),而无需将用户名和密码提供给第三方应用
具体是个什么概念、怎么实现实现的,我觉得阮一峰老师的这篇文章outh2.0[1]讲的更好,这里就不细讲了,直接进入实战
过程
- 用户打开应用主页点击 gitlab 的方式登陆
- 跳转到 gitlab 的授权页面后,用户同意获取他的基本信息
- gitlab 会返回一个包含授权码 code 以及其它参数并重定向 URI 并跳转至对应的网页
- 拿到 code 后去获取 gitlab api 的 token
准备工作
- 首先以 admin 的身份登陆 gitlab
- 点击我的-设置-应用, 如下图
实践
打开控制台输入
const url = 'http://xxxc.om/oauth/authorize?client_id=12345&redirect_uri=http://127.0.0.1:9003&response_type=code&scope=read_user'
location.href = url
全部参数说明
跳转到 gitlab 的授权页面
重定向
url 会携带参数 code 如下图
最后一步获取 token
https://xxx/oauth/token
参数同上面那个表格,拿到如下图 json
{
"access_token": "",
"token_type": "bearer",
"refresh_token": "42",
"scope": "api",
"created_at": 1577427939
}
好了可以尽情的去调用 gitlab api了,让我们首先获取个人资料
GET /users/:username
Status: 200 OK
{
"login": "octocat",
"id": 1,
"node_id": "MDQ6VXNlcjE=",
"avatar_url": "https://gitlab.com/images/error/octocat_happy.gif",
"gravatar_id": "",
"url": "https://api.gitlab.com/users/octocat",
"html_url": "https://gitlab.com/octocat",
"followers_url": "https://api.gitlab.com/users/octocat/followers",
"following_url": "https://api.gitlab.com/users/octocat/following{/other_user}",
"gists_url": "https://api.gitlab.com/users/octocat/gists{/gist_id}",
"starred_url": "https://api.gitlab.com/users/octocat/starred{/owner}{/repo}",
"subscriptions_url": "https://api.gitlab.com/users/octocat/subscriptions",
"organizations_url": "https://api.gitlab.com/users/octocat/orgs",
"repos_url": "https://api.gitlab.com/users/octocat/repos",
"events_url": "https://api.gitlab.com/users/octocat/events{/privacy}",
"received_events_url": "https://api.gitlab.com/users/octocat/received_events",
"type": "User",
"site_admin": false,
"name": "monalisa octocat",
"company": "GitHub",
"blog": "https://gitlab.com/blog",
"location": "San Francisco",
"email": "octocat@gitlab.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"
}
gitlab 其它登陆方式
在 gitlab v10之前官方提供了下面的一个 api,可以自定义登陆页面,只要最后通过这个验证即可。
https://gitlab.example.com/api/v4/session?login=john_smith&password=strongpassw0rd
最后
市面上的钉钉、微信、其它方式登陆都要去申请,就短期来说还是上 gitlab 更快一点,最重要的还是理解 OAuth2.0😊
参考资料
[1]outh2.0: http://www.ruanyifeng.com/blog/2019/04/oauth_design.html
本文使用 mdnice 排版