I've created a "test" project where I'm using a .Net 4.6 WebApi that I want to integrate authentication using ADFS - similar to this post. I'm calling the api from an angular project and using the following code I'm able to get the Authorization Header:
string authority = ConfigurationManager.AppSettings["adfsEndpoint"].ToString(); string resourceURI = "https://localhost:44388/"; string clientID = "someguid"; string clientReturnURI = "http://localhost:55695/"; var ac = new AuthenticationContext(authority, false); //This seems to be working as I am getting a token back after successful authentication var ar = await ac.AcquireTokenAsync(resourceURI, clientID, new Uri(clientReturnURI), new PlatformParameters(PromptBehavior.Auto)); string authHeader = ar.CreateAuthorizationHeader(); //this fails with a 401 var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:64038/api/Values"); request.Headers.TryAddWithoutValidation("Authorization", authHeader); var response = await client.SendAsync(request); return response ;
However, on a subsequent call to my ValuesController that is using the Authorize attribute, I always receive a 401 Unathorized response (even though I'm passing the Authorization header). I'm not sure what I'm missing.
One other thing to note: when I'm prompted for my credentials, I get the dialog below and not the typical ADFS login page I get with my normal MVC apps that authenticate using ADFS (I'm not sure why this happens either).
1 Answers
Answers 1
Ugh! Turns out I missed this piece of code that was needed in the ConfigureAuth method:
app.UseActiveDirectoryFederationServicesBearerAuthentication( new ActiveDirectoryFederationServicesBearerAuthenticationOptions { Audience = ConfigurationManager.AppSettings["ida:Audience"], MetadataEndpoint = ConfigurationManager.AppSettings["ida:MetadataEndpoint"] });
Once I added this and made the necessary configurations in the web.config file (and correcting the resourceUri variable passed into the AcquireTokenAsync method), I was able to make an http call from my api controller to the values controller that was decorated with the Authorize attribute using this code from the tutorial:
var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:64038/api/Values"); request.Headers.TryAddWithoutValidation("Authorization", authHeader); var response = await client.SendAsync(request); string responseString = await response.Content.ReadAsStringAsync(); return responseString;
This still won't work for an AngularJS client (which I now understand), so I'll look to implement the ADAL JS library for that.
Edit
As it turns out, based on this answer, it appears I will not be able to do what I was hoping to do (AngularJS app using WebApi backend using On-Premise ADFS). I've decided to use an MVC-AngularJS approach instead.
0 comments:
Post a Comment