HttpClient to call Azure AD-protected site

5k Views Asked by At

Following some Microsoft samples, I got to this point:

ASP.NET Core setup:

app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
    ClientId = Configuration["Authentication:AzureAD:ClientId"],
    Authority = Configuration["Authentication:AzureAd:Authority"],
    ResponseType = OpenIdConnectResponseType.IdToken,
    AutomaticAuthenticate = true,
    TokenValidationParameters = new TokenValidationParameters()
});

AuthorizationTest endpoint:

[HttpGet]
[Authorize]
public IActionResult Get()
{
    return Ok("SAMPLE TEXT - if you can read this then call it a day :)");
}

Client:

try
{
   var result = await authContext.AcquireTokenAsync(WebApiResourceId, WebApiClientId, WebApiRedirectUri, new PlatformParameters(PromptBehavior.Auto));
   authorizedClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

   var authorizedMessage = await authorizedClient.GetAsync("/AuthorizationTest");
   var statusCode = authorizedMessage.StatusCode.ToString();
   var message = await authorizedMessage.Content.ReadAsStringAsync();
   webBrowser.NavigateToString(message);
 }

And the authorizedClient is initiated as:

private static HttpClientHandler handler = new HttpClientHandler
{
    AllowAutoRedirect = true,
    CookieContainer = new CookieContainer(),
    UseCookies = true
 };
 private static HttpClient authorizedClient = new HttpClient(handler, false) { BaseAddress = WebApiBaseUri };

I used to initialize it only with the BaseAddress, and later added the handler following an answer here on So.

The problem:
Even though I get the token from AAD correctly, the response from the WEB API endpoint is an HTML (after an auto-redirect) that is the MS login page with the error "Your browser is set to block cookies....."

What should I change to make the HttpClient work? Or can I change the WebApi configuration to not use cookies? For the latter option I couldn't find any other alternative.

2

There are 2 best solutions below

0
On BEST ANSWER

As discussed in the comments, you need to use the JWT bearer token middleware from the package Microsoft.AspNetCore.Authentication.JwtBearer.

The Open ID Connect middleware is designed to redirect a user to a sign in page, not for authenticating access tokens. An example usage of the JWT bearer token middleware can be found here: https://github.com/Azure-Samples/active-directory-dotnet-native-aspnetcore/blob/master/TodoListService/Startup.cs.

0
On

Take a look at this thread: https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/issues/514 - it is showing the scenario you are trying to achieve.