JWT Middleware 未从 OpenIddict Issued JWT 获得声明

JWT Middleware not getting claims from OpenIddict Issued JWT

我正在使用 OpenIddict 为我的水疗中心颁发 JWT 令牌。我发布了 JWT,但我无法使用 JWT 中间件从中获取声明。我已验证声明已正确放入令牌中。注意:我使用的是 EF 6 而我没有使用 Identity

Startup.cs

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; set; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(
                "CorsPolicy",
                builder =>
                builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });

        services.AddTransient<IClaimsPrincipal, CustomClaimsPrincipal>(GetClaimsPrincipalProvider());
        services.AddTransient<ICustomClaimsPrincipal, CustomClaimsPrincipal>(GetClaimsPrincipalProvider());

        services.AddScoped(DbContext);

        services.AddMvc();

        services.AddIdentity<IClaimsPrincipal, ClaimsPrincipal>(config =>
        {
        }).AddDefaultTokenProviders();

    // configure open id
    services.AddOpenIddict()
            .AddCore(opt =>
            {
                opt.UseEntityFramework().UseDbContext<AuthorizationDbContext>();
            })
            .AddServer(opt =>
            {
                opt.UseMvc();

                opt.EnableTokenEndpoint("/api/ping");

                opt.AllowClientCredentialsFlow();

                opt.AllowPasswordFlow();

                opt.DisableHttpsRequirement();
                opt.UseJsonWebTokens();
                opt.AddSigningKey(signingKey);

                opt.AcceptAnonymousClients();
            });

        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
        JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata = false;
                options.SaveToken = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                };
            });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
    {
        app.UseCors("CorsPolicy");
        app.UseStaticFiles();

        app.UseAuthentication();
        app.UseSiteRouteMiddleware();

        app.UseHttpContextLogging();
        app.UseClaimsLogging();
        app.UseMiddleware<ExceptionMiddleware>();

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

令牌控制器:

    [HttpPost]
    [AllowAnonymous]
    public async Task<IActionResult> Post()
    {
        var claims = new List<Claim>
        {
            new Claim(CustomClaimType.LoginName, customClaimsName.LoginName),
            new Claim(CustomClaimType.SiteKey, customClaimsName.SiteKey.ToString()),
            new Claim(CustomClaimType.Id, customClaimsName.PtKey.ToString()),
            new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString(), ClaimValueTypes.Integer64)
        };

        claims.Add(new Claim(OpenIdConnectConstants.Claims.Subject, "Portal"));

        foreach (var x in claims)
            x.SetDestinations(OpenIdConnectConstants.Destinations.AccessToken);

        var identity = new ClaimsIdentity(claims, "OpenIddict");
        var principal = new ClaimsPrincipal(identity);

        // Create a new authentication ticket holding the user identity.
        var ticket = new AuthenticationTicket(
            principal,
            new AuthenticationProperties(),
            OpenIdConnectServerDefaults.AuthenticationScheme);

        // Returning a SignInResult will ask OpenIddict to issue the appropriate access/identity tokens.
        return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
    }
}

当我添加 try to get the claims from User.Claims 时,令牌中没有任何内容。我在中间件或 OpenIddict 配置中缺少什么?

测试控制器

[HttpGet("test")]
[AllowAnonymous]
public IActionResult Get()
{
    var temp = User.Claims;
    return Ok(temp);
}

您的 ASP.NET 核心 JWT 承载处理程序配置无效:它既不使用自动发现(因为 options.Authority 属性 未设置)也不包括令牌验证参数(如发行者、观众和签名密钥)。

由于配置无效,无法应用令牌验证逻辑,User.Claims 始终为空。

设置 options.Authorityoptions.Audience 应该可以。或者,切换回 OpenIddict 验证处理程序和默认令牌格式,提供更简单的配置体验。