【发布时间】:2020-08-10 14:11:35
【问题描述】:
我正在开发一个 .net 核心 Web API,并尝试使用 AZURE AD 身份验证对其进行身份验证。 我遵循以下配置。:
1.在 Startup.cs 我添加了身份验证方案:AzureADDefaults.BearerAuthenticationScheme
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => { Configuration.Bind("AzureAd", options); });
2.在startup.cs的configure方法中我添加了:
app.UseAuthentication();
3.在 app.settings.json 我添加了以下属性:
"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>"
}
- 我在控制器顶部添加了 Authorize 属性
- 我使用以下代码生成了我的 Bearer 令牌:
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;
}
- 此外,我正在使用在邮递员/控制台应用程序中生成的此令牌来调用 API,但在响应标头中出现错误:Bearer error="invalid_token", error_description="观众无效"
请帮助我。我被困在这里了
【问题讨论】:
标签: asp.net-core asp.net-web-api azure-active-directory asp.net-core-webapi azure-authentication