授权属性始终返回401

时间:2019-03-20 00:26:31

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

我正在使用客户端证书/应用程序身份流(OAuth 2.0),其中API能够通过其应用程序ID来验证网络应用程序。我需要确保身份验证成功的两件事:

  1. 从Web应用传递的用于访问API的访问令牌应该是有效的承载令牌(例如:未过期,有效格式等)

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

当我将[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错误之间,控制器类内的断点从未被击中...

2 个答案:

答案 0 :(得分:1)

我想给您2分,以供您检查:

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

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

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

实施此条件时,似乎您要将appId设置为aud中的值,即受众群体以令牌声明。这是不正确的,因为受众将始终是此令牌用于的自己的API。

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

看看Microsoft Docs reference for Access Tokens

enter image description here

enter image description here

此外,您可以通过使用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代码中放入log / trace语句,以准确找出代码中发生故障的位置..甚至在调用自定义逻辑之前,它是否意外地出现故障。也许正在执行一些初始验证时。

答案 1 :(得分:1)

在获取用于访问api应用程序的访问令牌时,如果资源是api应用程序的App ID URI。在api应用程序中,允许的访问者还应包括api应用程序的App ID URI

相关问题