JWT 不记名令牌不适用于 ASP.Net Core 3.1 + Identity Server 4

Hen*_*rck 4 .net c# asp.net jwt asp.net-identity

我目前正在尝试为我正在开发的移动应用程序创建一个 web api。我决定使用 ASP.Net Core 3.1 和包含的 Indentity Server 来使用 OpenID Connect + PKCE 进行身份验证。用户将通过 WebView 授权应用程序,访问令牌将用于对 api 的后续调用。api 的 Controllers 用[Authorize]Attribute修饰。

我尝试使用一些脚手架代码进行身份验证,但现在我很挣扎,因为 jwt 令牌在某些情况下似乎无法识别。

在脚手架代码中,ConfigureServices启动类中的方法调用了services.AddDefaultIdentity<ApplicationUser>(). 问题是,这还添加了所有我不需要/不想要的 Identity 的默认端点(/Account/Manage/Disable2fa、/Account/Manage/PersonalData 等)。因此,我更改为代码services.AddIdentity<ApplicationUser, IdentityRole>(),因为我现在阅读了多次,AddDefaultIdentity()显然与AddIdentity()调用相同但也调用.AddDefaultUI()

在测试登录流程后,事实证明 api 控制器Authorization: Bearer ...在进行更改后不再接受Header,并且 api 调用总是被重定向到登录页面,就好像用户没有登录一样

当我将代码改回 AddDefaultIdentity 时,JWT Bearer Token 再次正确验证,我可以使用 [Authorize] 属性访问控制器,但随后我再次遇到了默认身份页面的问题......

我的问题是:如何使用 [Authorize] Arribute 和 JWT Bearer Header 保护我的 API 控制器,而不必包含默认的身份 UI?

启动文件

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Munchify.Web.Data;
using Munchify.Web.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using APIBackend.Web.Services;

namespace APIBackend.Web
{
    public class Startup
    {
        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.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath = "/Identity/Account/Login";
            });

            services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

            services.AddAuthentication()
                .AddIdentityServerJwt();

            services.AddTransient<IEmailSender, EmailSender>();

            services.AddControllersWithViews();
            services.AddRazorPages();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            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.UseRouting();

            app.UseAuthentication();
            app.UseIdentityServer();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Hen*_*rck 5

我设法修复它

我基本上只是更换

services.AddIdentity<ApplicationUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();
Run Code Online (Sandbox Code Playgroud)

services.AddAuthentication(o =>
{
    o.DefaultScheme = IdentityConstants.ApplicationScheme;
    o.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})
.AddIdentityCookies(o => { });

var identityService = services.AddIdentityCore<ApplicationUser>(o =>
{
    o.Stores.MaxLengthForKeys = 128;
    o.SignIn.RequireConfirmedAccount = true;
})
    .AddDefaultTokenProviders()
    .AddEntityFrameworkStores<ApplicationDbContext>();

identityService.AddSignInManager();
identityService.Services.TryAddTransient<IEmailSender, EmailSender>();
Run Code Online (Sandbox Code Playgroud)

因为这就是 AddDefaultIdentity() 在没有 UI 部分的情况下在幕后所做的。

现在我的 JWT 标头身份验证再次起作用

希望这可以帮助有同样问题的人:)