持有合法验证信息(Bearer Token)的白名单服务器,可以通过 restful api 访问本系统的公开接口。
本系统采用标准 HTTP Authenticate (Bearer) 完成权限验证地交互流程
sequenceDiagram
title: 接口权限验证流程图
Client->>Cloudinstall: GET / HTTP/1.1
Cloudinstall-->>Client: HTTP/1.1 401 Unauthorized <br/> WWW-Authenticate: Bearer realm="Access to the site"
Client->>Client: 询问用户信息
Client->>Cloudinstall: GET / HTTP/1.1 <br/> Authorization: Bearer UHUzcGhDY29JTnZSbGpxZm1EOU......
Note left of Cloudinstall: 检查 Bearer Token
alt 无法解析 Bearer Token
Cloudinstall -->> Client: HTTP/1.1 401 Unauthorized
else Token 中的 APPID 不存在
Cloudinstall -->> Client: HTTP/1.1 401 Unauthorized
else 验证 Secret 是否正确
Cloudinstall -->> Client: HTTP/1.1 401 Unauthorized
else 客户端IP不在白名单中
Cloudinstall -->> Client: HTTP/1.1 401 Unauthorized
end
Note left of Cloudinstall: 权限检查完成,执行真实业务操作
Cloudinstall -->> Client: HTTP/1.1 200 OK
Bearer Token 由 AppID 和 Secret: sha256(AppID + "." + AppKey)
两部分组成:base64(AppID + "." + Secret)
如何得到 Bearer Token:
Golang 示例 :
package main
import (
"crypto/sha256"
"encoding/base64"
"fmt"
)
const (
AppID = "Pu3phCcoINvRljqfmD9F"
AppKey = "NZGmD6hqrCicWKQxj5HfBpznSuatO3LY0PFVTdRoM1"
)
func main() {
secret := sha256.Sum256([]byte(fmt.Sprintf("%s.%s", AppID, AppKey)))
token := fmt.Sprintf("%s.%s", AppID, fmt.Sprintf("%x", secret))
b64Token := base64.StdEncoding.EncodeToString([]byte(token))
bearerToken := fmt.Sprintf("Bearer %s", b64Token)
fmt.Println("Text Token:", token) // Text Token: Pu3phCcoINvRljqfmD9F.46a97c482e55816f175b807......
fmt.Println("Bearer Token:", bearerToken) // Bearer Token: Bearer UHUzcGhDY29JTnZSbGpxZm1EOU......
}
PHP示例:
<?php
$app_id = "Pu3phCcoINvRljqfmD9F";
$app_key = "NZGmD6hqrCicWKQxj5HfBpznSuatO3LY0PFVTdRoM1";
$secret = hash("sha256", sprintf("%s.%s", $app_id, $app_key));
$text_token = sprintf("%s.%s", $app_id, $secret);
$bearer_token = sprintf("Bearer %s", base64_encode($text_token));
echo "Text Token: " , $text_token; // Text Token: Pu3phCcoINvRljqfmD9F.46a97c482e55816f175b807......
echo PHP_EOL;
echo "Bearer Token: " , $bearer_token; // Bearer Token: Bearer UHUzcGhDY29JTnZSbGpxZm1EOU......ss
HTTP报文:
POST /api/lease/fhuwLNGM/start_install HTTP/1.1
Host: localhost
Content-Type: application/json
Authorization: Bearer UHUzcGhDY29JTnZSbGpxZm1EOU......
{
"system_code": "centos76",
"admin_password": "123456789"
}
cURL:
curl -X POST \
'https://localhost:9931/api/lease/fhuwLNGM/start_install' \
-H 'Authorization:Bearer UHUzcGhDY29JTnZSbGpxZm1EOU......' \
-d '{
"system_code": "centos76",
"admin_password": "123456789"
}'