如何在身份验证和授权之间使用身份服务器4在asp.net core中添加自定义中间件?

发布于 2025-01-11 07:55:15 字数 7194 浏览 0 评论 0原文

我需要在身份验证和授权之间添加自定义中间件,将 ClaimsIdentity 添加到上下文中的 User 中。

public class PermissionsMiddleware
    {
        private readonly RequestDelegate _next;

        public PermissionsMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context, IAccountService accountService)
        {
            if (context.User.Identity == null || !context.User.Identity.IsAuthenticated)
            {
                await _next(context);
                return;
            }

            var userSub = context.User.FindFirst(ClaimConstants.Subject)?.Value;
            if (string.IsNullOrEmpty(userSub))
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsync("User 'sub' claim is required");
                return;
            }

            var permissionsIdentity = await accountService.GetUserPermissionsIdentity(userSub);
            if (permissionsIdentity == null)
            {
                context.Response.StatusCode = 401;
                return;
            }

            context.User.AddIdentity(permissionsIdentity);
            await _next(context);
        }
    }

context.User.Identity.IsAuthenticated始终为false

我的 ConfigureServices 方法

string connectionString = Configuration["ConnectionStrings:DefaultConnection"];
        string migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

        services.AddCoreServices();
        services.AddControllers();

        services.AddDbContext<AppDbContext>(
            options => options.UseMySql(
                connectionString,
                ServerVersion.AutoDetect(connectionString),
                b => b.MigrationsAssembly(migrationsAssembly))
            .UseSnakeCaseNamingConvention());
        
        services.AddIdentity<ApplicationUser, ApplicationRole>().AddEntityFrameworkStores<AppDbContext>().AddDefaultTokenProviders();

        services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

        services.AddScoped<IUnitOfWork, UnitOfWork>();
        services.AddScoped<IEmailSender, EmailSender>();
        services.AddScoped<IUnitOfWork, HttpUnitOfWork>();
        services.AddScoped<IAccountManager, AccountManager>();
        services.AddTransient<IDatabaseInitializer, AppDbInitializer>();
        services.AddScoped<IGrantValidationService, DelegationGrantValidationService>();

        services.Configure<AppSettings>(Configuration);

        services.Configure<IdentityOptions>(options =>
        {
            options.User.RequireUniqueEmail = false;
            options.SignIn.RequireConfirmedEmail = false;


            options.Password.RequireDigit = false;
            options.Password.RequiredLength = 1;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = false;
            options.Password.RequireLowercase = false;
        });

        var applicationUrl = Configuration["ApplicationUrl"].TrimEnd('/');

        services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = builder => builder.UseMySql(
                    connectionString,
                    ServerVersion.AutoDetect(connectionString),
                    b => b.MigrationsAssembly(migrationsAssembly))
                .UseSnakeCaseNamingConvention();
            })
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = builder => builder.UseMySql(
                    connectionString,
                    ServerVersion.AutoDetect(connectionString),
                    b => b.MigrationsAssembly(migrationsAssembly))
                .UseSnakeCaseNamingConvention();

                options.EnableTokenCleanup = true;
                options.TokenCleanupInterval = 30;
            })
            .AddAspNetIdentity<ApplicationUser>()
            .AddProfileService<ProfileService<ApplicationUser>>()
            .AddDelegationGrant<ApplicationUser, string>();


        services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = applicationUrl;
                options.SupportedTokens = SupportedTokens.Jwt;
                options.RequireHttpsMetadata = false;
                options.ApiName = IdentityServerConfig.ApiName;
            });

        //services.AddSingleton<IAuthorizationHandler, ViewUserAuthorizationHandler>();
        //services.AddSingleton<IAuthorizationHandler, CreateUserAuthorizationHandler>();
        //services.AddSingleton<IAuthorizationHandler, EditUserAuthorizationHandler>();
        //services.AddSingleton<IAuthorizationHandler, DeleteUserAuthorizationHandler>();

        services.AddSingleton<IAuthorizationHandler, ViewRoleAuthorizationHandler>();
        services.AddSingleton<IAuthorizationHandler, AssignRolesAuthorizationHandler>();

        services.AddAuthorization(options =>
        {
            options.AddPolicy(Policies.ViewUsersPolicy, policy => policy.RequireClaim(ClaimConstants.Permission, ApplicationPermissions.ViewUsers));
            options.AddPolicy(Policies.CreateUsersPolicy, policy => policy.RequireClaim(ClaimConstants.Permission, ApplicationPermissions.CreateUsers));
            options.AddPolicy(Policies.EditUsersPolicy, policy => policy.RequireClaim(ClaimConstants.Permission, ApplicationPermissions.EditUsers));
            options.AddPolicy(Policies.DeleteUsersPolicy, policy => policy.RequireClaim(ClaimConstants.Permission, ApplicationPermissions.DeleteUsers));

            options.AddPolicy(Policies.ViewAllRolesPolicy, policy => policy.RequireClaim(ClaimConstants.Permission, ApplicationPermissions.ViewRoles));
            options.AddPolicy(Policies.ViewRoleByRoleNamePolicy, policy => policy.Requirements.Add(new ViewRoleAuthorizationRequirement()));
            options.AddPolicy(Policies.ManageAllRolesPolicy, policy => policy.RequireClaim(ClaimConstants.Permission, ApplicationPermissions.ManageRoles));

            options.AddPolicy(Policies.AssignAllowedRolesPolicy, policy => policy.Requirements.Add(new AssignRolesAuthorizationRequirement()));
        });

