JWT中间件未从已发行的JWT的OpenIddict获得索赔

时间:2018-10-24 18:54:41

标签: c# asp.net-core jwt openiddict

我正在使用OpenIddict为我的spa发行JWT令牌。我已经发布了JWT,但是我无法通过JWT中间件解决这些索赔。我已验证索赔已正确放入令牌中。注意:我正在使用EF 6,但没有使用身份

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);
    }
}

当我添加尝试从User.Claims获得声明时,令牌内没有任何内容。我在中间件或OpenIddict配置中缺少什么?

测试控制器

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

1 个答案:

答案 0 :(得分:1)

您的ASP.NET Core JWT承载处理程序配置无效:它既不使用自动发现(因为未设置<td> {{$employee->$manager->name}} </td> 属性),也不包含令牌验证参数(例如颁发者,受众和签名密钥) )。

由于配置无效,因此无法应用令牌验证逻辑,并且options.Authority始终为空。

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