API 文档

提示

API 文档默认已经集成在代码里面,部署完成后可以通过下面的方式进行访问

1 API 访问

VersionAccess methodexample
< 2.0.0http://<url>/docshttp://192.168.244.144/docs
>=2.0.0http://<url>/api/docs/http://192.168.244.144/api/docs/
>=2.6.0http://<url>/api/docs/http://192.168.244.144/api/docs/

版本小于 v2.6 需要打开 DEBUG 模式

  1. vi config.yml
  1. ...
  2. # 如果版本更低的话,配置文件是 config.py
  3. # Debug = true
  4. DEBUG: true

1.2 页面效果

api_swagger

2 API 认证

JumpServer API 支持的认证有以下几种方式

  1. Session 登录后可以直接使用 session_id 作为认证方式
  2. Token 获取一次性 Token,该 Token 有有效期, 过期作废
  3. Private Token 永久 Token
  4. Access Key Http Header 进行签名

SessionTokenPrivate TokenAccess Key

用户通过页面后登录,cookie 中会存在 jms_sessionid,请求时同样把 jms_sessionid 放到 cookie 中

  1. curl -X POST http://localhost/api/v1/authentication/auth/ \
  2. -H 'Content-Type: application/json' \
  3. -d '{"username": "admin", "password": "admin"}'

PythonGolangJava

  1. # Python 示例
  2. # pip install requests
  3. import requests, json
  4. def get_token(jms_url, username, password):
  5. url = jms_url + '/api/v1/authentication/auth/'
  6. query_args = {
  7. "username": username,
  8. "password": password
  9. }
  10. response = requests.post(url, data=query_args)
  11. return json.loads(response.text)['token']
  12. def get_user_info(jms_url, token):
  13. url = jms_url + '/api/v1/users/users/'
  14. headers = {
  15. "Authorization": 'Bearer ' + token,
  16. 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002'
  17. }
  18. response = requests.get(url, headers=headers)
  19. print(json.loads(response.text))
  20. if __name__ == '__main__':
  21. jms_url = 'https://demo.jumpserver.org'
  22. username = 'admin'
  23. password = 'admin'
  24. token = get_token(jms_url, username, password)
  25. get_user_info(jms_url, token)
  1. // Golang 示例
  2. package main
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "log"
  8. "net/http"
  9. "strings"
  10. )
  11. const (
  12. JmsServerURL = "https://demo.jumpserver.org"
  13. UserName = "admin"
  14. Password = "password"
  15. )
  16. func GetToken(jmsurl, username, password string) (string, error) {
  17. url := jmsurl + "/api/v1/authentication/auth/"
  18. query_args := strings.NewReader(`{
  19. "username": "`+username+`",
  20. "password": "`+password+`"
  21. }`)
  22. client := &http.Client{}
  23. req, err := http.NewRequest("POST", url, query_args)
  24. req.Header.Add("Content-Type", "application/json")
  25. resp, err := client.Do(req)
  26. if err != nil {
  27. log.Fatal(err)
  28. }
  29. defer resp.Body.Close()
  30. body, err := ioutil.ReadAll(resp.Body)
  31. if err != nil {
  32. log.Fatal(err)
  33. }
  34. response := map[string]interface{}{}
  35. json.Unmarshal(body, &response)
  36. return response["token"].(string), nil
  37. }
  38. func GetUserInfo(jmsurl, token string) {
  39. url := jmsurl + "/api/v1/users/users/"
  40. client := &http.Client{}
  41. req, err := http.NewRequest("GET", url, nil)
  42. req.Header.Add("Authorization", "Bearer "+token)
  43. req.Header.Add("X-JMS-ORG", "00000000-0000-0000-0000-000000000002")
  44. resp, err := client.Do(req)
  45. if err != nil {
  46. log.Fatal(err)
  47. }
  48. defer resp.Body.Close()
  49. body, err := ioutil.ReadAll(resp.Body)
  50. if err != nil {
  51. log.Fatal(err)
  52. }
  53. fmt.Println(string(body))
  54. }
  55. func main() {
  56. token, err := GetToken(JmsServerURL, UserName, Password)
  57. if err != nil {
  58. log.Fatal(err)
  59. }
  60. GetUserInfo(JmsServerURL, token)
  61. }
  1. // Java 示例
  2. import com.alibaba.fastjson.JSONObject;
  3. import org.apache.commons.lang3.StringUtils;
  4. import javax.net.ssl.*;
  5. import java.io.BufferedReader;
  6. import java.io.IOException;
  7. import java.io.InputStreamReader;
  8. import java.io.OutputStream;
  9. import java.net.URL;
  10. import java.util.HashMap;
  11. import java.util.Map;
  12. public class HttpsClientTest {
  13. private static final String JMS_URL = "hhttps://demo.jumpserver.org";
  14. private static final String JS_USER = "admin";
  15. private static final String JS_PASSWORD = "admin";
  16. public static void main(String[] args) throws IOException {
  17. Map map = new HashMap();
  18. map.put("username", JS_USER);
  19. map.put("password", JS_PASSWORD);
  20. https(JSONObject.toJSONString(map), "", "/api/v1/authentication/auth/");
  21. }
  22. public static void https(String params, String token, String uri) throws IOException {
  23. // 创建 URL 对象
  24. URL obj = new URL(JMS_URL + uri);
  25. // 打开连接
  26. HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
  27. // 忽略证书认证
  28. conn.setHostnameVerifier((hostname, session) -> true);
  29. conn.setSSLSocketFactory(getTrustedSSLSocketFactory());
  30. // 设置请求方法
  31. conn.setRequestMethod("GET");
  32. // 设置请求头部
  33. conn.setRequestProperty("Content-Type", "application/json");
  34. conn.setRequestProperty("x-jms-org", "00000000-0000-0000-0000-000000000002");
  35. if (StringUtils.isNotBlank(token)) {
  36. conn.setRequestProperty("Authorization", "Bearer " + token);
  37. }
  38. // 设置请求体数据
  39. conn.setDoOutput(true);
  40. if (StringUtils.isNotBlank(params)) {
  41. try (OutputStream outputStream = conn.getOutputStream()) {
  42. outputStream.write(params.getBytes("UTF-8"));
  43. }
  44. }
  45. // 发送请求并获取响应
  46. int responseCode = conn.getResponseCode();
  47. BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  48. String inputLine;
  49. StringBuilder response = new StringBuilder();
  50. while ((inputLine = in.readLine()) != null) {
  51. response.append(inputLine);
  52. }
  53. String res = response.toString();
  54. in.close();
  55. }
  56. private static SSLSocketFactory getTrustedSSLSocketFactory() {
  57. try {
  58. SSLContext sslContext = SSLContext.getInstance("TLS");
  59. sslContext.init(null, new TrustManager[] { new X509TrustManager() {
  60. @Override
  61. public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
  62. }
  63. @Override
  64. public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
  65. }
  66. @Override
  67. public java.security.cert.X509Certificate[] getAcceptedIssuers() {
  68. return null;
  69. }
  70. } }, new java.security.SecureRandom());
  71. return sslContext.getSocketFactory();
  72. } catch (Exception e) {
  73. e.printStackTrace();
  74. return null;
  75. }
  76. }
  77. }
  1. docker exec -it jms_core /bin/bash
  2. cd /opt/jumpserver/apps
  3. python manage.py shell
  4. from users.models import User
  5. u = User.objects.get(username='admin')
  6. u.create_private_token()