我的 Configure 方法

app.UseCors(x => x.SetIsOriginAllowed(origin => true)
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials());

        app.UseMiddleware<ErrorHandlerMiddleware>();

        //app.UseSwagger();
        //app.UseSwaggerUI();

        app.UseRouting();

        app.UseIdentityServer();
        app.UseMiddleware<PermissionsMiddleware>();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

I need to add custom middleware between authentication and authorization that will add ClaimsIdentity to User that in context.

public class PermissionsMiddleware
    {
        private readonly RequestDelegate _next;

        public PermissionsMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context, IAccountService accountService)
        {
            if (context.User.Identity == null || !context.User.Identity.IsAuthenticated)
            {
                await _next(context);
                return;
            }

            var userSub = context.User.FindFirst(ClaimConstants.Subject)?.Value;
            if (string.IsNullOrEmpty(userSub))
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsync("User 'sub' claim is required");
                return;
            }

            var permissionsIdentity = await accountService.GetUserPermissionsIdentity(userSub);
            if (permissionsIdentity == null)
            {
                context.Response.StatusCode = 401;
                return;
            }

            context.User.AddIdentity(permissionsIdentity);
            await _next(context);
        }
    }

But context.User.Identity.IsAuthenticated is always false.

My ConfigureServicesmethod

