Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

401 when authenticating an OAuth 2.0 bearer token with Microsoft Azure Active Directory in an MVC API

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:

Calling endpoint

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:

Creating a token in Postman

like image 781
Ilya Kogan Avatar asked Sep 30 '14 10:09

Ilya Kogan


1 Answers

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.

like image 56
Ilya Kogan Avatar answered Oct 05 '22 04:10

Ilya Kogan