从.NET Core 2.x迁移到.NET 6后出现401未经授权的问题。

huangapple go评论97阅读模式
英文:

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(&quot;init main&quot;);

    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&lt;AuthenticationOptions&gt;(configuration.GetSection(&quot;Authentication&quot;));
    builder.Services.AddSingleton&lt;GraphApiHelper&gt;();
    builder.Services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;();
    builder.Services.AddSingleton&lt;IAuthenticationProvider, OnBehalfOfMsGraphAuthenticationProvider&gt;();

    var context = new CustomAssemblyLoadContext();
    var architectureFolder = (IntPtr.Size == 8) ? &quot;64&quot; : &quot;32&quot;;
    context.LoadUnmanagedLibrary(Path.Combine(System.IO.Directory.GetCurrentDirectory(), $&quot;lib\\{architectureFolder}\\libwkhtmltox.dll&quot;));

    builder.Services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));
    builder.Services.AddTransient&lt;INotificationHelper, NotificationHelper&gt;();
    builder.Services.AddTransient&lt;IReportHelper, ReportHelper&gt;();
    builder.Services.AddTransient&lt;TemplateGenerator, TemplateGenerator&gt;();
    builder.Services.AddTransient&lt;IListOfValuesHelper, ListOfValuesHelper&gt;();
    builder.Services.AddTransient&lt;IInventoryService, InventoryService&gt;();

    builder.Services.AddAuthentication(options =&gt;
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddJwtBearer(options =&gt;
    {
        var authSettings = configuration.GetSection(&quot;MSAuthentication&quot;).Get&lt;AuthenticationOptions&gt;();
        options.TokenValidationParameters = new TokenValidationParameters()
        {
            ValidateIssuer = false,
            ValidAudiences = new List&lt;string&gt; { 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&lt;SubItemService&gt;();
    builder.Services.AddTransient&lt;EstimationHelper&gt;();
    builder.Services.AddTransient&lt;InventoryHelper&gt;();
    builder.Services.AddTransient&lt;UploadCutsHelper&gt;();
    builder.Services.AddTransient&lt;CutsHelper&gt;();
    builder.Services.AddTransient&lt;IStorageService&gt;(provider =&gt;
        new StorageService(configuration.GetValue(&quot;AzureStorage:ConnectionString&quot;, &quot;&quot;)));

    // NLog: Setup NLog for Dependency injection
    builder.Logging.ClearProviders();
    builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
    builder.Host.UseNLog();

    builder.Services.AddCors(options =&gt;
    {
        options.AddPolicy(name: &quot;_myAllowSpecificOrigins&quot;,
            policy =&gt;
            {
                policy.WithOrigins(&quot;https://mysite-qa.azurewebsites.net&quot;)
                .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(&quot;_myAllowSpecificOrigins&quot;);

    app.UseAuthorization();

    app.MapControllers();

    app.Run();
}
catch (Exception ex)
{
    //NLog: catch setup errors
    logger.Error(ex, &quot;Stopped program because of exception&quot;);
    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()

huangapple
  • 本文由 发表于 2023年8月8日 21:38:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76860114.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定