我试图使用我的自定义IUserStore实现与IdentityServer4 + asp.net Core Identity,我遵循的步骤是创建新的"IdentityServer与asp.net Core Identity"又名is4aspid模板删除EntityFramework资产后,然后我的配置服务看起来像
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddScoped<IIdentityUserRepository<ApplicationUser>, IdentityUserRepository>(); //<-- Repository that I used on CustomUserStore
services.AddDefaultIdentity<ApplicationUser>()
.AddUserStore<CustomUserStore<ApplicationUser>>() //<-- Add
.AddDefaultTokenProviders();
var builder = services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
// see https://identityserver4.readthedocs.io/en/latest/topics/resources.html
options.EmitStaticAudienceClaim = true;
})
.AddInMemoryIdentityResources(Config.IdentityResources)
.AddInMemoryApiScopes(Config.ApiScopes)
.AddInMemoryClients(Config.Clients)
.AddAspNetIdentity<ApplicationUser>();
}
自定义用户存储看起来像
public class CustomUserStore<TUser> :
IUserStore<TUser>,
IUserLoginStore<TUser>,
IUserRoleStore<TUser>,
IUserClaimStore<TUser>,
IUserPasswordStore<TUser>,
IUserSecurityStampStore<TUser>,
IUserEmailStore<TUser>,
IUserLockoutStore<TUser>,
IUserPhoneNumberStore<TUser>
where TUser : ApplicationUser
{
private readonly IIdentityUserRepository<TUser> _userRepository;
public CustomUserStore(IIdentityUserRepository<TUser> userRepository)
{
_userRepository = userRepository;
} //rest of the code hidden sake of brevity
自定义用户商店与默认的asp.net Core身份模板一起工作得很好,但在is4aspid模板中,当我试图摆脱实体框架并将我的自定义商店实现时,登录页面返回404消息,当我试图访问受保护的资源时,但除了这之外,主页工作正常,
下面没有错误消息或日志消息[13:03:04 Information] Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler
AuthenticationScheme: Identity.Application was challenged.
当这些事情发生时没有调用controller或CustomUserStore
我使用的文档
ASP的自定义存储提供者。. NET Core Identity
IdentityServer4使用ASP。. NET Core Identity
编辑:ApplicationUser类是自定义实现,没有任何继承,不像默认的ApplicationUser : IdentityUser
自带模板
我使用这样的代码将我自己的商店添加到IdentityServer:
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(_configuration["ConnectionString"]);
});
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
问题是AddDefaultIdentity
本身,因为它不仅增加了身份组件,还包括UI,我认为问题是由于UI组件随着AddDefaultIdentity
添加,所以当我试图使用项目的视图时,它混淆了框架,解决方案是使用AddIdentity
而不是AddDefaultIdentity
,所以这解决了问题,现在系统无缝工作。