Не срабатывает аутентификация/авторизация (JWT) для RequestDelegate

Проект .Net Core. Пытаюсь сделать аутентификацию с использованием JSON Web Token (JWT). Обработчик, ответственный за генерацию токена отрабатывает и возвращает мне токен. Но вот авторизация, судя по всему, не срабатывает - захожу в обработчики запроса (В коде Test1Handle и Test2Handle, которые с атрибутом Authorize) безо всяких преград, даже не получив предварительно токен. При этом свойство Context.User.Identity.Name = null. Пробовал определять явно политику по умолчанию и указывать ее в AuthenticationSchemes атрибута Authorize, увы, не помогло. Код моего StartUp.cs:

using KPAA.Services.AlarmsLibraryService.Authentication;
using KPAA.Services.AlarmsLibraryService.Database;
using KPAA.Services.Base.BaseREST;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;

namespace KPAA.Services.AlarmsLibraryService.REST
{
internal class TestStartup : BaseStartup
{
    private readonly MyContextFactory m_contextFactory;

    public TestStartup(MyContextFactory ContextFactory) : base()
    {
        m_contextFactory = ContextFactory;
    }
    public override void AddRoutes(RouteBuilder routeBuilder)
    {
        routeBuilder.MapRoute("test1", Test1Handle);
        routeBuilder.MapRoute("test2", Test2Handle);
        routeBuilder.MapPost("gettoken", TokenHandler);
        base.AddRoutes(routeBuilder);
    }
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRouting();
        services.AddAuthentication(SetAuthenticationOptions).AddJwtBearer(SetJWTAuthoptions);
        services.AddAuthorization(opts =>
        {
            opts.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser()
            .Build();
        });
    }

    private void SetAuthenticationOptions(AuthenticationOptions opt)
    {
        opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }

    private void SetJWTAuthoptions(JwtBearerOptions opt)
    {
        opt.RequireHttpsMetadata = false;
        
        opt.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = AuthOptions.ISSUER,
            ValidateAudience = true,
            ValidAudience = AuthOptions.AUDIENCE,
            ValidateLifetime = true,
            IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(),
            ValidateIssuerSigningKey = true,
            //ClockSkew = TimeSpan.Zero
        };
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        RouteBuilder routeBuilder = new RouteBuilder(app);
        AddRoutes(routeBuilder);
        app.UseRouter(routeBuilder.Build());

        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();

        app.Run(async (context) =>
        {
            JSONResponse res = new JSONResponse(JSONResponseResult.Error);
            res.Message = string.Format("Route is unknown", context.Request.Path);
            await context.Response.WriteAsync(res.ToJson());
        });
    }

    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    public async Task Test1Handle(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        await context.Response.WriteAsync($"Test1. Identity is {context.User.Identity.Name}");
    }

    [Authorize]
    private async Task Test2Handle(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        await context.Response.WriteAsync($"Test2. Identity is {context.User.Identity.Name}");
    }

    private async Task TokenHandler(HttpContext context)
    {
        Routes.Token.Response response = new Routes.Token.Response(context);
        context.Response.ContentType = "application/json";
        await context.Response.WriteAsync(response.ToJson());
    }
}
}

В чем может быть проблема? Как мне правильно сконфигурировать сервисы, чтобы авторизация стала работать и не пропускать запросы?


Ответы (0 шт):