Azure OAuth 2.0 – Client Credential Grant

When to use

If there is no end-user to provide authorization.

It’s important to note that the client application is afforded a certain level of trust in this scenario; you must assume that anyone with access to the client may have the same level off access to the resource. You would never do what I have done in my example code and leave the trusted client public and unsecured.

How to implement

Using ADAL, of course.

Code-wise, I’m representing the trusted client as another OWIN-hosted API, similar to the first but without any security for simplicity. The default controller has a single GET method which calls into our secured resource and returns the result.

The noteworthy section is the AquireToken overload which takes an instance of ClientCredential.

var authenticationContext = new AuthenticationContext("https://login.windows.net/yourtenantname");
var clientCredentials = new ClientCredential(
    "ClientID",         // Client ID
    "clientsecret");    // client secret, valid for one or two years

var authResult = authenticationContext.AcquireToken(
    "http://resourceapi", // resource ID
    clientCredentials);

As the flow diagram will show, this directly calls the auth server to retrieve a token based on the combination of client ID and client secret, which you’ll get from the Azure management portal.

When you register the client in Azure, make sure you register it as a “Web application and/or web API” then go to the configuration section where you’ll find an area called “Keys.”

clientsecret

You need to select a duration of either one or two years and then click Save. This key is your client secret and it will disappear after you leave the page so remember to put it somewhere safe. As you can see from the image, when you next return, the key will be hidden.

So, what’s happening?

It’s pretty simple, as the diagram shows.

clientgrant

  1. The client send it’s ID and secret to the authentication server
  2. If the credentials are valid, the server returns an authentication token. It will not return a refresh token but more about that later
  3. The client can now access the resource server with access token

Too easy. You can find the source here: https://github.com/AdamKorczynski/OAuth2.git

In summary

  • There is more than one way to get an access token
  • The Azure authentication library takes the pain out of the process
Advertisements

One thought on “Azure OAuth 2.0 – Client Credential Grant

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s