【问题标题】:Authorize attribute always returns 401授权属性总是返回 401
【发布时间】:2019-08-10 14:56:31
【问题描述】:

我正在使用客户端凭据/应用身份流 (OAuth 2.0),其中 API 能够通过其应用 ID 对 Web 应用进行身份验证。我需要做两件事来确保身份验证成功:

  1. 从 Web 应用传递来访问 API 的访问令牌应该是有效的不记名令牌(例如:未过期、有效格式等)

  2. 访问令牌中的应用 id 必须是指定的网络应用

当我将 [authorize] 属性放入控制器类时,它一直返回 401。

这里是 startup.cs 类

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddAzureAdBearer(options => Configuration.Bind("AzureAd", options));

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseHttpsRedirection();
            app.UseAuthentication();
            app.UseMvc();
        }

AzureAdAuthenticationBuilderExtentsions 类

public static class AzureAdAuthenticationBuilderExtentsions
    {
        public static AuthenticationBuilder AddAzureAdBearer(this AuthenticationBuilder builder)
        => builder.AddAzureAdBearer(_ => { });

        public static AuthenticationBuilder AddAzureAdBearer(this AuthenticationBuilder builder, Action<AzureAdOptions> configureOptions)
        {
            builder.Services.Configure(configureOptions);
            builder.Services.AddSingleton<IConfigureOptions<JwtBearerOptions>, ConfigureAzureOptions>();
            builder.AddJwtBearer();
            return builder;
        }

        private class ConfigureAzureOptions : IConfigureNamedOptions<JwtBearerOptions>
        {
            private readonly AzureAdOptions _azureOptions;

            public ConfigureAzureOptions(IOptions<AzureAdOptions> azureOptions)
            {
                _azureOptions = azureOptions.Value;
            }

            public void Configure(string name, JwtBearerOptions options)
            {
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidAudiences = new string[] {
                        _azureOptions.ClientId,
                        _azureOptions.ClientIdUrl
                    },
                    ValidateAudience = true,
                    ValidateIssuer = true,
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime = true,
                    RequireExpirationTime = true
                };
                options.Audience = _azureOptions.ClientId;
                options.Authority = $"{_azureOptions.Instance}{_azureOptions.TenantId}";
            }

            public void Configure(JwtBearerOptions options)
            {
                Configure(Options.DefaultName, options);
            }
        }
    }

这是 AzureAdOptions 类

 public class AzureAdOptions
    {
        internal static readonly object Settings;

        public string ClientId { get; set; }

        public string ClientIdUrl { get; set; }

        public string ClientSecret { get; set; }

        public string Instance { get; set; }

        public string Domain { get; set; }

        public string TenantId { get; set; }
    }

和控制器类

  [Route("api")]
    [ApiController]
public class FindController : ControllerBase
{
    private IConfiguration _configuration;
    HttpClient _client;
    public ContentController( IConfiguration configuration)
    {
        _configuration = configuration;
    }

    private bool ValidateRequest()
    {
        var authHeader = Request.Headers["Authorization"];
        if (StringValues.IsNullOrEmpty(authHeader) || authHeader.Count == 0)
        {
            throw new UnauthorizedAccessException(Messages.AuthHeaderIsRequired);
        }
        var tokenWithBearer = authHeader.Single();
        var token = tokenWithBearer.Substring(7); //remove bearer in the token
        var jwtHandler = new JwtSecurityTokenHandler();
        if (!jwtHandler.CanReadToken(token))
        {
            throw new FormatException("Invalid JWT Token");
        }

        var tokenS = jwtHandler.ReadToken(token) as JwtSecurityToken;
        var appId = tokenS.Audiences.First();
        if (string.IsNullOrEmpty(appId))
        {
            throw new UnauthorizedAccessException(Messages.AppIdIsMissing);
        }
        var registeredAppId = _configuration.GetSection("AzureAd:AuthorizedApplicationIdList")?.Get<List<string>>();
        return (registeredAppId.Contains(appId)) ? true : false;
    }
    [HttpPost("Find")]
    [Produces("application/json")]
    [Authorize]
    public async Task<IActionResult> Find()
    {
        try
        {
            if (!ValidateRequest())
            {
                return Unauthorized();
            }
         return new ObjectResult("hello world!");
        }
        catch (InvalidOperationException)
        {
            return null;
        }
    }
}

