IdentityServer4结合AspNetCore.Identity实现登录认证踩坑填坑记录

文章详细介绍了如何在不使用IdentityServer4.AspNetIdentity的情况下,通过实现IUserClaimsPrincipalFactory接口解决ASP.NET Core身份信息过期导致的登录失败问题,并通过实例演示了相关代码和配置。
部署运行你感兴趣的模型镜像

也可以自定义实现,不使用IdentityServer4.AspNetIdentity这个包,当然还要实现其他接口IResourceOwnerPasswordValidator、 IProfileService等

 

Idr4结合AspNetCore.Identity实现Claims认证需要一个问题:

额外再去去实现IUserClaimsPrincipalFactory接口,为什么要实现这个接口呢?

本生是能够登录的,但是过一段时间就会出现设置value值为null的错误如图

 

 

其实是Claims身份认证信息过期需要重新创建,所以我们要实现IUserClaimsPrincipalFactory接口来实现里面的CreateAsync

public class UserClaimsPrincipal : IUserClaimsPrincipalFactory<IdentityUser>
    {
        private readonly IUserStoreService _storeService;
        public UserClaimsPrincipal(IUserStoreService storeService)
        {
            _storeService = storeService;
        }
        public async Task<ClaimsPrincipal> CreateAsync(IdentityUser user)
        {
            var claims = await _storeService.GetAllClaimsByUser(user);
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims);
            ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
            return await Task.FromResult(claimsPrincipal);

        }
    }

处理如上,处理后一旦身份信息过期就会调用本方法重新创建身份信息

同时我们需要在服务中添加相关服务

services.AddIdentity<IdentityUser, IdentityRole>(options =>
            {
                options.User.RequireUniqueEmail = false;
                options.Password.RequiredLength = 6;
                options.Password.RequireLowercase = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = false;
                options.Password.RequireDigit = false;

            })
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders()
                .AddClaimsPrincipalFactory<UserClaimsPrincipal>();

这里有一个很奇葩的问题 就是在用来 AspNetIdentity 这个包以后,按理说我不需要再去实现 

IResourceOwnerPasswordValidator、 IUserClaimsPrincipalFactory、IProfileService 这些了, 本机调试测试登录都没有问题 但是发布在IIS上依然会出现 Value null的问题

查看Cookie发现 OIDC 中间件的cookies根本没有生成,没办法 我又手动注入了IUserClaimsPrincipalFactory、IProfileService 这个接口及实现,发布后就OK了

 

 但是本机调试运行发现OIDC生成的中间件Cookies 居然是这样

很奇怪~

 GitHub上有简单的例子

https://github.com/woshilangdanger

转载于:https://www.cnblogs.com/liyouming/p/9435941.html

您可能感兴趣的与本文相关的镜像

Llama Factory

Llama Factory

模型微调
LLama-Factory

LLaMA Factory 是一个简单易用且高效的大型语言模型(Large Language Model)训练与微调平台。通过 LLaMA Factory,可以在无需编写任何代码的前提下,在本地完成上百种预训练模型的微调

Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.ISecurityStampValidator Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.SecurityStampValidator`1[Microsoft.AspNetCore.Identity.IdentityUser]': Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IUserStore`1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.ITwoFactorSecurityStampValidator Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.TwoFactorSecurityStampValidator`1[Microsoft.AspNetCore.Identity.IdentityUser]': Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IUserStore`1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory`1[Microsoft.AspNetCore.Identity.IdentityUser] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.UserClaimsPrincipalFactory`2[Microsoft.AspNetCore.Identity.IdentityUser,Microsoft.AspNetCore.Identity.IdentityRole]': Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IUserStore`1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]': Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IUserStore`1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.SignInManager`1[Microsoft.AspNetCore.Identity.IdentityUser] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.SignInManager`1[Microsoft.AspNetCore.Identity.IdentityUser]': Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IUserStore`1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]': Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IRoleStore`1[Microsoft.AspNetCore.Identity.IdentityRole]' while attempting to activate 'Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]'.)”
最新发布
08-15
你遇到的这个错误信息非常长,但它的核心问题是: ``` Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IUserStore<IdentityUser>' while attempting to activate 'Microsoft.AspNetCore.Identity.UserManager<IdentityUser>' ``` --- ## 🚫 错误原因 这个错误表示 **依赖注入容器无法解析 `IUserStore<IdentityUser>` 接口的实现**,也就是说,**Identity 的 Entity Framework 存储服务没有被正确注册**。 这是典型的 **`AddEntityFrameworkStores<TContext>()` 没有被正确调用** 或者 **数据库上下文未正确注册** 所导致的问题。 --- ## ✅ 正确解决方案 ### ✅ 1. 确保你已经注册了数据库上下文(`ApplicationDbContext`) ```csharp builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); ``` ### ✅ 2. 确保你已经正确添加 Identity 并调用了 `.AddEntityFrameworkStores<ApplicationDbContext>()` ```csharp builder.Services.AddIdentity<IdentityUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); ``` > ⚠️ 注意:`ApplicationDbContext` 必须继承自 `IdentityDbContext<IdentityUser>`,而不是 `DbContext`。 --- ## ✅ 3. 确保 `ApplicationDbContext` 正确继承 `IdentityDbContext` ```csharp using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; public class ApplicationDbContext : IdentityDbContext<IdentityUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } } ``` --- ## ✅ 4. 确保你安装了必要的 NuGet 包 ```bash dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore dotnet add package Microsoft.EntityFrameworkCore.SqlServer ``` --- ## ✅ 5. 确保你调用了 `UseAuthentication()` 和 `UseAuthorization()` 中间件 在 `app.UseRouting();` 之后添加: ```csharp app.UseAuthentication(); app.UseAuthorization(); ``` 完整顺序如下: ```csharp app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); ``` --- ## ✅ 示例:完整的 `Program.cs` 配置示例(ASP.NET Core 6+) ```csharp using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using WebApplication1.Data; var builder = WebApplication.CreateBuilder(args); // 1. 添加数据库上下文 builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); // 2. 添加 Identity builder.Services.AddIdentity<IdentityUser, IdentityRole>(options => { options.Password.RequireDigit = true; options.Password.RequireLowercase = true; options.Password.RequireUppercase = true; options.Password.RequireNonAlphanumeric = true; options.Password.RequiredLength = 6; }) .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); var app = builder.Build(); // 3. 使用中间件 app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); // 或者 MapControllerRoute 等 app.Run(); ``` --- ## ✅ 常见错误点总结 | 错误 | 原因 | 解决方法 | |------|------|----------| | 没有注册 `ApplicationDbContext` | DI 容器找不到上下文 | 添加 `AddDbContext<T>` | | 没有调用 `.AddEntityFrameworkStores<TContext>()` | Identity 无法找到存储实现 | 添加 `.AddEntityFrameworkStores<ApplicationDbContext>()` | | `ApplicationDbContext` 继承自 `DbContext` 而不是 `IdentityDbContext` | 无法提供 Identity 所需的 Store | 改为继承 `IdentityDbContext<IdentityUser>` | | 没有安装 `Microsoft.AspNetCore.Identity.EntityFrameworkCore` | 缺少 EF Core 支持 | 安装该包 | | 没有调用 `UseAuthentication()` 和 `UseAuthorization()` | 中间件未启用 | 添加中间件 | --- ##
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值