【问题标题】:Azure Active Directory: Bearer error="invalid_token", error_description="The signature is invalid"Azure Active Directory: Bearer error="invalid_token", error_description="签名无效"
【发布时间】:2020-12-24 13:47:42
【问题描述】:

我有一个使用 Active Directory 进行身份验证的 .net core 3.1 网站。我可以使用在 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 未经授权 服务器:Microsoft-IIS/10.0 WWW-Authenticate: Bearer error="invalid_token", error_description="签名无效"

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

谁能给我一些建议吗?这可能是我在 Azure 中正确/未正确完成的事情,或者可能是我在启动时重新配置身份验证的方式。我就是找不到问题。

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

作为对评论的回应,我的应用注册如下所示:

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

【问题讨论】:

  • 您是否在应用注册中向客户端公开了您的 API?
  • 您添加的此屏幕截图是 API 权限,这使图形客户端可以根据权限读取详细信息。您能确认一下吗?您在“公开 API”下添加了您的客户端应用注册 ID
  • @Trevor Daniel - 如果你使用 IdentityClient lib 生成访问令牌会发生什么 - github.com/AzureAD/azure-activedirectory-library-for-dotnet/…
  • 我想知道你为什么不使用 Microsoft.Identity.Web。这是一个非常好的代码示例:github.com/Azure-Samples/…
  • @Purushothaman 我已根据您的回复更新了我的问题。再次。非常感谢!

标签: c# oauth azure-active-directory


【解决方案1】:

得到它的工作...不确定它是否 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;
    }

【讨论】:

    猜你喜欢
    • 2018-08-03
    • 2020-06-03
    • 2021-07-26
    • 2020-10-08
    • 2021-09-06
    • 2021-02-06
    • 2020-06-04
    • 2021-08-19
    • 1970-01-01
    相关资源
    最近更新 更多