c# - JWT 不记名 token 不适用于 ASP.Net Core 3.1 + Identity Server 4

标签 c# asp.net .net jwt asp.net-identity

我目前正在尝试为我正在开发的移动应用程序创建一个 web api。
我决定使用 ASP.Net Core 3.1 和包含的 Indentity Server 来使用 OpenID Connect + PKCE 进行身份验证。
用户将通过 WebView 授权应用程序,访问 token 将用于对 api 的后续调用。 api 的 Controllers 装饰有 [Authorize]属性。
我尝试使用一些脚手架代码进行身份验证,但现在我很挣扎,因为 jwt token 在某些情况下似乎无法识别。
在脚手架代码中,ConfigureServices名为 services.AddDefaultIdentity<ApplicationUser>() 的启动类中的方法.
问题是,这还添加了所有我不需要/不想要的 Identity 的默认端点(/Account/Manage/Disable2fa、/Account/Manage/PersonalData 等)。
因此我将代码改为 services.AddIdentity<ApplicationUser, IdentityRole>() ,因为我现在读了很多遍 AddDefaultIdentity()显然与 AddIdentity() 相同还要打电话.AddDefaultUI()测试登录流程后,发现 api Controller 不再接受 Authorization: Bearer ...进行更改和 api 调用后的标题总是被重定向到登录页面,就好像用户未登录一样
当我将代码改回 AddDefaultIdentity 时,JWT Bearer Token 再次正确验证,我可以使用 [Authorize] 属性访问 Controller ,但随后我再次遇到了默认身份页面的问题......
我的问题是:如何使用 [Authorize] Arribute 和 JWT Bearer Header 保护我的 API Controller ,而不必包含默认的身份 UI?
Startup.cs

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();
            });
        }
    }
}

最佳答案

我设法解决了它🥳
我基本上只是更换

services.AddIdentity<ApplicationUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();
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>();
因为这就是 AddDefaultIdentity() 在没有 UI 部分的情况下在幕后所做的。
现在我的 JWT header 身份验证再次起作用
希望这可以帮助有同样问题的人:)

关于c# - JWT 不记名 token 不适用于 ASP.Net Core 3.1 + Identity Server 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62639951/

相关文章:

c# - 语义相同的两个属性的 TypeId 应该不同还是相同?

c# - 如何让每个开发人员拥有自己的私有(private) web.config?

asp.net - IIS url 重写角色,除了一些 url

javascript - 将参数从链接按钮传递给 JavaScript

asp.net - 回发后动态列消失

asp.net - SMTP 服务器需要安全连接或客户端未通过身份验证

.net - 将 Nunit 测试添加到现有解决方案的公认做法是什么?

c# - 如何将毫秒的日期时间转换为 C# 中的字符串?

c# - 以编程方式运行 T4 文本模板

c# - 从 ContextMenu 实现 "Rename"