c# - 授权属性始终返回 401

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

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

  1. 从网络应用程序传递来访问 API 的访问 token 应该是有效的不记名 token (例如:未过期、格式有效等)

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

当我将 [authorize] 属性放入 Controller 类中时,它不断返回 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; }
    }

和 Controller 类

  [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 错误之间, Controller 类内的断点从未被命中...

最佳答案

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

关于c# - 授权属性始终返回 401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55251879/

相关文章:

c# - C# 中的文件大小限制或限制

azure - Azure IOT EDGE 路由中加密的消息到 Blob

asp.net-mvc - ASP.NET Core MVC 验证不需要的字段

asp.net-core - 我需要在 ASP.NET Core 中调用 AddMemoryCache 才能让缓存工作吗?

azure - 在两个azure AD之间同步用户

c# - 在 Docker 中创建新的 ASP.NET Core MVC 应用程序时,NuGet 包恢复速度极慢

c# - 无法将 Type 1 隐式转换为 Type 1

c# - 多个查找表的 MVC 核心存储库模式

c# - 在自定义文本框中检测 PropertyChanged

java - Application Insights 支持 java 的多环境