PingOne Platform APIs

Create Certificate with PKCS7 or PEM File

 

POST {{apiPath}}/environments/{{envID}}/certificates

The POST {{apiPath}}/environments/{{envID}}/certificates operation creates a new certificate resource for the specified environment. It creates a certificate from an upload of a PKCS7 or PEM file with public and trust certificates. Properties returned in the response are parsed from the uploaded file.

The response returns a 202 Accepted message and shows the certificate data parsed from the uploaded certificate file.

Prerequisites

Headers

Authorization      Bearer {{accessToken}}

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

Body

formdata

Key Type Value

file

file

usageType

text

SIGNING

Example Request

  • cURL

  • C#

  • Go

  • HTTP

  • Java

  • jQuery

  • NodeJS

  • Python

  • PHP

  • Ruby

  • Swift

curl --location --globoff '{{apiPath}}/environments/{{envID}}/certificates' \
--header 'Authorization: Bearer {{accessToken}}' \
--form 'file=@"/Users/kbentley/Downloads/cert.crt"' \
--form 'usageType="SIGNING"'
var options = new RestClientOptions("{{apiPath}}/environments/{{envID}}/certificates")
{
  MaxTimeout = -1,
};
var client = new RestClient(options);
var request = new RestRequest("", Method.Post);
request.AddHeader("Authorization", "Bearer {{accessToken}}");
request.AlwaysMultipartFormData = true;
request.AddFile("file", "/Users/kbentley/Downloads/cert.crt");
request.AddParameter("usageType", "SIGNING");
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}}/certificates"
  method := "POST"

  payload := &bytes.Buffer{}
  writer := multipart.NewWriter(payload)
  file, errFile1 := os.Open("/Users/kbentley/Downloads/cert.crt")
  defer file.Close()
  part1,
         errFile1 := writer.CreateFormFile("file",filepath.Base("/Users/kbentley/Downloads/cert.crt"))
  _, errFile1 = io.Copy(part1, file)
  if errFile1 != nil {
    fmt.Println(errFile1)
    return
  }
  _ = writer.WriteField("usageType", "SIGNING")
  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))
}
POST /environments/{{envID}}/certificates HTTP/1.1
Host: {{apiPath}}
Authorization: Bearer {{accessToken}}
Content-Length: 293
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

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

(data)
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="usageType"

SIGNING
------WebKitFormBoundary7MA4YWxkTrZu0gW--
OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
  .addFormDataPart("file","cert.crt",
    RequestBody.create(MediaType.parse("application/octet-stream"),
    new File("/Users/kbentley/Downloads/cert.crt")))
  .addFormDataPart("usageType","SIGNING")
  .build();
Request request = new Request.Builder()
  .url("{{apiPath}}/environments/{{envID}}/certificates")
  .method("POST", 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], "cert.crt");
form.append("usageType", "SIGNING");

var settings = {
  "url": "{{apiPath}}/environments/{{envID}}/certificates",
  "method": "POST",
  "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': 'POST',
  'url': '{{apiPath}}/environments/{{envID}}/certificates',
  'headers': {
    'Authorization': 'Bearer {{accessToken}}',
    'Content-Length': ''
  },
  formData: {
    'file': {
      'value': fs.createReadStream('/Users/kbentley/Downloads/cert.crt'),
      'options': {
        'filename': 'cert.crt',
        'contentType': null
      }
    },
    'usageType': 'SIGNING'
  }
};
request(options, function (error, response) {
  if (error) throw new Error(error);
  console.log(response.body);
});
import requests

url = "{{apiPath}}/environments/{{envID}}/certificates"

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

response = requests.request("POST", 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}}/certificates');
$request->setMethod(HTTP_Request2::METHOD_POST);
$request->setConfig(array(
  'follow_redirects' => TRUE
));
$request->setHeader(array(
  'Authorization' => 'Bearer {{accessToken}}',
  'Content-Length' => ''
));
$request->addPostParameter(array(
  'usageType' => 'SIGNING'
));
$request->addUpload('file', '/Users/kbentley/Downloads/cert.crt', 'cert.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}}/certificates")

http = Net::HTTP.new(url.host, url.port);
request = Net::HTTP::Post.new(url)
request["Authorization"] = "Bearer {{accessToken}}"
request["Content-Length"] = ""
form_data = [['file', File.open('/Users/kbentley/Downloads/cert.crt')],['usageType', 'SIGNING']]
request.set_form form_data, 'multipart/form-data'
response = http.request(request)
puts response.read_body
let parameters = [
  [
    "key": "file",
    "src": "/Users/kbentley/Downloads/cert.crt",
    "type": "file"
  ],
  [
    "key": "usageType",
    "value": "SIGNING",
    "type": "text"
  ]] 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}}/certificates")!,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 = "POST"
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

202 Accepted

{
    "_links": {
        "self": {
            "href": "https://api.pingone.com/v1/environments/abfba8f6-49eb-49f5-a5d9-80ad5c98f9f6/certificates"
        }
    },
    "id": "699cbbc5-11a3-49cd-9c5c-ad5f27300a44",
    "name": "kb doc test",
    "serialNumber": 1604411669268,
    "issuerDN": "CN=kb doc test,OU=,O=myOrg,L=,ST=,C=CA",
    "subjectDN": "CN=kb doc test,OU=,O=myOrg,L=,ST=,C=CA",
    "algorithm": "RSA",
    "keyLength": 2048,
    "createdAt": "2020-12-16T16:48:35.784Z",
    "expiresAt": "2021-11-03T13:54:29.000Z",
    "startsAt": "2020-11-03T13:54:29.000Z",
    "validityPeriod": 365,
    "signatureAlgorithm": "SHA256withRSA",
    "usageType": "SIGNING",
    "status": "VALID",
    "environment": {
        "id": "abfba8f6-49eb-49f5-a5d9-80ad5c98f9f6"
    }
}