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

Posted

技术标签:

【中文标题】.net core 2.2 应用程序的 JWT 身份验证不使用身份【英文标题】:JWT Authentication for .net core 2.2 application not using Identity 【发布时间】:2019-10-30 13:16:11 【问题描述】:

我在这里关注这篇文章:https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login,我遇到了一个障碍,我的 JWT 不记名令牌没有授权我的用户。我得到了一个有效的 JWT - 见截图:

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

这是我在邮递员中获得 401 的屏幕截图。

我已经阅读了这篇文章中的所有 cmets,其他一些因各种原因得到 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】:

我新建了一个全新的项目,一步一步地处理事情,找到了罪魁祸首。原来有两个。

1) 在 VS 2019 中,您必须调试授权才能工作。对此并不超级兴奋。我更希望能够在应用程序运行时授权工作,但不一定要调试 - 如果有解决这个问题的方法,我很想听听。 2) 我在Configure() 中的一些其他声明下方有我的app.UseAuthentication(),显然顺序很重要——谁能解释一下?

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

【讨论】:

啊,是的,这是有道理的。对于问题 2,这是 asp.net 核心处理中间件的方式(几乎整个管道都被视为中间件):docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/… 调试的只是很奇怪,肯定是一个错误? @Ben 一定是……这会让我的集成测试很痛苦。

以上是关于.net core 2.2 应用程序的 JWT 身份验证不使用身份的主要内容,如果未能解决你的问题,请参考以下文章

ASP.NET Core 2.2 JWT 身份验证

C# Jwt 令牌生成失败 asp.net core 2.2

ASP.NET Core 2.2 : 二十七. JWT与用户授权(细化到Action)

使用 Razor 时如何在每个请求处传输 JWT 令牌(.NET CORE 2.2 MVC)

在 ASP .Net Core 2.2 中添加 JWT 令牌后授权不起作用

Auth0 + Swashbuckle .Net Core 2.2。使用 SwaggerUI 时 jwt 令牌中缺少声明