PingOne Platform APIs

Import Certificate Authority (CA) Response to a CSR

 

PUT {{apiPath}}/environments/{{envID}}/keys/{{keyID}}/csr

The PUT {{apiPath}}/environments/{{envID}}/keys/{{keyID}}/csr operation imports a Certificate Authority (CA) response to a CSR.

Prerequisites

  1. If you’ve not already done so, use POST {{apiPath}}/environments/{{envID}}/keys to create a public key.

  2. Use GET {{apiPath}}/environments/{{envID}}/keys/{{keyID}} to export the public key.

  3. Copy the response to this request into a .csr file.

  4. Generate a CA response for this CSR. You can do this using OpenSSL as a local certificate authority using a command similar to this:

    openssl x509 -req [-digest] [-days expiry] -in CSR.csr -CA ca.pem -CAkey ca.key -CAcreateserial [-outform DER|PEM|NET] -out ca.resp.crt

    For example:

    openssl x509 -req -sha256 -days 365 -in CSR_RSA.csr -CA ca_rsa.pem -CAkey ca_rsa.key -CAcreateserial -outform PEM -out ca_rsa.resp.crt
  5. You can then call PUT {{apiPath}}/environments/{{envID}}/keys/{{keyID}}/csr to import the CA reponse.

For more information, see:

Headers

Authorization      Bearer {{accessToken}}

Content-Type      multipart/form-data; boundary=<calculated when request is sent>

Body

formdata

Key Type Value

file

file

Example Request

  • cURL

  • C#

  • Go

  • HTTP

  • Java

  • jQuery

  • NodeJS

  • Python

  • PHP

  • Ruby

  • Swift

curl --location --globoff --request PUT '{{apiPath}}/environments/{{envID}}/keys/{{keyID}}/csr' \
--header 'Authorization: Bearer {{accessToken}}' \
--form 'file=@"/Users/kbentley/workspace/ca_rsa.resp.crt"'
var options = new RestClientOptions("{{apiPath}}/environments/{{envID}}/keys/{{keyID}}/csr")
{
  MaxTimeout = -1,
};
var client = new RestClient(options);
var request = new RestRequest("", Method.Put);
request.AddHeader("Authorization", "Bearer {{accessToken}}");
request.AlwaysMultipartFormData = true;
request.AddFile("file", "/Users/kbentley/workspace/ca_rsa.resp.crt");
RestResponse response = await client.ExecuteAsync(request);
Console.WriteLine(response.Content);
package main

import (
  "fmt"
  "bytes"
  "mime/multipart"
  "os"
  "path/filepath"
  "net/http"
  "io"
)

