I'm writing an API service in MVC (no views, just API), and I want to use OAuth 2.0 tokens acquired via the client_credentials flow (2-legged OAuth). I created an ActiveDirectory app in the Azure management portal, and have successfully acquired a bearer token (see screenshot from Postman at the bottom).
Then I installed the Microsoft.Owin.Security.ActiveDirectory
nuget package, created an Owin startup class and wrote the following code in it:
public class OwinStartup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
var myoptions = new WindowsAzureActiveDirectoryBearerAuthenticationOptions();
myoptions.Audience = // my App ID
myoptions.Tenant = // my tenant
myoptions.AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive;
app.UseWindowsAzureActiveDirectoryBearerAuthentication(myoptions);
}
}
I added a controller with an action, and I would like the action to be accessible with the bearer token.
This is the controller:
public class TestController : Controller
{
[Authorize]
public JsonResult Index()
{
return Json(3, JsonRequestBehavior.AllowGet);
}
}
I'm trying to call it with the Authorization header like this:
However, I'm getting 401: "You do not have permission to view this directory or page". The details are:
Module ManagedPipelineHandler
Notification ExecuteRequestHandler
Handler System.Web.Mvc.MvcHandler
Error Code 0x00000000
Requested URL http://localhost:57872/test
Logon Method Anonymous
Logon User Anonymous
It looks that my bearer token is ignored.
What am I doing wrong?
Appendix: Creating an Azure Active Directory OAuth bearer token in Postman with the client_credentials flow:
It seems that I can get it to work by creating a second application in AD - a client app, authorizing it to the service app, and requesting the authentication token as the client rather than as the service.
So in the token request I had to use the client app's ID and secret instead of the original ones and add another parameter: "resource", whose value is the service app ID: https://mytenant.onmicrosoft.com/servieappname
I based my solution on this good example by Microsoft. Replaced the Windows store app by a web app acting as the client.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With