You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 3.1升级到.NET 8后Docker中JWT认证失效求助

.NET Core 3.1升级到.NET 8预览版后Docker容器中JWT认证失效

我把ASP.NET Core Web API从.NET Core 3.1升级到.NET 8(版本v8.0.100-preview.5.23303.2)后,在Docker容器里运行时JWT认证功能失效了。

JWT令牌由一个我拿不到源码的服务生成,我的项目需要验证这个令牌来实现授权。项目是通过.NET Upgrade Assistant完成升级的,在Windows本地运行完全正常,但放到Docker容器里就一直返回“Invalid-Token”(HTTP状态码是200)。我试过用JWTBearer 3.1.1版本替换预览版,也参考相关问题调整了Startup.cs,但问题还是没解决。

以下是相关代码文件:

Startup.cs

using System.Net;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using AppName.Models;

namespace AppName
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = new BaseUrls().getJwtIssuer(),
                        ValidAudience = new BaseUrls().getJwtAudience(),
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(new BaseUrls().getJwtKey()))
                    };
                });
            services.AddControllersWithViews();
            services.AddMemoryCache();
            services
                .AddMvc(option => option.EnableEndpointRouting = false)
                .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver())
                .AddNewtonsoftJson(options => options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local);
            services.AddSession();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStatusCodePages(async context => 
            {
                var request = context.HttpContext.Request;
                var response = context.HttpContext.Response;

                if (response.StatusCode == (int)HttpStatusCode.Unauthorized)
                {
                    response.Redirect("/account/login");
                }
            });

            app.UseAuthentication();
            app.UseAuthorization();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

.csproj

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <ServerGarbageCollection>false</ServerGarbageCollection>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="EFCore.BulkExtensions" Version="3.1.0" />
    <PackageReference Include="Microsoft.Extensions.Caching.Redis" Version="2.2.0" />
    <PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.31.0" />
    <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.31.0" />
    <PackageReference Include="Flurl.Http" Version="2.4.1" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.DataProtection" Version="8.0.0-preview.5.23302.2" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.0-preview.5.23302.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.0-preview.5.23280.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="8.0.0-preview.5.23280.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.0-preview.5.23280.1" />
    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
  </ItemGroup>
</Project>

Dockerfile

FROM mcr.microsoft.com/dotnet/aspnet:8.0.0-preview.5-jammy-amd64 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:8.0.100-preview.5-jammy-amd64 AS build
WORKDIR /src
COPY ["AppName/AppName.csproj", "AppName/"]
RUN dotnet restore "AppName/AppName.csproj"
COPY . .
RUN find -type d -name bin -prune -exec rm -rf {} \; && find -type d -name obj -prune -exec rm -rf {} \;
WORKDIR "/src/AppName"
RUN dotnet build "AppName.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "AppName.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "AppName.dll"]

内容的提问来源于stack exchange,提问作者user22145594

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 02:12:03