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.