Промежуточное программное обеспечение JWT не получает претензий от OpenIddict, выданного JWT - PullRequest
0 голосов
/ 24 октября 2018

Я использую 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);
    }
}

При добавлении попробуйте получитьутверждает от User.Claims, внутри токена ничего нет.Чего мне не хватает в конфигурации промежуточного ПО или OpenIddict?

Тестовый контроллер

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

1 Ответ

0 голосов
/ 25 октября 2018

Недопустимая конфигурация обработчика канала-носителя JWT в ASP.NET Core: он не использует автоматическое обнаружение (поскольку свойство options.Authority не установлено) и не включает параметры проверки токена (например, эмитента, аудиторию и ключ подписи).

Поскольку конфигурация недопустима, логика проверки токена не может быть применена, и User.Claims всегда пуст.

Установите options.Authority и options.Audience, и это должно работать.Или же вернитесь к обработчику проверки OpenIddict и формату токена по умолчанию, который упрощает настройку.

...