How To Create Service Princiapls Of Ad In Linux
Document-based auth with Azure Service Principals from Linux command line
In his comprehensive article, Developer'southward guide to auth with Azure Resources Manager API, Dushyant Gill describes multiple authentication flows for obtaining an access token from Azure Agile Directory and using it to invoke Azure Resources Manager Balance APIs (ARM).
There are also multiple open-source Azure SDKs (Coffee, Node.js, Go, Carmine, Python, .NET) that encapsulate the necessary hallmark logic into convenient helper methods.
In this mail service, my aim is to demonstrate, in a deliberate semi-transmission fashion, how to obtain the access token via Azure Service Main with Document-based Authentication from Linux (east.g. CentOS 6.half dozen) command line using a few tools and raw Balance calls.
Permit's get started.
Generate Certificate
Use openssl control to generate a cocky-signed certificate and protect it with a PEM laissez passer phrase (eastward.m. P@ssword123):
openssl req -x509 -days 3650 -newkey rsa:2048 -keyout key.pem -out cert.pem
You should see two files created in the current direct:
- cert.pem contains the public cardinal
- central.pem contains the individual key
Document Thumbprint
To be able to uniquely identify the certificate, let'due south go its hexadecimal thumbprint:
openssl x509 -in cert.pem -fingerprint -noout
We will actually demand the thumbprint converted from its hexadecimal representation to base64. We can use sed to replace the colons and remove "SHA1 Fingerprint=" substring, xxd to convert to bytes, and base64 to encode.
Combining these steps together into the following piped command:
echo $(openssl x509 -in cert.pem -fingerprint -noout) | sed 'due south/SHA1 Fingerprint=//thou' | sed 's/://g' | xxd -r -ps | base64
Document Central Value
cert.pem file contains the public primal value of the self-signed certificate we generated. We will need to grab that value skipping the start and the last lines.
tail -n+2 cert.pem | head -n-1
Setup Azure CLI
To manage Azure via the command line from Linux, delight install and configure Azure CLI by following these instructions:
- Install Azure Control Line Interface (Azure CLI) on Linux
- Connect to your Azure subscription from the Azure Command Line Interface (Azure CLI)
One time Azure CLI is installed and you have logged in using your "organizational account", switch to the "ARM way":
azure config mode arm
Create Application and its Service Principal
Utilize Azure CLI to create an "Application" in the Azure Active Directory of your subscription by passing the public key value from cert.pem file (equally you recall from in a higher place tail/head are there to skip the first and last lines):
azure ad app create — name "myapp20150918" — home-folio "http://myapp20150918/" — identifier-uris "http://myapp20150918/" — key-usage "Verify" — finish-date "2020–01–01" — fundamental-value "$(tail -north+two cert.pem | caput -n-1)"
NOTE: If you lot get an fault message maxim "'ad' is non an azure command. See 'azure aid'", double bank check that yous switched to the ARM mode via "azure config mode arm".
Create the "Service Principal" object for the Application Id that was created in the previous call.
azure ad sp create <Copy and Paste Application Id GUID Here>
Assign proper role to the "Service Principal" using its Object Id. In this example, we will assign the "Contributor" role to the service main at the telescopic of the subscription then that information technology can admission and make changes to any resource grouping within the subscription.
azure role assignment create — objectId <Copy and Paste Service Principal Object Id GUID Hither> -o Contributor
Install node.js package jsonwebtoken
Visit http://jwt.io/ to learn more than nearly the JSON Web Token format and encounter many other libraries for JSON Spider web Token signing/verification available in various programming languages. I take picked Node.js since information technology is already bachelor on the Linux VM after installing the "Azure CLI". In addition, we need to make sure that the library nosotros use supports RSA-SHA256 algorithm that is expected by Azure Agile Directory when using certificate authentication.
Apply node package manager (npm) to install the jsonwebtoken packet:
npm install jsonwebtoken
Obtain Azure Active Directory Tenant Id
We too need to obtain our Azure Active Directory Tenant Id GUID to specify it within the token payload. Since we already have Azure CLI installed, we can obtain the Tenant Id by running the following command and copy-and-pasting the value returned in the "Tenant Id" column.
azure account listing
azure account show "Arsen Subscription Proper name"
Sign the JWT Token
Create a pocket-sized node.js script that we will phone call signjwt.js to sign the client assertion specifying the base64 encoded certificate thumbprint in the "x5t" additional header. Y'all volition recall that we obtained this base64 value in i of the primeval steps.
The other standard "claims" of the JSON Web Token should contain the post-obit values:
- "aud" (Audience) is set to https://login.microsoftonline.com/TENANT_ID _HERE/oauth2/token
- "iss" (Issuer) and "sub" (Discipline) are all set up to the Awarding Id GUID
- "jti" (JWT ID) is set to a unique identifier for the JWT (in this case I will set information technology to a random value)
- "nbf" (Not Earlier) is set to the UNIX timestamp denoting the commencement of the token validity period
- "exp" (Expiration Time) is set to the UNIX timestamp cogent the end of the token validity period
var jwt = require('jsonwebtoken');
var fs = crave('fs');
var cert = fs.readFileSync('cardinal.pem');
var additionalHeaders = {
"x5t":"HuMOEZfePZctStPVCVWgmQc90Pc="
}
var myJwt = {
"aud": "https://login.microsoftonline.com/TENANT_ID/oauth2/token",
"iss": "APPLICATION_ID",
"sub": "APPLICATION_ID",
"jti": "" + Math.random(),
"nbf": "" + (Math.flooring(Engagement.now()/1000)-1000),
"exp": "" + (Math.flooring(Appointment.now()/1000)+7*8640000)
};
console.log(myJwt);
var token = jwt.sign(myJwt,cert,{algorithm:'RS256', header:additionalHeaders});
panel.log(token);
Execute the script we created
node signjwt.js
Validate Signed JWT Token
Nosotros can use http://jwt.io/ to validate that the token is parsing correctly. The signed token consists of three parts: base64(header).base64(body).base64(signature) without the "==" at the end.
Example of what JWT looks similar with a signature:
Become Access Token from Azure Active Directory
We will use Postman, Fiddler, or any of your other favorite HTTP request builder tools to manually submit a raw HTTP request to the Azure Agile Directory endpoint passing in all of the required parameters and obtaining back the Bearer access token that we tin use to admission Azure Resource Manager APIs.
Nosotros volition brand an HTTPS Postal service to this OAuth endpoint for your Azure Active Directory tenant: https://login.microsoftonline.com/TENANT_ID/oauth2/token
The asking body must contain the following parameters:
HTTPS Mail URL https://login.microsoftonline.com/TENANT_ID/oauth2/token
grant_type client_credentials
client_id This should be set up to your Application Id GUID
client_assertion_type This should be set to a specific value telling Azure Active Directory OAuth endpoint that nosotros will be using certificate hallmark instead of "password" urn:ietf:params:oauth:customer-assertion-type:jwt-bearer
client_assertion This is the signed JWT token. It volition be a long value. Remember, it was signed using our little signjwt.js script and the private key from the key.pem file. Azure Active Directory will validate this assertion's signature using the public cardinal (cert.pem) that we submitted to Azure when creating the application via Azure CLI.
resources This is the endpoint for the resource that we are asking Azure Active Directory to issue the states a token for. In example of Azure Resource Manager, it should be ready to the post-obit URL since that Residuum API start with this value https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/{resource-group}/providers/{provider-namespace}/
https://management.azure.com/
We can also obtain the access token from the command line using curl
ringlet
— data "grant_type=client_credentials&client_id=APPLICATION_ID&client_assertion_type=urn:ietf:params:oauth:customer-assertion-blazon:jwt-bearer&client_assertion=SIGNED_JWT&resource=https://direction.azure.com/" https://login.microsoftonline.com/TENTANT_ID/oauth2/token
Access Azure Resource Manager API
At present that we obtained the "access_token", we can apply information technology to access Azure Resource Manager Balance API.
We volition manually construct a simple HTTP request to get the listing of resources groups and ostend that the access token is working as expected.
HTTPS GET URL You will demand your subscription id, which yous can obtain using "azure account list" Azure CLI command and looking at the Id column https://management.azure.com/subscriptions/SUBSCRIPTION_ID/resourcegroups?api-version=2015-01-01
HTTP_HEADER Authorization
Bearer ACCESS_TOKEN_ISSUED_BY_AZURE_ACTIVE_DIRECTORY
We can too perform this examination from the command line using the following coil command and getting back a JSON response from the Azure Resource Manager Remainder API:
curl -H "Say-so: Bearer ACCESS_TOKEN_HERE" https://management.azure.com/subscriptions/SUBSCRIPTION_ID/resourcegroups?api-version=2015-01-01
Conclusion
Past now we should have a pretty skillful agreement of how to manually authenticate via Azure Active Directory using an application Service Principal and certificates, how to obtain the OAuth admission token, and how to use it to invoke Azure Resources Manager REST APIs — all from Linux command line.
Whenever possible, I recommend using the available Azure SDKs with all of the inbuilt helper methods. Withal, I as well find it useful to manually step through a process to get a deeper understanding of what is happening backside the scenes.
I'thou looking forrad to your feedback or questions via Twitter https://twitter.com/ArsenVlad
How To Create Service Princiapls Of Ad In Linux,
Source: https://arsenvlad.medium.com/certificate-based-auth-with-azure-service-principals-from-linux-command-line-a440c4599cae
Posted by: cervantezglanking.blogspot.com
0 Response to "How To Create Service Princiapls Of Ad In Linux"
Post a Comment