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!

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

Parameters

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.

HTTP POST

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 https://login.microsoftonline.com/{Tenant ID}/oauth2/v2.0/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
x-ms-version: 2018-11-01
Host: login.microsoftonline.com
content-length: ...

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

That’s it.

Complicated?

That gives us a response like:

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

{"token_type":"Bearer","expires_in":3600,"ext_expires_in":3600,"access_token":"VERY_LONG_STRING"}

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}”.

Summary

That’s it. Nice and easy.

But even easier is MSI. Look it up.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s