C# .net core 2.2应用程序的JWT身份验证不使用标识

C# .net core 2.2应用程序的JWT身份验证不使用标识,c#,jwt,asp.net-core-2.0,claims-based-identity,C#,Jwt,Asp.net Core 2.0,Claims Based Identity,我在这里关注这篇文章:我遇到了一个障碍,我的JWT承载令牌没有授权我的用户。我得到一个有效的JWT-请参见屏幕截图: 下面是我调用api以检索该令牌的屏幕截图: 这是我在邮递员那里拿到401的截图。 我已经阅读了所有关于这篇文章的评论,还有一些人因为各种原因得到了401分,但我对所有这些问题都感到满意,它们不是我的 想知道另一双眼睛是否有助于发现发生了什么。事实上,我没有使用Identity进行登录。我更喜欢使用我自己的表结构和登录机制,但我不认为这是我的问题的根源 这是我的startup.

我在这里关注这篇文章:我遇到了一个障碍,我的JWT承载令牌没有授权我的用户。我得到一个有效的JWT-请参见屏幕截图:

下面是我调用api以检索该令牌的屏幕截图:

这是我在邮递员那里拿到401的截图。

我已经阅读了所有关于这篇文章的评论,还有一些人因为各种原因得到了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");
            }
        });
    }
}
公共类启动
{
private const string SecretKey=“INIVDMHLPUA2223SQSFHQGBMRDRJ1PVKH”;
私有只读SymmetricSecurityKey _signingKey=新的SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
//在生产中,角度文件将从此目录中提供
services.AddSpaStaticFiles(配置=>
{
configuration.RootPath=“ClientApp/dist”;
});
services.AddDbContext(选项=>
options.UseSqlServer(Configuration.GetConnectionString(“MyHomeBuilderContext”))
);
services.AddSingleton();
services.TryAddTransient();
//jwt接线
//从应用程序设置获取选项
var jwtappsetingoptions=Configuration.GetSection(nameof(jwtissueoptions));
//配置JwtIssuerOptions
配置(选项=>
{
options.Issuer=jwtappsetingoptions[名称(JwtIssuerOptions.Issuer)];
options.audition=jwtappsetingoptions[名称(jwtissueoptions.audition)];
options.SigningCredentials=新的SigningCredentials(_signingKey,SecurityAlgorithms.HmacSha256);
});
var tokenValidationParameters=新的tokenValidationParameters
{
validateisuer=true,
ValidIssuer=jwtAppSettingOptions[名称(JwtIssuerOptions.Issuer)],
ValidateAudience=true,
ValidAudience=jwtAppSettingOptions[名称(JWTissueOptions.Audience)],
ValidateSuersigningKey=true,
IssuerSigningKey=\u signingKey,
RequireExpirationTime=false,
ValidateLifetime=true,
时钟偏移=时间跨度0
};
services.AddAuthentication(选项=>
{
options.DefaultAuthenticateScheme=JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme=JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(配置选项=>
{
configureOptions.claimssuer=jwtappsetingoptions[名称(jwtissueoptions.Issuer)];
configureOptions.TokenValidationParameters=TokenValidationParameters;
configureOptions.SaveToken=true;
});
//api用户声明策略
services.AddAuthorization(选项=>
{
options.AddPolicy(“ApiUser”,policy=>policy.requirecall(Constants.Strings.jwtclaimintifiers.Rol,Constants.Strings.JwtClaims.apicaccess));
});
//从appsettings.json映射电子邮件设置,以便将它们推送到核心项目
services.Configure(Configuration.GetSection(“EmailSettings”))
.AddSingleton(jd=>jd.GetRequiredService().Value);
//从appsettings.json映射推送通知设置,以便将它们推送到核心项目
services.Configure(Configuration.GetSection(“VapidKeys”))
.AddSingleton(jd=>jd.GetRequiredService().Value);
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseExceptionHandler(“/Error”);
//默认的HSTS值为30天。您可能希望在生产场景中更改此值,请参阅https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“默认”,
模板:“{controller}/{action=Index}/{id?}”);
});
app.UseAuthentication();
app.UseSpa(spa=>
{
//要从ASP.NET Core了解更多有关提供角度SPA的选项,
//看https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath=“ClientApp”;
if(env.IsDevelopment())
{
安古拉克利斯温泉酒店