0
votes

I have an asp.net core web api which uses AzureAd registered app service for authentication.
It's purpose will be to act as a backend service to UI front ends.
I have tested security functionality using postman, headers, JWT Authorization, etc., and that works successfully.
Now, I have created a front end in asp.net core 2.1 as an MVC web app.
I have AzureAd login working on the front end.
As a test, I have tried an ajax request to the backend web api.
But, I get a 401 Unauthorized response because I do not know how to pass the Authorization Bearer in the request headers, I presume this is my problem.

My question is how is this done?
How do I authenticate to an asp.net core web api from an asp.net core web app?
I would like to use a streamlined approach like this, if possible.
And/Or, is there a better approach?

Thanks you your help.

1

1 Answers

0
votes

I found my own answer to this problem after reading about middleware and HttpClient requests. In case anyone finds their self in the same boat here is how I solved it.

  1. Capture the azure "Bearer" token and store token server-side as an identity claim of the user.
  2. Make a method to send http requests to the Web Api.

Like this as follows:

GETTING AND STORING THE TOKEN This goes in your startup.cs where you configure servcies for AzureAd/OpenIdConnect.

builder.Services.Configure(configureOptions);
        builder.Services.AddSingleton<IConfigureOptions<OpenIdConnectOptions>, ConfigureAzureOptions>();
        builder.AddOpenIdConnect(o =>
        {
            //Additional config snipped
            o.Events = new OpenIdConnectEvents
            {
                OnTokenValidated = async context =>
                {
                    ClaimsIdentity identity = context.Principal.Identity as ClaimsIdentity;
                    if (identity != null)
                    {
                        identity.AddClaim(new Claim("access_token", context.SecurityToken.RawData));
                    }
                    System.Diagnostics.Debug.WriteLine(context.SecurityToken.RawData + "\n\n");
                }
            };
        });

METHOD FOR SENDING ALL HTTP REQUESTS WITH THE AUTHORIZATION TOKEN.

public async Task<IActionResult> AjaxAction(string url)
    {
        if (User.Claims == null) return null;
        System.Security.Claims.Claim claim = User.Claims.SingleOrDefault(s => s.Type == "access_token");
        if (claim == null) return null;

        HttpClient httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Bearer", claim.Value);
        string url_e = System.Web.HttpUtility.UrlEncode(url);

        HttpResponseMessage response = await httpClient.GetAsync(url);

        // Here we ask the framework to dispose the response object a the end of the user resquest
        HttpContext.Response.RegisterForDispose(response);

        return new HttpResponseMessageResult(response);
    }