Authenticating an Azure service principal

When it comes to using Service Principal in Azure, I always advise using Managed System Identity (MSI).

MSI is simpler and safer. MSI handles certificate rotations. We never see the certificate. Remember this: the safest secret is the secret you never see.

But in cases we can’t use MSI, we are going to give a recipe to do this over HTTP.

There are libraries that pre-packaged that code, but it’s one HTTPS post. Not exactly rocket science.

I realized last week I didn’t have that HTTPS POST pattern handy and for some reason it doesn’t pop in the top 3 when I search for it… So, I decided I was going to write a short article so I could search it later!

You are welcome future self!

Update 22-08-2019: I realized there was a little error in the use of the API and that the online doc covers it pretty well. So here is the online doc for OAuth v1 and OAuth v2.

I’m going to cover only “secret authentication”, i.e. not certificate based authentication.


Here are the parameters we are going to use:

Parameter Description
Tenant ID Azure AD tenant the Service Principal belongs to ; it's a GUID
Audience Also called the scope or resource. This is what we are going to authenticate against. If it's an Azure AD application, it can be its application ID. It can also be a URI.
Client ID This is the Application ID of the Service Principal
Client Secret A secret of the application. Sometimes refer to as a password.


We need something to build an HTTP post.

It could be Postman or any other tool. It can be .NET, Java, Python, Go, whatever code.

HTTP Request

So here we go. Ready?

Request (parameters defined above are referred to in {curly braces}):

POST{Tenant ID}/oauth2/v2.0/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
x-ms-version: 2018-11-01
content-length: ...

grant_type=client_credentials&scope={Audience}&client_id={Client ID}&client_secret={Client Secret}

That’s it.


That gives us a response like:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: ...


Using authentication

Typically, we use the response of the authentication by keeping the token type and access token part of the JSON payload.

We can then use it to authenticate subsequent requests by adding an HTTP header “authentication” with the value “{token type} {access token}”.


That’s it. Nice and easy.

But even easier is MSI. Look it up.

Leave a comment