已经存在 private_token,可以直接获取即可

  1. u.private_token

以 PrivateToken: 937b38011acf499eb474e2fecb424ab3 为例:

  1. curl http://demo.jumpserver.org/api/v1/users/users/ \
  2. -H 'Authorization: Token 937b38011acf499eb474e2fecb424ab3' \
  3. -H 'Content-Type: application/json' \
  4. -H 'X-JMS-ORG: 00000000-0000-0000-0000-000000000002'

PythonGolang

  1. # Python 示例
  2. # pip install requests
  3. import requests, json
  4. def get_user_info(jms_url, token):
  5. url = jms_url + '/api/v1/users/users/'
  6. headers = {
  7. "Authorization": 'Token ' + token,
  8. 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002'
  9. }
  10. response = requests.get(url, headers=headers)
  11. print(json.loads(response.text))
  12. if __name__ == '__main__':
  13. jms_url = 'https://demo.jumpserver.org'
  14. token = '937b38011acf499eb474e2fecb424ab3'
  15. get_user_info(jms_url, token)
  1. // Golang 示例
  2. package main
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "log"
  8. "net/http"
  9. "strings"
  10. )
  11. const (
  12. JmsServerURL = "https://demo.jumpserver.org"
  13. JMSToken = "adminToken"
  14. )
  15. func GetUserInfo(jmsurl, token string) {
  16. url := jmsurl + "/api/v1/users/users/"
  17. client := &http.Client{}
  18. req, err := http.NewRequest("GET", url, nil)
  19. req.Header.Add("Authorization", "Token "+token)
  20. req.Header.Add("X-JMS-ORG", "00000000-0000-0000-0000-000000000002")
  21. resp, err := client.Do(req)
  22. if err != nil {
  23. log.Fatal(err)
  24. }
  25. defer resp.Body.Close()
  26. body, err := ioutil.ReadAll(resp.Body)
  27. if err != nil {
  28. log.Fatal(err)
  29. }
  30. fmt.Println(string(body))
  31. }
  32. func main() {
  33. GetUserInfo(JmsServerURL, JMSToken)
  34. }

