c# - .net core 2.2 应用程序的 JWT 身份验证不使用身份

标签 c# jwt asp.net-core-2.0 claims-based-identity

我在这里关注这篇文章:https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login我遇到了一个障碍,我的 JWT 不记名 token 未授权我的用户。我获得了有效的 JWT - 请参阅屏幕截图:enter image description here

这是我调用 api 来检索该 token 的屏幕截图: enter image description here

这是我在 postman 中收到 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) 在 VS 2019 中,您必须调试授权才能工作。对此并不太兴奋。我更希望能够在应用程序运行时进行授权工作,但不一定要进行调试 - 如果有解决此问题的方法,我很想听听。 2) 我的 app.UseAuthentication() 位于 Configure() 中的一些其他声明下方,显然顺序很重要 - 谁能解释一下?

我会保留这个,以防其他人遇到这个问题,并且如果有人对我的问题有一些想法 - 请求我很乐意接受教育:)

关于c# - .net core 2.2 应用程序的 JWT 身份验证不使用身份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56622934/

相关文章:

c# - WPF隐藏和显示按钮取决于datacontext的值

Azure AD B2C 图形 API 401 未经授权

c# - 使用 JWT 承载 token 的身份验证 Swagger

c# - ASP.NET Core 中 Func<T> 类型的依赖注入(inject)

javascript - 将特定于 View 的 JavaScript 添加到 Asp.Net Core 2 MVC 应用程序的首选方法是什么?

.net-core - 如何从.netcore中的 token 中删除“http ://schemas. xmlsoap.org/ws/2005/05/identity/urls

c# - Entity Framework 如何在其他查询失败时恢复已执行的查询

c# - C# 的 Winform 控件

c# - 可以在单元测试中使用 fakeiteasy 使用 3 个类型参数调用 "event Action<>"

javascript - 在浏览器中存储 token