英文:
Getting 401 Unauthorized after moving from .NET Core 2.x to .NET 6
问题
在从.NET Core 2.x迁移到.NET 6后,出现401未经授权的错误。将代码从Startup.cs移动到program.cs。
应用程序编译和部署成功。我可以使用我的凭据登录,但一旦开始进行API调用,就会出现401未经授权的错误。
对于我可能遗漏的内容,有什么想法吗?
var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
try
{
logger.Debug("init main");
var builder = WebApplication.CreateBuilder(args);
ConfigurationManager configuration = builder.Configuration; // 允许访问和设置配置
IWebHostEnvironment environment = builder.Environment;
// 将服务添加到容器中。
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDistributedMemoryCache();
//MEW
builder.Services.Configure<AuthenticationOptions>(configuration.GetSection("Authentication"));
builder.Services.AddSingleton<GraphApiHelper>();
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddSingleton<IAuthenticationProvider, OnBehalfOfMsGraphAuthenticationProvider>();
var context = new CustomAssemblyLoadContext();
var architectureFolder = (IntPtr.Size == 8) ? "64" : "32";
context.LoadUnmanagedLibrary(Path.Combine(System.IO.Directory.GetCurrentDirectory(), $"lib\\{architectureFolder}\\libwkhtmltox.dll"));
builder.Services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));
builder.Services.AddTransient<INotificationHelper, NotificationHelper>();
builder.Services.AddTransient<IReportHelper, ReportHelper>();
builder.Services.AddTransient<TemplateGenerator, TemplateGenerator>();
builder.Services.AddTransient<IListOfValuesHelper, ListOfValuesHelper>();
builder.Services.AddTransient<IInventoryService, InventoryService>();
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
var authSettings = configuration.GetSection("MSAuthentication").Get<AuthenticationOptions>();
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = false,
ValidAudiences = new List<string> { authSettings.Audience, authSettings.Authority }
};
options.Authority = authSettings.Authority;
options.Audience = authSettings.Audience;
options.TokenValidationParameters.ValidateLifetime = true;
options.TokenValidationParameters.ClockSkew = TimeSpan.Zero;
options.SaveToken = true;
});
builder.Services.AddAuthorization();
builder.Services.AddTransient<SubItemService>();
builder.Services.AddTransient<EstimationHelper>();
builder.Services.AddTransient<InventoryHelper>();
builder.Services.AddTransient<UploadCutsHelper>();
builder.Services.AddTransient<CutsHelper>();
builder.Services.AddTransient<IStorageService>(provider =>
new StorageService(configuration.GetValue("AzureStorage:ConnectionString", "")));
// NLog: 设置NLog以进行依赖注入
builder.Logging.ClearProviders();
builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
builder.Host.UseNLog();
builder.Services.AddCors(options =>
{
options.AddPolicy(name: "_myAllowSpecificOrigins",
policy =>
{
policy.WithOrigins("https://mysite-qa.azurewebsites.net")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
var app = builder.Build();
// 配置HTTP请求管道。
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("_myAllowSpecificOrigins");
app.UseAuthorization();
app.MapControllers();
app.Run();
}
catch (Exception ex)
{
//NLog: 捕获设置错误
logger.Error(ex, "Stopped program because of exception");
throw;
}
finally
{
// 在应用程序退出之前刷新和停止内部计时器/线程(避免在Linux上出现分段错误)
NLog.LogManager.Shutdown();
}
英文:
Getting 401 Unauthorized after moving from .NET Core 2.x to .NET 6. Moved the code from the Startup.cs to program.cs.
Application compiles and deploys. I'm able to log in with my credentials, but once it starts making API calls, I get a 401 Unauthorized error.
Any ideas on what I could be missing here?
var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
try
{
logger.Debug("init main");
var builder = WebApplication.CreateBuilder(args);
ConfigurationManager configuration = builder.Configuration; // allows both to access and to set up the config
IWebHostEnvironment environment = builder.Environment;
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDistributedMemoryCache();
//MEW
builder.Services.Configure<AuthenticationOptions>(configuration.GetSection("Authentication"));
builder.Services.AddSingleton<GraphApiHelper>();
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddSingleton<IAuthenticationProvider, OnBehalfOfMsGraphAuthenticationProvider>();
var context = new CustomAssemblyLoadContext();
var architectureFolder = (IntPtr.Size == 8) ? "64" : "32";
context.LoadUnmanagedLibrary(Path.Combine(System.IO.Directory.GetCurrentDirectory(), $"lib\\{architectureFolder}\\libwkhtmltox.dll"));
builder.Services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));
builder.Services.AddTransient<INotificationHelper, NotificationHelper>();
builder.Services.AddTransient<IReportHelper, ReportHelper>();
builder.Services.AddTransient<TemplateGenerator, TemplateGenerator>();
builder.Services.AddTransient<IListOfValuesHelper, ListOfValuesHelper>();
builder.Services.AddTransient<IInventoryService, InventoryService>();
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
var authSettings = configuration.GetSection("MSAuthentication").Get<AuthenticationOptions>();
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = false,
ValidAudiences = new List<string> { authSettings.Audience, authSettings.Authority }
};
options.Authority = authSettings.Authority;
options.Audience = authSettings.Audience;
options.TokenValidationParameters.ValidateLifetime = true;
options.TokenValidationParameters.ClockSkew = TimeSpan.Zero;
options.SaveToken = true;
});
builder.Services.AddAuthorization();
builder.Services.AddTransient<SubItemService>();
builder.Services.AddTransient<EstimationHelper>();
builder.Services.AddTransient<InventoryHelper>();
builder.Services.AddTransient<UploadCutsHelper>();
builder.Services.AddTransient<CutsHelper>();
builder.Services.AddTransient<IStorageService>(provider =>
new StorageService(configuration.GetValue("AzureStorage:ConnectionString", "")));
// NLog: Setup NLog for Dependency injection
builder.Logging.ClearProviders();
builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
builder.Host.UseNLog();
builder.Services.AddCors(options =>
{
options.AddPolicy(name: "_myAllowSpecificOrigins",
policy =>
{
policy.WithOrigins("https://mysite-qa.azurewebsites.net")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("_myAllowSpecificOrigins");
app.UseAuthorization();
app.MapControllers();
app.Run();
}
catch (Exception ex)
{
//NLog: catch setup errors
logger.Error(ex, "Stopped program because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();
}
答案1
得分: 1
你需要在 app.UseAuthorization() 之前添加 app.UseAuthentication()。
英文:
You will need app.UseAuthentication() before app.UseAuthorization()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论