API Authentication

How to create a certificate? #

OpenSSL library is used here with the help of OpenSSL Command Prompt that can be found here.

  • For Windows, make sure you run the prompt with elevated privileges (Run as Administrator)

Here are the commands to create a .crt file to be used for authenticating against the VaultN API.

openssl req -new -newkey rsa:2048 -passout pass:password -nodes -out sample.csr -keyout sample.key

openssl x509 -req -days 365 -in sample.csr -signkey sample.key -out sample.crt

openssl pkcs12 -export -in sample.crt -inkey sample.key -out sample.pfx

  • The first command should prompt multiple short input, the last of which is an e-mail address. If you cannot reach that prompt, it could mean there are issues, possibly with privileges.
  • It creates 4 files in your working folder. (.crt, .csr, .key, .pfx files) .crt file is to be uploaded to VaultN via UI.
  • Upload the .crt file on the VaultN UI.
    • VaultN -> Settings -> Certificates -> + Add Certificate

Additional Notes

  • -pass parameter in the first command defines the password that you will be asked for in the second command and during the token creation later.
  • -days parameter in the second command defines the validity period of the certificate and may be adjusted as seen fit.
  • In case of re-uploads to VaultN, .crt filename should be different than the existing certificates. Upload may fail without prompt in case of same filenames.

How to get an access token? #

Once the certificate is created and uploaded, it is now used for authenticating against the API.

The following code snippets in (currently available for C#) demonstrates how to acquire the token string.

public string GenerateToken(string vaultGuid) 
{ 
  var tokenHandler = new JwtSecurityTokenHandler(); 
  var cert = new X509Certificate2("{pfxFilePath}", "{pfxPassword}"); 
	var cred = new X509SigningCredentials(cert); 
 
	var tokenDescriptor = new SecurityTokenDescriptor { 
    Issuer = "Self", 
    Audience = "VAULTN", 
    Subject = new ClaimsIdentity(new Claim[] { 
      new Claim(JwtRegisteredClaimNames.Sub, userGuid)  }), 
    Expires = DateTime.UtcNow.AddDays(14), 
    SigningCredentials = cred 
 	};
  
 	var token = tokenHandler.CreateToken(tokenDescriptor); 
	var retval = tokenHandler.WriteToken(token);
  
  return retval;
}
  • Replace the .pfx file path and password accordingly.
  • While defining the Claim, use your VaultN Guid as the parameter vaultGuid _found under _VaultN -> Settings.
  • It is to be used as a Bearer token.

Additional Notes

  • For C#
    • Add System.IdentityModel.Tokens.Jwt as a reference to your project.
    • AddDays() -> defines the validity period for the claim. It can be as long as the certificate is good for.
  • For PHP
    • Use command “composer require firebase/php-jwt”.
    • The used PHP version is 5.6.
    • “exp” => time() + (60 * 60 * 24 * 365) -> last parameter defines the validity of the token in seconds.

Powered by BetterDocs