string connectionString = Configuration["ConnectionStrings:DefaultConnection"];
        string migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

        services.AddCoreServices();
        services.AddControllers();

        services.AddDbContext<AppDbContext>(
            options => options.UseMySql(
                connectionString,
                ServerVersion.AutoDetect(connectionString),
                b => b.MigrationsAssembly(migrationsAssembly))
            .UseSnakeCaseNamingConvention());
        
        services.AddIdentity<ApplicationUser, ApplicationRole>().AddEntityFrameworkStores<AppDbContext>().AddDefaultTokenProviders();

        services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

        services.AddScoped<IUnitOfWork, UnitOfWork>();
        services.AddScoped<IEmailSender, EmailSender>();
        services.AddScoped<IUnitOfWork, HttpUnitOfWork>();
        services.AddScoped<IAccountManager, AccountManager>();
        services.AddTransient<IDatabaseInitializer, AppDbInitializer>();
        services.AddScoped<IGrantValidationService, DelegationGrantValidationService>();

        services.Configure<AppSettings>(Configuration);

        services.Configure<IdentityOptions>(options =>
        {
            options.User.RequireUniqueEmail = false;
            options.SignIn.RequireConfirmedEmail = false;


            options.Password.RequireDigit = false;
            options.Password.RequiredLength = 1;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = false;
            options.Password.RequireLowercase = false;
        });

        var applicationUrl = Configuration["ApplicationUrl"].TrimEnd('/');

        services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = builder => builder.UseMySql(
                    connectionString,
                    ServerVersion.AutoDetect(connectionString),
                    b => b.MigrationsAssembly(migrationsAssembly))
                .UseSnakeCaseNamingConvention();
            })
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = builder => builder.UseMySql(
                    connectionString,
                    ServerVersion.AutoDetect(connectionString),
                    b => b.MigrationsAssembly(migrationsAssembly))
                .UseSnakeCaseNamingConvention();

                options.EnableTokenCleanup = true;
                options.TokenCleanupInterval = 30;
            })
            .AddAspNetIdentity<ApplicationUser>()
            .AddProfileService<ProfileService<ApplicationUser>>()
            .AddDelegationGrant<ApplicationUser, string>();


        services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = applicationUrl;
                options.SupportedTokens = SupportedTokens.Jwt;
                options.RequireHttpsMetadata = false;
                options.ApiName = IdentityServerConfig.ApiName;
            });

        //services.AddSingleton<IAuthorizationHandler, ViewUserAuthorizationHandler>();
        //services.AddSingleton<IAuthorizationHandler, CreateUserAuthorizationHandler>();
        //services.AddSingleton<IAuthorizationHandler, EditUserAuthorizationHandler>();
        //services.AddSingleton<IAuthorizationHandler, DeleteUserAuthorizationHandler>();

        services.AddSingleton<IAuthorizationHandler, ViewRoleAuthorizationHandler>();
        services.AddSingleton<IAuthorizationHandler, AssignRolesAuthorizationHandler>();

        services.AddAuthorization(options =>
        {
            options.AddPolicy(Policies.ViewUsersPolicy, policy => policy.RequireClaim(ClaimConstants.Permission, ApplicationPermissions.ViewUsers));
            options.AddPolicy(Policies.CreateUsersPolicy, policy => policy.RequireClaim(ClaimConstants.Permission, ApplicationPermissions.CreateUsers));
            options.AddPolicy(Policies.EditUsersPolicy, policy => policy.RequireClaim(ClaimConstants.Permission, ApplicationPermissions.EditUsers));
            options.AddPolicy(Policies.DeleteUsersPolicy, policy => policy.RequireClaim(ClaimConstants.Permission, ApplicationPermissions.DeleteUsers));

            options.AddPolicy(Policies.ViewAllRolesPolicy, policy => policy.RequireClaim(ClaimConstants.Permission, ApplicationPermissions.ViewRoles));
            options.AddPolicy(Policies.ViewRoleByRoleNamePolicy, policy => policy.Requirements.Add(new ViewRoleAuthorizationRequirement()));
            options.AddPolicy(Policies.ManageAllRolesPolicy, policy => policy.RequireClaim(ClaimConstants.Permission, ApplicationPermissions.ManageRoles));

            options.AddPolicy(Policies.AssignAllowedRolesPolicy, policy => policy.Requirements.Add(new AssignRolesAuthorizationRequirement()));
        });

My Configure method

app.UseCors(x => x.SetIsOriginAllowed(origin => true)
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials());

        app.UseMiddleware<ErrorHandlerMiddleware>();

        //app.UseSwagger();
        //app.UseSwaggerUI();

        app.UseRouting();

        app.UseIdentityServer();
        app.UseMiddleware<PermissionsMiddleware>();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不喜欢何必死缠烂打 2025-01-18 07:55:15

首先,确保 TOKEN 中的 Authority 和 ApiName 与 API 中的相同。 (我认为这区分大小写。)这是您尚未提供的内容,因此我无法验证。

另外,在此行之前添加 1 行:

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)

添加以下行:

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

编辑:同时在启动中删除此行:

        app.UseIdentityServer();

这很可能会覆盖您自己的 Identityserver 设置。

First off, make sure the Authority and ApiName are the same in the TOKEN as in your API. (I think this is case sensitive.) This is something you haven't provided so I cannot verify.

Also 1 line before this line:

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)

add the following line:

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

EDIT: Also remove this line in your startup:

        app.UseIdentityServer();

This most likely overrides your own settings for identityserver.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文