Аутентификация JWT для приложения .net core 2.2, не использующего Identity - PullRequest
0 голосов
/ 17 июня 2019

Я слежу за этой статьей здесь: https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login, и я столкнулся с проблемой, когда мой токен-носитель JWT не авторизует моего пользователя.Я получил действительный JWT - см. Скриншот: enter image description here

вот скриншот того, как я вызываю API для получения этого токена: enter image description here

И вот скриншот того, как я получаю 401 в почтальоне.enter image description here

Я прочитал все комментарии к статье, а некоторые другие получали 401-е по разным причинам, но я удовлетворил все эти проблемы, и они немой.

Интересно, может ли другой набор глаз помочь определить, что происходит?Впрочем, я не использую Identity для входа в систему.Для этого я предпочитаю использовать собственную структуру таблиц и механизм входа, но я не думаю, что это является источником моей проблемы.

Вот мой файл startup.cs.Что-нибудь здесь выпрыгивает?Не совсем уверен, куда идти дальше.

public class Startup
{
    private const string SecretKey = "iNivDmHLpUA223sqsfhqGbMRdRj1PVkH";
    private readonly SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        // In production, the Angular files will be served from this directory
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/dist";
        });

        services.AddDbContext<MyHomeBuilderContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("MyHomeBuilderContext"))
        );

        services.AddSingleton<IJwtFactory, JwtFactory>();

        services.TryAddTransient<IHttpContextAccessor, HttpContextAccessor>();

        // jwt wire up
        // Get options from app settings
        var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

        // Configure JwtIssuerOptions
        services.Configure<JwtIssuerOptions>(options =>
        {
            options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
            options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
            options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
        });

        var tokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

            ValidateAudience = true,
            ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

            ValidateIssuerSigningKey = true,
            IssuerSigningKey = _signingKey,

            RequireExpirationTime = false,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero
        };

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

        }).AddJwtBearer(configureOptions =>
        {
            configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
            configureOptions.TokenValidationParameters = tokenValidationParameters;
            configureOptions.SaveToken = true;
        });

        // api user claim policy
        services.AddAuthorization(options =>
        {
            options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
        });

        // map the email settings from appsettings.json so they can be pushed to the core project
        services.Configure<EmailSettingsModel>(Configuration.GetSection("EmailSettings"))
            .AddSingleton(jd => jd.GetRequiredService<IOptions<EmailSettingsModel>>().Value);

        // map the push notification settings from appsettings.json so they can be pushed to the core project
        services.Configure<PushSettingsModel>(Configuration.GetSection("VapidKeys"))
            .AddSingleton(jd => jd.GetRequiredService<IOptions<PushSettingsModel>>().Value);

        services.AddTransient<IEmailService, EmailService>();
        services.AddTransient<IPushService, PushService>();

        services.AddTransient<IUserRepository, UserRepositoryEFDatabase>();
        services.AddTransient<IUserService, UserService>();
        services.AddTransient<IAdapter<UserModel, User>, UserAdapter>();

        services.AddTransient<IProjectRepository, ProjectRepositoryEFDatabase>();
        services.AddTransient<IProjectService, ProjectService>();
        services.AddTransient<IAdapter<ProjectModel, Project>, ProjectAdapter>();

        services.AddTransient<IProjectFileBucketRepository, ProjectFileBucketRepositoryEFDatabase>();
        services.AddTransient<IProjectFileBucketService, ProjectFileBucketService>();
        services.AddTransient<IAdapter<ProjectFileBucketModel, ProjectFileBucket>, ProjectFileBucketAdapter>();

        services.AddTransient<IProjectFileRepository, ProjectFileRepositoryEFDatabase>();
        services.AddTransient<IProjectFileService, ProjectFileService>();
        services.AddTransient<IAdapter<ProjectFileModel, ProjectFile>, ProjectFileAdapter>();

        services.AddTransient<IDeviceRepository, DeviceRepositoryEFDatabase>();
        services.AddTransient<IDeviceService, DeviceService>();
        services.AddTransient<IAdapter<DeviceModel, Device>, DeviceAdapter>();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseSpaStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action=Index}/{id?}");
        });
        app.UseAuthentication();
        app.UseSpa(spa =>
        {
            // To learn more about options for serving an Angular SPA from ASP.NET Core,
            // see https://go.microsoft.com/fwlink/?linkid=864501

            spa.Options.SourcePath = "ClientApp";

            if (env.IsDevelopment())
            {
                spa.UseAngularCliServer(npmScript: "start");
            }
        });
    }
}

1 Ответ

0 голосов
/ 17 июня 2019

Я защитил целиком новый проект, шаг за шагом прошел через все и нашел виновника.Оказывается, на самом деле их два.

1) В VS 2019 вы должны отлаживать, чтобы авторизация работала.Не супер взволнован об этом.Я бы предпочел, чтобы авторизация работала с запущенным приложением, но не обязательно отлаживала - если есть способ обойти это, я бы хотел услышать об этом.2) У меня было app.UseAuthentication() ниже некоторых других моих деклараций в Configure(), и, очевидно, порядок имеет значение - кто-нибудь может объяснить это?

Я оставлю это, если кто-то еще столкнется с этой проблемой, и еслиу кого-нибудь есть идеи по моим вопросам - просьба, я бы хотел получить образование :)

...