identity4 系列————用户数据持久化篇[六]

前言

前面的例子已经将各种情形下的例子已经介绍了一遍,那么后面就是用户数据持久化该如何处理了。

正文

例子位置:

https://github.com/IdentityServer/IdentityServer4/tree/main/samples/Quickstarts/6_AspNetIdentity

里面介绍如何将用户数据持久化到数据库。

  1. 配置数据库
services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

然后添加认证服务:

services.AddIdentity<ApplicationUser, IdentityRole>()
			.AddEntityFrameworkStores<ApplicationDbContext>()
			.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>();

这样其实就可以了。

  1. 初始化数据
public static void EnsureSeedData(string connectionString)
{
	var services = new ServiceCollection();
	services.AddLogging();
	services.AddDbContext<ApplicationDbContext>(options =>
	   options.UseSqlite(connectionString));

	services.AddIdentity<ApplicationUser, IdentityRole>()
		.AddEntityFrameworkStores<ApplicationDbContext>()
		.AddDefaultTokenProviders();

	using (var serviceProvider = services.BuildServiceProvider())
	{
		using (var scope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
		{
			var context = scope.ServiceProvider.GetService<ApplicationDbContext>();
			context.Database.Migrate();

			var userMgr = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
			var alice = userMgr.FindByNameAsync("alice").Result;
			if (alice == null)
			{
				alice = new ApplicationUser
				{
					UserName = "alice",
					Email = "AliceSmith@email.com",
					EmailConfirmed = true,
				};
				var result = userMgr.CreateAsync(alice, "Pass123$").Result;
				if (!result.Succeeded)
				{
					throw new Exception(result.Errors.First().Description);
				}

				result = userMgr.AddClaimsAsync(alice, new Claim[]{
					new Claim(JwtClaimTypes.Name, "Alice Smith"),
					new Claim(JwtClaimTypes.GivenName, "Alice"),
					new Claim(JwtClaimTypes.FamilyName, "Smith"),
					new Claim(JwtClaimTypes.WebSite, "http://alice.com"),
				}).Result;
				if (!result.Succeeded)
				{
					throw new Exception(result.Errors.First().Description);
				}
				Log.Debug("alice created");
			}
			else
			{
				Log.Debug("alice already exists");
			}

			var bob = userMgr.FindByNameAsync("bob").Result;
			if (bob == null)
			{
				bob = new ApplicationUser
				{
					UserName = "bob",
					Email = "BobSmith@email.com",
					EmailConfirmed = true
				};
				var result = userMgr.CreateAsync(bob, "Pass123$").Result;
				if (!result.Succeeded)
				{
					throw new Exception(result.Errors.First().Description);
				}

				result = userMgr.AddClaimsAsync(bob, new Claim[]{
					new Claim(JwtClaimTypes.Name, "Bob Smith"),
					new Claim(JwtClaimTypes.GivenName, "Bob"),
					new Claim(JwtClaimTypes.FamilyName, "Smith"),
					new Claim(JwtClaimTypes.WebSite, "http://bob.com"),
					new Claim("location", "somewhere")
				}).Result;
				if (!result.Succeeded)
				{
					throw new Exception(result.Errors.First().Description);
				}
				Log.Debug("bob created");
			}
			else
			{
				Log.Debug("bob already exists");
			}
		}
	}
}

里面就不多介绍了,就是如果不存在就数据。

下一节介绍各个表的作用。

posted @ 2022-08-28 17:03  敖毛毛  阅读(245)  评论(2编辑  收藏  举报