在 Web 页面 API Key 列表创建或获取 AccessKeyID AccessKeySecret

PythonGolangJava

  1. # Python 示例
  2. # pip install requests drf-httpsig
  3. import requests, datetime, json
  4. from httpsig.requests_auth import HTTPSignatureAuth
  5. def get_auth(KeyID, SecretID):
  6. signature_headers = ['(request-target)', 'accept', 'date']
  7. auth = HTTPSignatureAuth(key_id=KeyID, secret=SecretID, algorithm='hmac-sha256', headers=signature_headers)
  8. return auth
  9. def get_user_info(jms_url, auth):
  10. url = jms_url + '/api/v1/users/users/'
  11. gmt_form = '%a, %d %b %Y %H:%M:%S GMT'
  12. headers = {
  13. 'Accept': 'application/json',
  14. 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002',
  15. 'Date': datetime.datetime.utcnow().strftime(gmt_form)
  16. }
  17. response = requests.get(url, auth=auth, headers=headers)
  18. print(json.loads(response.text))
  19. if __name__ == '__main__':
  20. jms_url = 'https://demo.jumpserver.org'
  21. KeyID = 'AccessKeyID'
  22. SecretID = 'AccessKeySecret'
  23. auth = get_auth(KeyID, SecretID)
  24. get_user_info(jms_url, auth)
  1. // Golang 示例
  2. package main
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "net/http"
  8. "time"
  9. "gopkg.in/twindagger/httpsig.v1"
  10. )
  11. const (
  12. JmsServerURL = "https://demo.jumpserver.org"
  13. AccessKeyID = "f7373851-ea61-47bb-8357-xxxxxxxxxxx"
  14. AccessKeySecret = "d6ed1a06-66f7-4584-af18-xxxxxxxxxxxx"
  15. )
  16. type SigAuth struct {
  17. KeyID string
  18. SecretID string
  19. }
  20. func (auth *SigAuth) Sign(r *http.Request) error {
  21. headers := []string{"(request-target)", "date"}
  22. signer, err := httpsig.NewRequestSigner(auth.KeyID, auth.SecretID, "hmac-sha256")
  23. if err != nil {
  24. return err
  25. }
  26. return signer.SignRequest(r, headers, nil)
  27. }
  28. func GetUserInfo(jmsurl string, auth *SigAuth) {
  29. url := jmsurl + "/api/v1/users/users/"
  30. gmtFmt := "Mon, 02 Jan 2006 15:04:05 GMT"
  31. client := &http.Client{}
  32. req, err := http.NewRequest("GET", url, nil)
  33. req.Header.Add("Date", time.Now().Format(gmtFmt))
  34. req.Header.Add("Accept", "application/json")
  35. req.Header.Add("X-JMS-ORG", "00000000-0000-0000-0000-000000000002")
  36. if err != nil {
  37. log.Fatal(err)
  38. }
  39. if err := auth.Sign(req); err != nil {
  40. log.Fatal(err)
  41. }
  42. resp, err := client.Do(req)
  43. if err != nil {
  44. log.Fatal(err)
  45. }
  46. defer resp.Body.Close()
  47. body, err := ioutil.ReadAll(resp.Body)
  48. if err != nil {
  49. log.Fatal(err)
  50. }
  51. json.MarshalIndent(body, "", " ")
  52. fmt.Println(string(body))
  53. }
  54. func main() {
  55. auth := SigAuth{
  56. KeyID: AccessKeyID,
  57. SecretID: AccessKeySecret,
  58. }
  59. GetUserInfo(JmsServerURL, &auth)
  60. }
  1. // Java 示例
  2. import com.google.common.net.MediaType;
  3. import net.adamcin.httpsig.api.*;
  4. import net.adamcin.httpsig.hmac.HmacKey;
  5. import okhttp3.OkHttpClient;
  6. import okhttp3.Request;
  7. import okhttp3.Response;
  8. import javax.net.ssl.SSLContext;
  9. import javax.net.ssl.TrustManager;
  10. import javax.net.ssl.X509TrustManager;
  11. import java.io.IOException;
  12. import java.security.KeyManagementException;
  13. import java.security.NoSuchAlgorithmException;
  14. import java.security.SecureRandom;
  15. import java.security.cert.CertificateException;
  16. import java.security.cert.X509Certificate;
  17. import java.util.HashMap;
  18. import java.util.Map;
  19. public class JMSApiClient {
  20. private static final String JMS_URL = "https://demo.jumpserver.org";
  21. private static final String KEY_ID = "f7373851-ea61-47bb-8357-xxxxxxxxxxx";
  22. private static final String SECRET_ID = "d6ed1a06-66f7-4584-af18-xxxxxxxxxxxx";
  23. private static final String ORGANIZATION_ID = "00000000-0000-0000-0000-000000000002";
  24. public static void main(String[] args) throws IOException {
  25. String apiKey = "";
  26. String keySecret = "";
  27. String endpoint = "";
  28. String uri = "/api/v1/users/users/";
  29. DefaultKeychain provider = new DefaultKeychain();
  30. HmacKey hmacKey = new HmacKey(apiKey, keySecret);
  31. provider.add(hmacKey);
  32. Map<String, String> headers = new HashMap<>();
  33. headers.put("Accept", MediaType.JSON_UTF_8.toString());
  34. headers.put("keyId", apiKey);
  35. headers.put("secret", keySecret);
  36. headers.put("algorithm", Algorithm.HMAC_SHA256.name());
  37. RequestContent.Builder requestContentBuilder = new RequestContent.Builder();
  38. requestContentBuilder.setRequestTarget("GET", "/api/v1/users/users/");
  39. for (Map.Entry<String, String> header : headers.entrySet()) {
  40. requestContentBuilder.addHeader(header.getKey(), header.getValue());
  41. }
  42. if (requestContentBuilder.build().getDate() == null) {
  43. requestContentBuilder.addDateNow();
  44. String dateValue = requestContentBuilder.build().getDate();
  45. requestContentBuilder.addHeader("date", dateValue);
  46. headers.put("date", dateValue);
  47. }
  48. Signer signer = new Signer(provider, key -> hmacKey.getId());
  49. RequestContent requestContent = requestContentBuilder.build();
  50. Authorization authorization = signer.sign(requestContent);
  51. if (authorization != null) {
  52. headers.put("Authorization", authorization.getHeaderValue());
  53. }
  54. try {
  55. OkHttpClient.Builder builderClient = new OkHttpClient().newBuilder();
  56. disableCertificateValidation(builderClient);
  57. OkHttpClient client = builderClient.build();
  58. Request.Builder builder = new Request.Builder()
  59. .url(endpoint + uri)
  60. .method("GET", null);
  61. for (Map.Entry<String, String> header : headers.entrySet()) {
  62. builder.addHeader(header.getKey(), header.getValue());
  63. }
  64. Request request = builder.build();
  65. Response response = client.newCall(request).execute();
  66. System.out.println(response.body().string());
  67. } catch (IOException e) {
  68. e.printStackTrace();
  69. }
  70. }
  71. public static void disableCertificateValidation(OkHttpClient.Builder builderClient) {
  72. // 创建信任所有证书的 TrustManager
  73. try {
  74. TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
  75. @Override
  76. public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  77. }
  78. @Override
  79. public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  80. }
  81. @Override
  82. public X509Certificate[] getAcceptedIssuers() {
  83. return new X509Certificate[0];
  84. }
  85. }};
  86. // 创建 SSLContext,并关联信任所有证书的 TrustManager
  87. SSLContext sslContext = SSLContext.getInstance("TLS");
  88. sslContext.init(null, trustAllCerts, new SecureRandom());
  89. // 创建 OkHttpClient.Builder,并设置 SSLContext builder
  90. builderClient.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0]);
  91. builderClient.hostnameVerifier((hostname, session) -> true);
  92. } catch (NoSuchAlgorithmException | KeyManagementException e) {
  93. e.printStackTrace();
  94. }
  95. }
  96. }