如何在身份验证和授权之间使用身份服务器4在asp.net core中添加自定义中间件?
我需要在身份验证和授权之间添加自定义中间件,将 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 ConfigureServices
method
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,确保 TOKEN 中的 Authority 和 ApiName 与 API 中的相同。 (我认为这区分大小写。)这是您尚未提供的内容,因此我无法验证。
另外,在此行之前添加 1 行:
添加以下行:
编辑:同时在启动中删除此行:
这很可能会覆盖您自己的 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:
add the following line:
EDIT: Also remove this line in your startup:
This most likely overrides your own settings for identityserver.