0

I am a newbie in Azure. I have registered an application in Azure B2C. And I am trying to access my web api from a c# console application (not DOT NET core).

I can generate AccessToken using below code and access my API from localhost successfully. But if I add [Authorize] attribute in my Web API Action then I am getting 401 i.e. Unauthorized error.

Please see below my code.

            string clientId = "{client Id of the application that I have registered using azure app registration in Azure B2C}";
            string clientSecret = "{client secret of the application that I have registered using azure app registration in Azure B2C}";
            string instance = "https://login.microsoftonline.com/{0}/";
            string tenantId = "{Tenant Id that I can see when I open the application that I have registered using azure app registration in Azure B2C}";           

            IConfidentialClientApplication app;

            app = ConfidentialClientApplicationBuilder.Create(clientId)
                    .WithClientSecret(clientSecret)
                    .WithAuthority(AzureCloudInstance.AzurePublic, tenantId)
                    .Build();

            string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
            AuthenticationResult result = null;
            result = await app.AcquireTokenForClient(scopes)
                   .ExecuteAsync();

            if (result != null)
            {
                var httpClient = new HttpClient();
                var apiCaller = new ProtectedApiCallHelper(httpClient);

                string webApiUrl = "http://localhost:51615/Sample/apis/Sample/Customers/Search";

                var defaultRequetHeaders = httpClient.DefaultRequestHeaders;
                if (defaultRequetHeaders.Accept == null || !defaultRequetHeaders.Accept.Any(m => m.MediaType == "application/json"))
                {
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }
                defaultRequetHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

                HttpResponseMessage response = await httpClient.GetAsync(webApiUrl);
                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadAsStringAsync();
                    var jsonResult = JsonConvert.DeserializeObject<List<JObject>>(json);
                }
                else
                {
                    Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
                    string content = await response.Content.ReadAsStringAsync();
                }
                Console.ResetColor();
            }

Below is my WebApi Controller code.

namespace PccNet.Web.Sample.Api.Controllers
{
    [RoutePrefix("apis/Sample/Customers")]
    public class SampleCustomersApiController : ApiController
    {
        [HttpGet]
        [Route("Search")] 
        public IHttpActionResult Search()
        {
            var customers = ReadCustomers();
            return Json(customers);
        }        
    }
}

But If I add [Authorize] on Search action (see below) then I am getting 401 error (Error Message below).

namespace PccNet.Web.Sample.Api.Controllers
{
    [RoutePrefix("apis/Sample/Customers")]
    public class SampleCustomersApiController : ApiController
    {
        [Authorize]
        [HttpGet]
        [Route("Search")] 
        public IHttpActionResult Search()
        {
            var customers = ReadCustomers();
            return Json(customers);
        }        
    }
}

Error Message: {StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers

I am not sure I have missed something while registering my Application in Azure B2C or some Azure B2C configuration is missing or the issue exist in my code.

Requesting for help.

  • You are trying to access your web API. But the `scope` you set is `https://graph.microsoft.com/.default`. You should modify it to `https://{B2C tenant}.onmicrosoft.com/api/{some scope}`. See https://learn.microsoft.com/en-us/azure/active-directory-b2c/add-web-api-application?tabs=app-reg-ga#configure-scopes. – Allen Wu Jun 19 '20 at 01:21
  • Hi Allen, Thanks. tried with scope "https://{B2C Tenant}.onmicrosoft.com/api/.default" but getting same 401 error. And if use "https://{B2C Tenant}.onmicrosoft.com/api/read" then getting error "The resource principal named https://{B2C Tenant}.onmicrosoft.com/api/read was not found in the tenant named.." – – S Chatterjee Jun 20 '20 at 07:45
  • Make sure that you have exposed an api named ` https://{B2C Tenant}.onmicrosoft.com/api/read` in the API AAD application and grant permissions for this api in the Client AAD application. The 2 steps are in the link I provide above. – Allen Wu Jun 22 '20 at 02:46

0 Answers0