首页 > 解决方案 > .net core web API not getting authenticated even after generating bearer token from Azure AD using AzureADDefaults.BearerAuthenticationScheme

问题描述

I am developing a .net core Web API and I am trying to authenticate it using AZURE AD authentication. I am following below configurations.:

1.In Startup.cs I have added authentication scheme as :AzureADDefaults.BearerAuthenticationScheme

 services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
              .AddAzureADBearer(options => { Configuration.Bind("AzureAd", options); });

2.In configure method of startup.cs I have added:

app.UseAuthentication();

3.In app.settings.json I have added following properties:

 "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "ClientId": "<MY client ID>",
    "TenantId": "<My Tenant ID>",
    "Issuer": "https://login.microsoftonline.com/<My Tenant ID>/v2.0",
    "Domain": "<My Domain>",
    "ConfigView": "MVC",
    "CallbackPath": "/signin-oidc",
    "ClientSecret": "<My Client Secret>"
  }
  1. I have added Authorize attribute on top of my controller
  2. I have generated my Bearer token using following code:
 static void Main(string[] args)
        {
            Program obj = new Program();
            IRestResponse ARMtokenResponse = obj.GetARMAuthToken();
            dynamic response = JsonConvert.DeserializeObject(ARMtokenResponse.Content);
            Console.WriteLine(response["access_token"].ToString());
            Console.ReadKey();
        }
        private IRestResponse GetARMAuthToken()
        {
            var client = new RestClient("https://login.microsoftonline.com/<MY TENANT ID>/oauth2/token"); //tenantid
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddParameter("grant_type", "client_credentials");
            request.AddParameter("client_id", "<My Client ID>");
            request.AddParameter("client_secret", "<MY CLIENT SECRET>");
            request.AddParameter("resource", "https://management.azure.com/");
            IRestResponse response = client.Execute(request);
            return response;
        }
  1. Further I am using this token generated, in postman/console app for calling the API but getting error in response header: Bearer error="invalid_token", error_description="The audience is invalid"

Please help me in this. I am stuck here

标签: asp.net-coreasp.net-web-apiazure-active-directoryasp.net-core-webapiazure-authentication

解决方案


您的代码中有几个问题:

  1. 您应该获取 web api 的访问令牌,而不是获取 Azure Rest API ( https://management.azure.com/ ) 的访问令牌,您的 web api 无法验证 Azure Rest API 的访问令牌。

  2. 获取令牌时,您使用的是 Azure AD V1.0 端点,但验证令牌时,您使用的是 Azure AD V2.0 端点 ( Issuer)。

对于 Azure AD V1.0,您可以参考代码示例:使用 Azure AD 在 ASP.NET Core Web 应用中调用 Web API

对于 Azure AD V2.0,您可以参考代码示例:使您的 Web 应用能够登录用户并使用面向开发人员的 Microsoft 标识平台调用 API,并按照4-WebApp-your-API场景进行操作。


推荐阅读