Thursday, June 04, 2015

ADFS : Protecting Web API with OAuth2

This is for Active Directory Federation Services / "AD FS" / ADFS on Windows Server 2016 (currently Technical Preview 2).

It also uses the Active Directory Authentication Library (ADAL).

Vittorio has a good overview describing Server 2012 behaviour over at Securing a Web API with ADFS on WS2012 R2 Got Even Easier.

How does that look on Server 2016?

The VS solution is pretty much the same. I added a Windows Forms project to the solution which is my native client and the code for that (behind the button) is pretty much the same as  the above post. This calls a web API project in the same solution.

private async void button1_Click(object sender, EventArgs e)
            string authority = "";
            string resourceURI = "https://myPC/WinServTP2ADALWebApplication/";
            string clientID = "API1234";
            string clientReturnURI = "https://myPC/WinServTP2ADALWebApplication/";

            AuthenticationContext ac = new AuthenticationContext(authority, false);
            AuthenticationResult ar = ac.AcquireToken(resourceURI, clientID, new Uri(clientReturnURI));

            string authHeader = ar.CreateAuthorizationHeader();
            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://myPC/WinServTP2ADALWebApplication/api/Values");
            request.Headers.TryAddWithoutValidation("Authorization", authHeader);
            HttpResponseMessage response = await client.SendAsync(request);
            string responseString = await response.Content.ReadAsStringAsync();

ADFS_local is a Windows Server 2016 server running as an Azure VM.

Over to ADFS.

The OAuth client now has wizard support as opposed to the PowerShell in the post. It looks like:

You do this under "Clients".

We add the RP manually and notice the new OAuth option.

Notice also the extra menu items on the LHS for OAuth.

You can click on the "All Clients" to add more permissions (scopes). At the moment, it is just for "openid". You could also click on "Add" and select a specific client.

I added "email" and "profile".

(BTW, there is a separate "Scope Descriptions" item in the main menu).

Then choose your Access Policy on the next screen - in this case "Permit everyone". Review and you are done.

So looking at our RP, we have an identifier:

and some OAuth permissions - notice the new tab. That's pretty much it.

OK - so now we have the client and the web API RP all configured and ready to go.

Time to run up the client:

Click the button which calls the API. This is protected as per the configuration and so we get the ADFS logon screen. Authenticate with ADFS and:

We are done!


No comments: