gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:29:29 26 4
gpt4 key购买 nike

我正在使用客户端凭据/应用程序身份流 (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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com