首页 > 解决方案 > C# 控制台应用程序无法使用 AccessToken 访问 Web Api 总是出现 401 错误

问题描述

我是 Azure 的新手。我在 Azure B2C 中注册了一个应用程序。我正在尝试从 ac# 控制台应用程序(不是 DOT NET 核心)访问我的 web api。

我可以使用下面的代码生成 AccessToken 并成功地从 localhost 访问我的 API。但是,如果我在我的 Web API 操作中添加 [Authorize] 属性,那么我会收到 401 即未经授权的错误。

请看下面我的代码。

            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();
            }

下面是我的 WebApi 控制器代码。

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);
        }        
    }
}

但是如果我在搜索操作中添加 [Authorize](见下文),那么我会收到 401 错误(下面的错误消息)。

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);
        }        
    }
}

错误消息: {StatusCode:401,ReasonPhrase:'未授权',版本:1.1,内容:System.Net.Http.HttpConnectionResponseContent,标头

我不确定在 Azure B2C 中注册我的应用程序时是否遗漏了某些内容,或者缺少某些 Azure B2C 配置,或者我的代码中存在问题。

请求帮助。

标签: c#azureconsole-applicationazure-ad-b2cazure-application-settings

解决方案


推荐阅读