有人知道为什么它总是返回 401 错误吗?我想提到的一件事是,在我开始调用 API 直到它返回 401 错误之间,控制器类中的断点从未被击中......

【问题讨论】:

  • 您可以发布相关代码,了解如何使用 AAD V1.0 或 v2.0 获取访问令牌?
  • 是的,我意识到我生成访问令牌的方式不正确。我在这里找到了一个教程,但目前无法生成令牌:stackoverflow.com/questions/55252940/…
  • @NanYu 现在可以正确生成访问令牌。谢谢你的帮助。但是 api 仍然在控制器类中返回 401 和 [Authorize] 属性。在 controller 类和 AzureAdAuthenticationBuilderExtentsions 类中没有遇到断点。知道为什么吗?
  • 你的 _azureOptions.ClientId 是什么? api 应用程序的客户端 id ?
  • _azureOptions.ClientId 是我的目标应用程序的应用程序 ID。

标签: c# azure asp.net-core oauth-2.0 azure-active-directory


【解决方案1】:

我会提出 2 点供您检查:

1.在您的代码中检查与 AuthorizedApplicationIdList 匹配的 appID

我认为您描述条件以检查单词的方式很好,但是您在代码中实现第二个条件的方式存在问题。

  1. 访问令牌中的应用 ID 必须是指定的 Web 应用

在实现此条件时,您似乎将 appId 设置为来自 aud 的值,即令牌中的受众声明。这是不正确的,因为受众将始终是您自己的 API,此令牌的目标是。

您要检查的是令牌中appid 声明的值,这将是获取此令牌的客户端的应用程序 ID。这应该是您要对照授权应用程序列表检查的前端 Web 应用程序的应用程序 ID。

看看Microsoft Docs reference for Access Tokens

此外,您可以通过使用https://jwt.ms 解码令牌来轻松验证这一点

我发现问题的帖子中的相关代码

    var appId = tokenS.Audiences.First();
    if (string.IsNullOrEmpty(appId))
    {
        throw new UnauthorizedAccessException(Messages.AppIdIsMissing);
    }
    var registeredAppId = _configuration.GetSection("AzureAd:AuthorizedApplicationIdList")?.Get<List<string>>();
    return (registeredAppId.Contains(appId)) ? true : false;

2。常规日志/调试

另外,附带说明一下,您可能可以在 API 代码中调试或放置日志/跟踪语句,以准确找出代码中出现故障的位置。或者,即使在调用自定义逻辑之前,它是否在某个地方意外失败。也许在执行一些初始验证时。

【讨论】:

  • 嗯,实际上 tokenS 来自网络应用程序。因此,受众将是网络应用的应用 ID,而不是我的 API 的应用 ID。
  • @WWpana 我已经更新了答案以包含来自 Microsoft Docs 的访问令牌的参考,以显示声明 audappid 的描述。我仍然会说观众将是 App ID您的 Web API 的 URI .. 和 appid 将是获取令牌的前端 Web 应用程序的应用程序 ID。检查这一点的一个好方法是解码 jwt.ms 中的令牌我的理解是 Web 应用程序获取Web API 的访问令牌.. 由于访问令牌适用于 Web API,这就是 aud 声称或目标受众所告诉的内容
  • 谢谢,有道理。对于您的第二点,我尝试进行调试,但它从未在控制器类或解决方案中的任何地方遇到我的任何断点。您知道可能导致此问题的原因吗?
  • @WWpana 您拥有 TokenValidationParameters 的初始配置代码将是另一个需要检查的区域。不确定那里是否有断点/日志语句..
  • @WWpana azp 声明将是替代方案。您可能正在使用 v2.0 端点。对于来自 v1 端点 appid 的令牌,声明将提供应用程序 ID,如果是 v2 端点 azp 将执行相同操作。 oid 是代表对象 ID 的不同声明
【解决方案2】:

获取访问api应用的access token时,如果资源是api应用的App ID URI。在api应用程序中,允许的观众还应该包括api应用程序的App ID URI

【讨论】:

    猜你喜欢
    • 2016-05-22
    • 1970-01-01
    • 2014-07-03
    • 2019-08-29
    • 2018-05-19
    • 2018-01-01
    • 1970-01-01
    • 2019-02-01
    • 2017-09-20
    相关资源
    最近更新 更多