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.”
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.
- The client send it’s ID and secret to the authentication server
- If the credentials are valid, the server returns an authentication token. It will not return a refresh token but more about that later
- 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
- There is more than one way to get an access token
- The Azure authentication library takes the pain out of the process