asp.net-core - .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>"
}
- I have added Authorize attribute on top of my controller
- 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;
}
- 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
解决方案
您的代码中有几个问题:
您应该获取 web api 的访问令牌,而不是获取 Azure Rest API ( https://management.azure.com/ ) 的访问令牌,您的 web api 无法验证 Azure Rest API 的访问令牌。
获取令牌时,您使用的是 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
场景进行操作。
推荐阅读
- python - 将不相等的数据框与所有值合并
- angularjs - TypeError:试图分配给“$stateChangeStart”事件参数上的只读属性
- postgresql - 使用 LEFT JOIN 时 Postgres 因分段错误而崩溃
- python - 如何在 Python 中使用 rpy2 访问 R 中的全局环境?
- r - 连续预测变量和参考变量的梯度是否意味着什么?
- android - 活动开始时如何清除物理键盘缓冲区
- android - 领域迁移 - 向现有领域模块添加新类
- excel - 需要帮助清理我当前工作的代码
- shell - 在多个文本文件中查找单词
- c# - 带有 Realm 的 Xamarin.iOS 中的动态类型