Azure Active Directory:承载错误="invalid_token"、error_description="The signature is invalid"
Azure Active Directory: Bearer error="invalid_token", error_description="The signature is invalid"
我有一个 .net core 3.1 网站,它使用 Active Directory 进行身份验证。我可以使用我在 Azure 门户中创建的用户登录。
然后我添加了一个 API 控制器。
我已成功使用以下代码获得令牌:
public static async Task<ADAuthResponse> GetAuthToken()
{
using HttpClient httpClient = new HttpClient();
StringContent body = new StringContent("client_id=6865ee8xxxxxxx7-9f28-867ff93b079c&scope=user.read%20openid%20profile%20offline_access&username=cardiffwebjob@xxxxxx.onmicrosoft.com&password=!!XXXXX!123&grant_type=password&client_secret=jJg.6mXXXXXXXXX-w-3l9SHv-T", Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage response = await httpClient.PostAsync("https://login.microsoftonline.com/62580128-946f-467b-ae83-7924e7e4fb18/oauth2/v2.0/token", body);
ADAuthResponse result = await JsonSerializer.DeserializeAsync<ADAuthResponse>(await response.Content.ReadAsStreamAsync());
return result;
}
然后我尝试使用此代码调用端点:
public static async Task UpdateWebJobStatus(UpdateFunctionValues updateFunctionValues)
{
// get the auth token
ADAuthResponse authResponse = await GetAuthToken();
using HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResponse.access_token);
StringContent stringContent = new StringContent(JsonSerializer.Serialize(updateFunctionValues), Encoding.UTF8, "application/json");
HttpResponseMessage httpRequestMessage = await httpClient.PostAsync("https://cardiffwebsite.azurewebsites.net/api/DashboardAPI/SetFunctionStatus", stringContent);
}
网站中的控制器如下所示:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[ServiceFilter(typeof(IExceptionFilter))]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
[Route("api/[controller]")]
[ApiController]
public class DashboardAPIController : ControllerBase
{
private readonly BaseContext _db;
private readonly IHubContext<WebJobStatusHub> _hub;
private readonly IHttpContextAccessor _httpContextAccessor;
public DashboardAPIController(BaseContext db, IHubContext<WebJobStatusHub> hubContext, IHttpContextAccessor httpContextAccessor)
{
_db = db;
_hub = hubContext;
_httpContextAccessor = httpContextAccessor;
}
[HttpPost]
[Route("SetFunctionStatus")]
public async Task SetFunctionStatus([FromBody] UpdateFunctionValues updateFunctionValues)
{
WebJobStatusHub hub = new WebJobStatusHub(_db, _hub);
await hub.SendJobStatusUpdate(updateFunctionValues.WebJobId, updateFunctionValues.FunctionId, updateFunctionValues);
}
}
网站中与身份验证相关的 startup.cs 如下所示:
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => _config.Bind("AzureAd", options))
.AddJwtBearer(options =>{
options.Authority = "https://login.microsoftonline.com/62580128-946f-467b-ae83-7924e7e4fb18/";
options.Audience = "f8954991-11xxxxx-73769d3c98cd";
options.TokenValidationParameters.ValidateLifetime = true;
options.TokenValidationParameters.ClockSkew = TimeSpan.Zero;
});
调用 API:
时出现此错误
HTTP/1.1 401 Unauthorized
Server: Microsoft-IIS/10.0
WWW-Authenticate: Bearer error="invalid_token", error_description="The signature is invalid"
我已经阅读了大约 100 个关于如何 fix/configure Azure and/or 我的应用程序以使其正常工作的线程。
谁能给我指点一下?这可能是我 have/have 在 Azure 中没有正确完成的事情,也可能是我在启动时重新配置身份验证的方式。我就是找不到问题。
任何 pointers/help 将不胜感激。
回应这里的评论是我的应用程序注册的样子:
响应人们在 Azure 配置中帮助我公开 API...我似乎没有在这里做任何事情。
成功了...不确定它是否 100% 正确,但这就是我所做的
首先在 Azure 中设置“应用程序注册”并记下客户端 ID 和密码。
然后,在我的网站启动时,我将 startup.cs 更新为如下所示:
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => _config.Bind("AzureAd", options))
.AddJwtBearer(options =>
{
options.Authority = "https://login.microsoftonline.com/TenantIdHere";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateIssuerSigningKey = false,
ValidateLifetime = false,
ValidateActor = false,
ValidateTokenReplay = false
};
});
并像这样装饰 api 控制器:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Authorize(AuthenticationSchemes = AzureADDefaults.AuthenticationScheme)]
[Route("api/[controller]")]
[ApiController]
我得到这样的授权令牌:
public static async Task<ADAuthResponse> GetAuthToken()
{
using HttpClient httpClient = new HttpClient();
// client id and secret from the app registration
byte[] authHeader = Encoding.UTF8.GetBytes("ClientIdHere" + ":" + "ClientSecretHere");
string base64 = Convert.ToBase64String(authHeader);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64);
StringContent body = new StringContent("grant_type=client_credentials&scope=", Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage response = await httpClient.PostAsync("https://login.microsoftonline.com/TenantIdHere/oauth2/token", body);
ADAuthResponse result = await JsonSerializer.DeserializeAsync<ADAuthResponse>(await response.Content.ReadAsStreamAsync());
return result;
}
我有一个 .net core 3.1 网站,它使用 Active Directory 进行身份验证。我可以使用我在 Azure 门户中创建的用户登录。
然后我添加了一个 API 控制器。
我已成功使用以下代码获得令牌:
public static async Task<ADAuthResponse> GetAuthToken()
{
using HttpClient httpClient = new HttpClient();
StringContent body = new StringContent("client_id=6865ee8xxxxxxx7-9f28-867ff93b079c&scope=user.read%20openid%20profile%20offline_access&username=cardiffwebjob@xxxxxx.onmicrosoft.com&password=!!XXXXX!123&grant_type=password&client_secret=jJg.6mXXXXXXXXX-w-3l9SHv-T", Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage response = await httpClient.PostAsync("https://login.microsoftonline.com/62580128-946f-467b-ae83-7924e7e4fb18/oauth2/v2.0/token", body);
ADAuthResponse result = await JsonSerializer.DeserializeAsync<ADAuthResponse>(await response.Content.ReadAsStreamAsync());
return result;
}
然后我尝试使用此代码调用端点:
public static async Task UpdateWebJobStatus(UpdateFunctionValues updateFunctionValues)
{
// get the auth token
ADAuthResponse authResponse = await GetAuthToken();
using HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResponse.access_token);
StringContent stringContent = new StringContent(JsonSerializer.Serialize(updateFunctionValues), Encoding.UTF8, "application/json");
HttpResponseMessage httpRequestMessage = await httpClient.PostAsync("https://cardiffwebsite.azurewebsites.net/api/DashboardAPI/SetFunctionStatus", stringContent);
}
网站中的控制器如下所示:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[ServiceFilter(typeof(IExceptionFilter))]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
[Route("api/[controller]")]
[ApiController]
public class DashboardAPIController : ControllerBase
{
private readonly BaseContext _db;
private readonly IHubContext<WebJobStatusHub> _hub;
private readonly IHttpContextAccessor _httpContextAccessor;
public DashboardAPIController(BaseContext db, IHubContext<WebJobStatusHub> hubContext, IHttpContextAccessor httpContextAccessor)
{
_db = db;
_hub = hubContext;
_httpContextAccessor = httpContextAccessor;
}
[HttpPost]
[Route("SetFunctionStatus")]
public async Task SetFunctionStatus([FromBody] UpdateFunctionValues updateFunctionValues)
{
WebJobStatusHub hub = new WebJobStatusHub(_db, _hub);
await hub.SendJobStatusUpdate(updateFunctionValues.WebJobId, updateFunctionValues.FunctionId, updateFunctionValues);
}
}
网站中与身份验证相关的 startup.cs 如下所示:
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => _config.Bind("AzureAd", options))
.AddJwtBearer(options =>{
options.Authority = "https://login.microsoftonline.com/62580128-946f-467b-ae83-7924e7e4fb18/";
options.Audience = "f8954991-11xxxxx-73769d3c98cd";
options.TokenValidationParameters.ValidateLifetime = true;
options.TokenValidationParameters.ClockSkew = TimeSpan.Zero;
});
调用 API:
时出现此错误HTTP/1.1 401 Unauthorized Server: Microsoft-IIS/10.0 WWW-Authenticate: Bearer error="invalid_token", error_description="The signature is invalid"
我已经阅读了大约 100 个关于如何 fix/configure Azure and/or 我的应用程序以使其正常工作的线程。
谁能给我指点一下?这可能是我 have/have 在 Azure 中没有正确完成的事情,也可能是我在启动时重新配置身份验证的方式。我就是找不到问题。
任何 pointers/help 将不胜感激。
回应这里的评论是我的应用程序注册的样子:
响应人们在 Azure 配置中帮助我公开 API...我似乎没有在这里做任何事情。
成功了...不确定它是否 100% 正确,但这就是我所做的
首先在 Azure 中设置“应用程序注册”并记下客户端 ID 和密码。
然后,在我的网站启动时,我将 startup.cs 更新为如下所示:
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => _config.Bind("AzureAd", options))
.AddJwtBearer(options =>
{
options.Authority = "https://login.microsoftonline.com/TenantIdHere";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateIssuerSigningKey = false,
ValidateLifetime = false,
ValidateActor = false,
ValidateTokenReplay = false
};
});
并像这样装饰 api 控制器:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Authorize(AuthenticationSchemes = AzureADDefaults.AuthenticationScheme)]
[Route("api/[controller]")]
[ApiController]
我得到这样的授权令牌:
public static async Task<ADAuthResponse> GetAuthToken()
{
using HttpClient httpClient = new HttpClient();
// client id and secret from the app registration
byte[] authHeader = Encoding.UTF8.GetBytes("ClientIdHere" + ":" + "ClientSecretHere");
string base64 = Convert.ToBase64String(authHeader);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64);
StringContent body = new StringContent("grant_type=client_credentials&scope=", Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage response = await httpClient.PostAsync("https://login.microsoftonline.com/TenantIdHere/oauth2/token", body);
ADAuthResponse result = await JsonSerializer.DeserializeAsync<ADAuthResponse>(await response.Content.ReadAsStreamAsync());
return result;
}