3.4. 创建 Token

未匹配的标注

Github: github.com/bigfile/bigfile

API

创建 Token 是接下来所有操作的开始,让我们先开看一下 API 参数。

POST /api/bigfile/token/create

name type required description
appUid string yes APP UID
nonce string yes 3248 长度的随机字符串
sign string yes 请求参数签名
path string no Token 的作用域,默认为:/,可以理解为根目录
ip string no 限制当前 Token 仅能被使用的 IP 列表,多个 IP 逗号分隔
expiredAt timestamp no Token 失效时间,默认永久有效
secret string no Token 密钥,1232 位,建议设置,默认为空
availableTimes int no Token 可用次数,默认无限次数
readOnly bool no 限制此 Token 仅能被用于去下载文件

示例

package main

import (
    "fmt"
    "io/ioutil"
    libHttp "net/http"
    "strings"
    "time"

    "github.com/bigfile/bigfile/databases/models"
    "github.com/bigfile/bigfile/http"
)

func main() {
    appUid := "42c4fcc1a620c9e97188f50b6f2ab199"
    appSecret := "f8f2ae1fe4f70b788254dcc991a35558"
    body := http.GetParamsSignBody(map[string]interface{}{
        "appUid":         appUid,
        "nonce":          models.RandomWithMd5(128),
        "path":           "/images/png",
        "expiredAt":      time.Now().AddDate(0, 0, 2).Unix(),
        "secret":         models.RandomWithMd5(44),
        "availableTimes": -1,
        "readOnly":       false,
    }, appSecret)
    request, err := libHttp.NewRequest(
        "POST", "https://127.0.0.1:10985/api/bigfile/token/create", strings.NewReader(body))
    if err != nil {
        fmt.Println(err)
        return
    }
    request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    resp, err := libHttp.DefaultClient.Do(request)
    if err != nil {
        fmt.Println(err)
        return
    }
    if bodyBytes, err := ioutil.ReadAll(resp.Body); err != nil {
        fmt.Println(err)
        return
    } else {
        fmt.Println(string(bodyBytes))
    }
}

响应成功之后,你将得到下面这样的响应:

{
    "requestId":10001,
    "success":true,
    "errors":null,
    "data":{
        "availableTimes":-1,
        "expiredAt":1568127304,
        "ip":null,
        "path":"/images/png",
        "readOnly":0,
        "secret":"46afc3607a93ac410357a8ed53a872b8",
        "token":"4d50ae8061c1d6f148a45031356294bd"
    }
}

证书错误

如果您再使用 HTTP API 的时候,遇到如下错误:

x509: certificate signed by unknown authority

是因为使用 rpc:make-cert 生成的证书不被系统信任,这里有两种解决方案:

  1. 将证书加入到系统的可信任证书库中
  2. 在请求时选择不验证证书,例如:
import "crypto/tls"
....
funf main(){
tr := &http.Transport{    //解决x509: certificate signed by unknown authority
        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    }
client := &http.Client{
        Timeout:   15 * time.Second,
        Transport: tr,    //解决x509: certificate signed by unknown authority
    }
....
client.Do(req)
}

英文文档:bigfile.site

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
Michael001
讨论数量: 0
发起讨论 只看当前版本


暂无话题~