Azure Active Directory:承载错误=“ invalid_token”,error_description =“签名无效”

时间:2020-09-05 15:22:52

标签: c# oauth azure-active-directory

我有一个.net core 3.1网站,该网站使用Active Directory进行身份验证。我可以使用在Azure门户中创建的用户登录。

然后我添加了一个API控制器。

我设法使用以下代码获取令牌:

mny_to_mny

然后我尝试使用以下代码调用端点:

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

与身份验证有关的网站中的startup.cs如下:

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

调用API时出现此错误:

HTTP / 1.1 401未经授权 服务器:Microsoft-IIS / 10.0 WWW-Authenticate:承载错误=“ invalid_token”,error_description =“签名无效”

我已经阅读了大约100个有关如何修复/配置Azure和/或我的应用程序以使其正常运行但没有运气的线程。

有人可以给我任何指示吗?可能是我在Azure中没有/没有正确完成某些事情,或者是我在启动时重新配置了身份验证的方式。我只是找不到问题。

任何指针/帮助将不胜感激。

在回应评论时,我的应用程序注册如下:

enter image description here

作为对人们在Azure配置中帮助我公开API的回应……我在这里似乎没有做任何事情。enter image description here

1 个答案:

答案 0 :(得分:0)

让它正常工作...不确定它是否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;
    }