TheRocinante
TheRocinante

Reputation: 4201

Get AngularJS to talk to .NET Web API secured with Azure AD

I have two different web projects on Microsoft Azure. One project is a .NET MVC web application and the other project is a .NET Web API.

Both projects are configured to use Azure AD. The MVC web application is able to get a token and use it to make requests against the Web API. Here's sample code from the MVC web app.

string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID));
ClientCredential credential = new ClientCredential(clientId, appKey);
result = authContext.AcquireTokenSilent(todoListResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

// Make a call against the Web Api
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, webApiBaseAddress + "/api/list");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await client.SendAsync(request);

So this code works just fine. However, what I need to do now is call the Web API directly from an AngularJS application. When I try to do that, I get a 401 unauthorized error.

The way I am doing this is by adding a header to the HTTP GET request sent by AngularJS. I'm setting "Bearer" to the result.AccessToken value that I am passing to the page from my MVC application (code above).

Obviously this doesn't work. I suppose now my question is what are my options? Is there an official or better way to do this? Let's say I wanted to make calls to the Web API from standard JavaScript (lets forget the complexities of AngularJS). Is there a way to authenticate with Azure AD?

Upvotes: 0

Views: 648

Answers (2)

vibronet
vibronet

Reputation: 7394

The work I mentioned in the older answer finally hit the preview stage. Please take a look at http://www.cloudidentity.com/blog/2014/10/28/adal-javascript-and-angularjs-deep-dive/ - that should solve precisely the scenario you described. If you have feedback on the library please do let us know! Thanks V.

Upvotes: 1

vibronet
vibronet

Reputation: 7394

the canonical way of obtaining a token for an in-browser JS application would be to use the OAuth2 implicit flow. Azure AD does not currently expose that flow, but stay tuned: we are working on enabling the scenario. No dates to share yet.

HTH! V.

Upvotes: 2

Related Questions