参考:
https://blog.csdn.net/qq_36437991/article/details/136255926

前端提交给服务端生成token并返回

1 思路:

根据官方文档,生成token的内容(即document,editorConfig这些页面上的json格式代码)要在前端一起打包通过body发送到服务端,服务端收到json数据,golang语言需要解析为结构体,然后将结构体作为“荷载”payload ,生成token,官方的说明:https://api.onlyoffice.com/docs/docs-api/additional-api/signature/browser/
The payload for the JWT token in the JSON format must have the same structure as the config.
Please note that starting from version 7.1, the parameter list to be signed will be strictly regulated. Don’t forget to add all the parameters listed below to your signature.

2 前端:

页面代码中的{{}}是beego框架下golang服务端传递给页面的变量。这些怎么弄,见我的开源代码吧

const config = {
    "document": {
      "fileType": "{{.fileType}}",
      "key": "{{.Key}}", //"Khirz6zTPdfd7"
      "title": "{{.Doc.FileName}}",
      "url":"http:\/\/192.168.100.37/attachment/onlyoffice/测试v3.docx"
      // "url": "{{.Engineercmsapi_url}}/attachment/onlyoffice/{{.Doc.FileName}}?hotqinsessionid={{.Sessionid}}",
    },
    "documentType": "{{.documentType}}",
    "editorConfig": {
      "callbackUrl": "{{.Engineercmsapi_url}}/url-to-callback?id={{.Doc.Id}}",
      "customization": {
        "uiTheme": "theme-dark",
        "unit": "cm",
        "wordHeadingsColor": "#00ff00",
        "zoom": 100,
      },
      "user": {
        "id": {{.Uid }},
        "name": "{{.Username}}"
      },
      "lang": "zh-CN", //"en-US",
      "mode": {{.Mode }}, //"view",//edit
      "region": "zh-CN",
    },
    "height": "100%",
    "type": {{.Type }}, //"desktop",embedded,mobile访问文档的平台类型 网页嵌入
    "width": "100%"
  }
  // window.docEditor = new DocsAPI.DocEditor("placeholder", config);

  $(function () {
    const configJsonStr = JSON.stringify(config);
    $.ajax({
      type: "POST",
      url: "/v1/onlyoffice/jwtencode",
      contentType: "application/json",
      data: JSON.stringify({
        "jsonStr":configJsonStr
      }),
      dataType: "json",
      success: function (data) {
        console.log("成功")
        console.log(data)
        if(data.jwt){
          config.token = data.jwt;
        }
        var docEditor = new DocsAPI.DocEditor("placeholder", config);
      },
      error: function (err) {
        console.error(err);
      }
    })
  })

3 服务端:

服务端golang beego框架,配合生成token返回给前端

type onlyofficeJwtManager struct {
    key []byte
}

func (j onlyofficeJwtManager) Sign(payload interface {
    Valid() error
}) (string, error) {
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, payload)
    ss, err := token.SignedString(j.key)

    if err != nil {
        return "", errors.New("could not generate a new jwt")
    }

    return ss, nil
}

type OnlyofficeClaims struct {
    Document     OnlyDocument     `json:"document"`
    DocumentType string           `json:"documentType"`
    EditorConfig OnlyEditorConfig `json:"editorConfig"`
    Height       string           `json:"height"`
    Type         string           `json:"type"`
    Width        string           `json:"width"`
    jwt.RegisteredClaims
}

type OnlyDocument struct {
    FileType string `json:"fileType"`
    Key      string `json:"key"`
    Title    string `json:"title"`
    Url      string `json:"url"`
}

type OnlyEditorConfig struct {
    CallbackUrl   string     `json:"callbackUrl"`
    Customization OnlyCustom `json:"customization"`
    User          OnlyUser   `json:"user"`
    Lang          string     `json:"lang"`
    Mode          string     `json:"mode"`
    Region        string     `json:"region"`
}

type OnlyCustom struct {
    UiTheme           string `json:"uiTheme"`
    Unit              string `json:"unit"`
    WordHeadingsColor string `json:"wordHeadingsColor"`
    Zoom              int    `json:"zoom"`
}

type OnlyUser struct {
    Id   string `json:"id"`
    Name string `json:"name"`
}

// @Title post onlyoffce jwtencode token
// @Description post onlyoffice jwtencode token
// @Success 200 {object} models.Ollyoffice
// @Failure 400 Invalid page supplied
// @Failure 404 office not found
// @router /jwtencode [post]
// 生成token
func (c *OnlyController) JwtEncode() {
    content := c.Ctx.Input.RequestBody
    var onlyofficeconfig OnlyofficeClaims
    err := json.Unmarshal(content, &onlyofficeconfig)
    if err != nil {
        logs.Error(err)
    }
    logs.Info(onlyofficeconfig) // {"document":{"fileType":"doc","key":"1558683150313208200","title":"xml.doc","url":"http://192.168.100.37/attachment/onlyoffice/测试v3.docx"},"documentType":"word","editorConfig":{"callbackUrl":"http://192.168.137.1:8081/url-to-callback?id=10","customization":{"uiTheme":"theme-dark","unit":"cm","wordHeadingsColor":"#00ff00","zoom":100},"user":{"id":"0","name":"127.0.0.1"},"lang":"zh-CN","mode":"edit","region":"zh-CN"},"height":"100%","type":"desktop","width":"100%"}
    jwt_enabled, err := web.AppConfig.String("JWT_ENABLED")
    if err != nil {
        logs.Error(err)
    }
    if jwt_enabled == "true" {
        jwt_secret, err := web.AppConfig.String("onlyoffice_token_secret")
        if err != nil {
            logs.Error(err)
        }
        key := onlyofficeJwtManager{[]byte(jwt_secret)}
        logs.Info(key)
        token, err := key.Sign(onlyofficeconfig)
        if err != nil {
            logs.Error(err)
        }
        c.Data["json"] = map[string]interface{}{"state": "SUCCESS", "info": "SUCCESS", "jwt": token}
        c.ServeJSON()
        return
    }
    c.Data["json"] = map[string]interface{}{"state": "SUCCESS", "info": "SUCCESS", "jwt": onlyofficeconfig}
    c.ServeJSON()
}

4 callbackUrl

似乎最后一个关闭编辑后,oo服务器会像文档下载服务器callbackUrl传出token,需要将token解析吗??官方文件:
https://api.onlyoffice.com/docs/docs-api/additional-api/signature/request/token-in-body/

Outgoing requests
Request to "callbackUrl" address by document editing service when the last user closed the document for editing without changes
Validation is performed for outgoing requests to "callbackUrl" address by document editing service.

Sample parameters of request to "callbackUrl" address by document editing service when the last user closed the document for editing without changes:

{
  "key": "Khirz6zTPdfd7",
  "status": 4
}

Sample of request to "callbackUrl" address by document editing service when the last user closed the document for editing without changes:

POST /url-to-callback.ashx HTTP/1.1
Host: example.com
Content-Type: application/json

{
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXkiOiJLaGlyejZ6VFBkZmQ3Iiwic3RhdHVzIjo0fQ.gCyNKPpg6ISAnhvFQmRiY6BRqG6WPcEGgnK79hREdkU"
}

Where the example.com is the name of the server where document manager and document storage service are installed. See the How it works section to find out more on ONLYOFFICE Docs service client-server interactions.

When performing the GET requests from ONLYOFFICE Docs an authorization header with the token is added.
作者:秦晓川  创建时间:2025-03-15 02:04
最后编辑:秦晓川  更新时间:2025-03-15 10:29
上一篇:
下一篇: