servicePrincipal: addKey
Article
07/20/2022
5 minutes to read
9 contributors
In this article
Namespace: microsoft.graph
Adds a key credential to a servicePrincipal . This method along with removeKey can be used by a servicePrincipal to automate rolling its expiring keys.
As part of the request validation for this method, a proof of possession of an existing key is verified before the action can be performed.
ServicePrincipals that don’t have any existing valid certificates (i.e.: no certificates have been added yet, or all certificates have expired), won’t be able to use this service action. Update servicePrincipal can be used to perform an update instead.
Permissions
Permission type
Permissions (from least to most privileged)
Delegated (work or school account)
Application.ReadWrite.All, Directory.ReadWrite.All
Delegated (personal Microsoft account)
None.
Application
Application.ReadWrite.OwnedBy, Application.ReadWrite.All, Directory.ReadWrite.All
HTTP request
POST /servicePrincipals/{id}/addKey
Name
Description
Authorization
Bearer {token}. Required.
Content-Type
application/json. Required.
Request body
In the request body, provide the following required properties.
Property
Type
Description
keyCredential
keyCredential
The new servicePrincipal key credential to add. The type , usage and key are required properties for this usage. Supported key types are:AsymmetricX509Cert: The usage must be Verify.X509CertAndPassword: The usage must be Sign
passwordCredential
passwordCredential
Only secretText is required to be set which should contain the password for the key. This property is required only for keys of type X509CertAndPassword. Set it to null otherwise.
proof
String
A self-signed JWT token used as a proof of possession of the existing keys. This JWT token must be signed using the private key of one of the servicePrincipal's existing valid certificates. The token should contain the following claims:aud - Audience needs to be 00000002-0000-0000-c000-000000000000.iss - Issuer needs to be the id of the servicePrincipal that is making the call.nbf - Not before time.exp - Expiration time should be "nbf" + 10 mins. Here is a code sample that can be used to generate this proof of possession token.
Response
If successful, this method returns a 200 OK response code and a new keyCredential object in the response body.
Examples
Example 1: Adding a new key credential to a servicePrincipal
Request
The following is an example of the request.
POST https://graph.microsoft.com/v1.0/servicePrincipals/{id}/addKey
Content-type: application/json
{
"keyCredential": {
"type": "AsymmetricX509Cert",
"usage": "Verify",
"key": "MIIDYDCCAki..."
},
"passwordCredential": null,
"proof":"eyJ0eXAiOiJ..."
}
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var keyCredential = new KeyCredential
{
Type = "AsymmetricX509Cert",
Usage = "Verify",
Key = Convert.FromBase64String("MIIDYDCCAki...")
};
PasswordCredential passwordCredential = null;
var proof = "eyJ0eXAiOiJ...";
await graphClient.ServicePrincipals["{servicePrincipal-id}"]
.AddKey(keyCredential,proof,passwordCredential)
.Request()
.PostAsync();
For details about how to add the SDK to your project and create an authProvider instance, see the SDK documentation .
const options = {
authProvider,
};
const client = Client.init(options);
const keyCredential = {
keyCredential: {
type: 'AsymmetricX509Cert',
usage: 'Verify',
key: 'MIIDYDCCAki...'
},
passwordCredential: null,
proof: 'eyJ0eXAiOiJ...'
};
await client.api('/servicePrincipals/{id}/addKey')
.post(keyCredential);
For details about how to add the SDK to your project and create an authProvider instance, see the SDK documentation .
GraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider( authProvider ).buildClient();
KeyCredential keyCredential = new KeyCredential();
keyCredential.type = "AsymmetricX509Cert";
keyCredential.usage = "Verify";
keyCredential.key = Base64.getDecoder().decode("MIIDYDCCAki...");
String proof = "eyJ0eXAiOiJ...";
graphClient.servicePrincipals("{id}")
.addKey(ServicePrincipalAddKeyParameterSet
.newBuilder()
.withKeyCredential(keyCredential)
.withPasswordCredential(passwordCredential)
.withProof(proof)
.build())
.buildRequest()
.post();
For details about how to add the SDK to your project and create an authProvider instance, see the SDK documentation .
//THE GO SDK IS IN PREVIEW. NON-PRODUCTION USE ONLY
graphClient := msgraphsdk.NewGraphServiceClient(requestAdapter)
requestBody := graphmodels.NewKeyCredentialPostRequestBody()
keyCredential := graphmodels.NewKeyCredential()
type := "AsymmetricX509Cert"
keyCredential.SetType(&type)
usage := "Verify"
keyCredential.SetUsage(&usage)
key := []byte("mIIDYDCCAki...")
keyCredential.SetKey(&key)
requestBody.SetKeyCredential(keyCredential)
passwordCredential := null
requestBody.SetPasswordCredential(&passwordCredential)
proof := "eyJ0eXAiOiJ..."
requestBody.SetProof(&proof)
result, err := graphClient.ServicePrincipalsById("servicePrincipal-id").AddKey().Post(requestBody)
For details about how to add the SDK to your project and create an authProvider instance, see the SDK documentation .
Import-Module Microsoft.Graph.Applications
$params = @{
KeyCredential = @{
Type = "AsymmetricX509Cert"
Usage = "Verify"
Key = [System.Text.Encoding]::ASCII.GetBytes("MIIDYDCCAki...")
}
PasswordCredential = $null
Proof = "eyJ0eXAiOiJ..."
}
Add-MgServicePrincipalKey -ServicePrincipalId $servicePrincipalId -BodyParameter $params
For details about how to add the SDK to your project and create an authProvider instance, see the SDK documentation .
<?php
// THIS SNIPPET IS A PREVIEW FOR THE KIOTA BASED SDK. NON-PRODUCTION USE ONLY
$graphServiceClient = new GraphServiceClient($requestAdapter);
$requestBody = new KeyCredentialPostRequestBody();
$keyCredential = new KeyCredential();
$keyCredential->setType('AsymmetricX509Cert');
$keyCredential->setUsage('Verify');
$KeyCredential->setKey(base64_decode('MIIDYDCCAki...'));
$requestBody->setKeyCredential($keyCredential);
$requestBody->setPasswordCredential(null);
$requestBody->setProof('eyJ0eXAiOiJ...');
$requestResult = $graphServiceClient->servicePrincipalsById('servicePrincipal-id')->addKey()->post($requestBody);
For details about how to add the SDK to your project and create an authProvider instance, see the SDK documentation .
Response
The following is an example of the response.
HTTP/1.1 200 OK
Content-Type: application/json
{
"@odata.context": "https://graph.microsoft.com/v1.0/$metadata#microsoft.graph.keyCredential"
}
Example 2: Adding a key credential and an associated password for the key
Request
The following is an example of the request.
POST https://graph.microsoft.com/v1.0/servicePrincipals/{id}/addKey
Content-type: application/json
{
"keyCredential": {
"type": "X509CertAndPassword",
"usage": "Sign",
"key": "MIIDYDCCAki..."
},
"passwordCredential": {
"secretText": "MKTr0w1..."
},
"proof":"eyJ0eXAiOiJ..."
}
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var keyCredential = new KeyCredential
{
Type = "X509CertAndPassword",
Usage = "Sign",
Key = Convert.FromBase64String("MIIDYDCCAki...")
};
var passwordCredential = new PasswordCredential
{
SecretText = "MKTr0w1..."
};
var proof = "eyJ0eXAiOiJ...";
await graphClient.ServicePrincipals["{servicePrincipal-id}"]
.AddKey(keyCredential,proof,passwordCredential)
.Request()
.PostAsync();
For details about how to add the SDK to your project and create an authProvider instance, see the SDK documentation .
const options = {
authProvider,
};
const client = Client.init(options);
const keyCredential = {
keyCredential: {
type: 'X509CertAndPassword',
usage: 'Sign',
key: 'MIIDYDCCAki...'
},
passwordCredential: {
secretText: 'MKTr0w1...'
},
proof: 'eyJ0eXAiOiJ...'
};
await client.api('/servicePrincipals/{id}/addKey')
.post(keyCredential);
For details about how to add the SDK to your project and create an authProvider instance, see the SDK documentation .
GraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider( authProvider ).buildClient();
KeyCredential keyCredential = new KeyCredential();
keyCredential.type = "X509CertAndPassword";
keyCredential.usage = "Sign";
keyCredential.key = Base64.getDecoder().decode("MIIDYDCCAki...");
PasswordCredential passwordCredential = new PasswordCredential();
passwordCredential.secretText = "MKTr0w1...";
String proof = "eyJ0eXAiOiJ...";
graphClient.servicePrincipals("{id}")
.addKey(ServicePrincipalAddKeyParameterSet
.newBuilder()
.withKeyCredential(keyCredential)
.withPasswordCredential(passwordCredential)
.withProof(proof)
.build())
.buildRequest()
.post();
For details about how to add the SDK to your project and create an authProvider instance, see the SDK documentation .
//THE GO SDK IS IN PREVIEW. NON-PRODUCTION USE ONLY
graphClient := msgraphsdk.NewGraphServiceClient(requestAdapter)
requestBody := graphmodels.NewKeyCredentialPostRequestBody()
keyCredential := graphmodels.NewKeyCredential()
type := "X509CertAndPassword"
keyCredential.SetType(&type)
usage := "Sign"
keyCredential.SetUsage(&usage)
key := []byte("mIIDYDCCAki...")
keyCredential.SetKey(&key)
requestBody.SetKeyCredential(keyCredential)
passwordCredential := graphmodels.NewPasswordCredential()
secretText := "MKTr0w1..."
passwordCredential.SetSecretText(&secretText)
requestBody.SetPasswordCredential(passwordCredential)
proof := "eyJ0eXAiOiJ..."
requestBody.SetProof(&proof)
result, err := graphClient.ServicePrincipalsById("servicePrincipal-id").AddKey().Post(requestBody)
For details about how to add the SDK to your project and create an authProvider instance, see the SDK documentation .
Import-Module Microsoft.Graph.Applications
$params = @{
KeyCredential = @{
Type = "X509CertAndPassword"
Usage = "Sign"
Key = [System.Text.Encoding]::ASCII.GetBytes("MIIDYDCCAki...")
}
PasswordCredential = @{
SecretText = "MKTr0w1..."
}
Proof = "eyJ0eXAiOiJ..."
}
Add-MgServicePrincipalKey -ServicePrincipalId $servicePrincipalId -BodyParameter $params
For details about how to add the SDK to your project and create an authProvider instance, see the SDK documentation .
<?php
// THIS SNIPPET IS A PREVIEW FOR THE KIOTA BASED SDK. NON-PRODUCTION USE ONLY
$graphServiceClient = new GraphServiceClient($requestAdapter);
$requestBody = new KeyCredentialPostRequestBody();
$keyCredential = new KeyCredential();
$keyCredential->setType('X509CertAndPassword');
$keyCredential->setUsage('Sign');
$KeyCredential->setKey(base64_decode('MIIDYDCCAki...'));
$requestBody->setKeyCredential($keyCredential);
$passwordCredential = new PasswordCredential();
$passwordCredential->setSecretText('MKTr0w1...');
$requestBody->setPasswordCredential($passwordCredential);
$requestBody->setProof('eyJ0eXAiOiJ...');
$requestResult = $graphServiceClient->servicePrincipalsById('servicePrincipal-id')->addKey()->post($requestBody);
For details about how to add the SDK to your project and create an authProvider instance, see the SDK documentation .
Response
The following is an example of the response.
HTTP/1.1 200 OK
Content-Type: application/json
{
"@odata.context": "https://graph.microsoft.com/v1.0/$metadata#microsoft.graph.keyCredential"
}