func main() {

  url := "{{apiPath}}/environments/{{envID}}/keys/{{keyID}}/csr"
  method := "PUT"

  payload := &bytes.Buffer{}
  writer := multipart.NewWriter(payload)
  file, errFile1 := os.Open("/Users/kbentley/workspace/ca_rsa.resp.crt")
  defer file.Close()
  part1,
         errFile1 := writer.CreateFormFile("file",filepath.Base("/Users/kbentley/workspace/ca_rsa.resp.crt"))
  _, errFile1 = io.Copy(part1, file)
  if errFile1 != nil {
    fmt.Println(errFile1)
    return
  }
  err := writer.Close()
  if err != nil {
    fmt.Println(err)
    return
  }


  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("Authorization", "Bearer {{accessToken}}")

  req.Header.Set("Content-Type", writer.FormDataContentType())
  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := io.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
PUT /environments/{{envID}}/keys/{{keyID}}/csr HTTP/1.1
Host: {{apiPath}}
Authorization: Bearer {{accessToken}}
Content-Length: 202
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="ca_rsa.resp.crt"
Content-Type: <Content-Type header here>

(data)
------WebKitFormBoundary7MA4YWxkTrZu0gW--
OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
  .addFormDataPart("file","ca_rsa.resp.crt",
    RequestBody.create(MediaType.parse("application/octet-stream"),
    new File("/Users/kbentley/workspace/ca_rsa.resp.crt")))
  .build();
Request request = new Request.Builder()
  .url("{{apiPath}}/environments/{{envID}}/keys/{{keyID}}/csr")
  .method("PUT", body)
  .addHeader("Authorization", "Bearer {{accessToken}}")
  .addHeader("Content-Length", "")
  .build();
Response response = client.newCall(request).execute();
var form = new FormData();
form.append("file", fileInput.files[0], "ca_rsa.resp.crt");

var settings = {
  "url": "{{apiPath}}/environments/{{envID}}/keys/{{keyID}}/csr",
  "method": "PUT",
  "timeout": 0,
  "headers": {
    "Authorization": "Bearer {{accessToken}}",
    "Content-Length": ""
  },
  "processData": false,
  "mimeType": "multipart/form-data",
  "contentType": false,
  "data": form
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
var request = require('request');
var fs = require('fs');
var options = {
  'method': 'PUT',
  'url': '{{apiPath}}/environments/{{envID}}/keys/{{keyID}}/csr',
  'headers': {
    'Authorization': 'Bearer {{accessToken}}',
    'Content-Length': ''
  },
  formData: {
    'file': {
      'value': fs.createReadStream('/Users/kbentley/workspace/ca_rsa.resp.crt'),
      'options': {
        'filename': 'ca_rsa.resp.crt',
        'contentType': null
      }
    }
  }
};
request(options, function (error, response) {
  if (error) throw new Error(error);
  console.log(response.body);
});
import requests

url = "{{apiPath}}/environments/{{envID}}/keys/{{keyID}}/csr"

payload = {}
files=[
  ('file',('ca_rsa.resp.crt',open('/Users/kbentley/workspace/ca_rsa.resp.crt','rb'),'application/octet-stream'))
]
headers = {
  'Authorization': 'Bearer {{accessToken}}',
  'Content-Length': ''
}

response = requests.request("PUT", url, headers=headers, data=payload, files=files)

print(response.text)
<?php
require_once 'HTTP/Request2.php';
$request = new HTTP_Request2();
$request->setUrl('{{apiPath}}/environments/{{envID}}/keys/{{keyID}}/csr');
$request->setMethod(HTTP_Request2::METHOD_PUT);
$request->setConfig(array(
  'follow_redirects' => TRUE
));
$request->setHeader(array(
  'Authorization' => 'Bearer {{accessToken}}',
  'Content-Length' => ''
));
$request->addUpload('file', '/Users/kbentley/workspace/ca_rsa.resp.crt', 'ca_rsa.resp.crt', '<Content-Type Header>');
try {
  $response = $request->send();
  if ($response->getStatus() == 200) {
    echo $response->getBody();
  }
  else {
    echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
    $response->getReasonPhrase();
  }
}
catch(HTTP_Request2_Exception $e) {
  echo 'Error: ' . $e->getMessage();
}
require "uri"
require "net/http"

url = URI("{{apiPath}}/environments/{{envID}}/keys/{{keyID}}/csr")

http = Net::HTTP.new(url.host, url.port);
request = Net::HTTP::Put.new(url)
request["Authorization"] = "Bearer {{accessToken}}"
request["Content-Length"] = ""
form_data = [['file', File.open('/Users/kbentley/workspace/ca_rsa.resp.crt')]]
request.set_form form_data, 'multipart/form-data'
response = http.request(request)
puts response.read_body
let parameters = [
  [
    "key": "file",
    "src": "/Users/kbentley/workspace/ca_rsa.resp.crt",
    "type": "file"
  ]] as [[String: Any]]

let boundary = "Boundary-\(UUID().uuidString)"
var body = Data()
var error: Error? = nil
for param in parameters {
  if param["disabled"] != nil { continue }
  let paramName = param["key"]!
  body += Data("--\(boundary)\r\n".utf8)
  body += Data("Content-Disposition:form-data; name=\"\(paramName)\"".utf8)
  if param["contentType"] != nil {
    body += Data("\r\nContent-Type: \(param["contentType"] as! String)".utf8)
  }
  let paramType = param["type"] as! String
  if paramType == "text" {
    let paramValue = param["value"] as! String
    body += Data("\r\n\r\n\(paramValue)\r\n".utf8)
  } else {
    let paramSrc = param["src"] as! String
    let fileURL = URL(fileURLWithPath: paramSrc)
    if let fileContent = try? Data(contentsOf: fileURL) {
      body += Data("; filename=\"\(paramSrc)\"\r\n".utf8)
      body += Data("Content-Type: \"content-type header\"\r\n".utf8)
      body += Data("\r\n".utf8)
      body += fileContent
      body += Data("\r\n".utf8)
    }
  }
}
body += Data("--\(boundary)--\r\n".utf8);
let postData = body


var request = URLRequest(url: URL(string: "{{apiPath}}/environments/{{envID}}/keys/{{keyID}}/csr")!,timeoutInterval: Double.infinity)
request.addValue("Bearer {{accessToken}}", forHTTPHeaderField: "Authorization")
request.addValue("", forHTTPHeaderField: "Content-Length")
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

request.httpMethod = "PUT"
request.httpBody = postData

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  guard let data = data else {
    print(String(describing: error))
    return
  }
  print(String(data: data, encoding: .utf8)!)
}

task.resume()

Example Response

200 OK

{
    "_links": {
        "self": {
            "href": "https://api.pingone.com/v1/environments/abfba8f6-49eb-49f5-a5d9-80ad5c98f9f6/keys/f245a32f-f85a-4aab-abda-3bab8c8cb0b1"
        }
    },
    "id": "f245a32f-f85a-4aab-abda-3bab8cxxxxxx",
    "name": "Doc test cert",
    "serialNumber": 12935964723820231176,
    "subjectDN": "CN=Doc test cert, OU=Ping Identity, O=Ping Identity, L=, ST=, C=US",
    "issuerDN": "O=ping, C=ca",
    "algorithm": "RSA",
    "keyLength": 2048,
    "createdAt": "2024-04-17T12:09:50.797Z",
    "startsAt": "2024-05-10T12:18:37.000Z",
    "expiresAt": "2025-05-10T12:18:37.000Z",
    "validityPeriod": 365,
    "signatureAlgorithm": "SHA256withRSA",
    "usageType": "SIGNING",
    "status": "VALID",
    "organization": {
        "id": "bed432e6-676a-4ebe-b5a5-6b3b54e46bda"
    },
    "environment": {
        "id": "abfba8f6-49eb-49f5-a5d9-80ad5c98f9f6"
    },
    "default": false
}